getopt.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. /* Getopt for GNU.
  2. NOTE: getopt is now 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-2022 Free Software Foundation, Inc.
  6. NOTE: This source is derived from an old version taken from the GNU C
  7. Library (glibc).
  8. This program is free software; you can redistribute it and/or modify it
  9. under the terms of the GNU General Public License as published by the
  10. Free Software Foundation; either version 2, or (at your option) any
  11. 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, write to the Free Software
  18. Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301,
  19. USA. */
  20. /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
  21. Ditto for AIX 3.2 and <stdlib.h>. */
  22. #ifndef _NO_PROTO
  23. # define _NO_PROTO
  24. #endif
  25. #ifdef HAVE_CONFIG_H
  26. # include <config.h>
  27. #endif
  28. #if !defined __STDC__ || !__STDC__
  29. /* This is a separate conditional since some stdc systems
  30. reject `defined (const)'. */
  31. # ifndef const
  32. # define const
  33. # endif
  34. #endif
  35. #include "ansidecl.h"
  36. #include <stdio.h>
  37. /* Comment out all this code if we are using the GNU C Library, and are not
  38. actually compiling the library itself. This code is part of the GNU C
  39. Library, but also included in many other GNU distributions. Compiling
  40. and linking in this code is a waste when using the GNU C library
  41. (especially if it is a shared library). Rather than having every GNU
  42. program understand `configure --with-gnu-libc' and omit the object files,
  43. it is simpler to just do this in the source for each such file. */
  44. #define GETOPT_INTERFACE_VERSION 2
  45. #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
  46. # include <gnu-versions.h>
  47. # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
  48. # define ELIDE_CODE
  49. # endif
  50. #endif
  51. #ifndef ELIDE_CODE
  52. /* This needs to come after some library #include
  53. to get __GNU_LIBRARY__ defined. */
  54. #ifdef __GNU_LIBRARY__
  55. /* Don't include stdlib.h for non-GNU C libraries because some of them
  56. contain conflicting prototypes for getopt. */
  57. # include <stdlib.h>
  58. # include <unistd.h>
  59. #endif /* GNU C library. */
  60. #ifdef VMS
  61. # include <unixlib.h>
  62. # if HAVE_STRING_H - 0
  63. # include <string.h>
  64. # endif
  65. #endif
  66. #ifndef _
  67. /* This is for other GNU distributions with internationalized messages.
  68. When compiling libc, the _ macro is predefined. */
  69. # if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC
  70. # include <libintl.h>
  71. # define _(msgid) gettext (msgid)
  72. # else
  73. # define _(msgid) (msgid)
  74. # endif
  75. #endif
  76. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  77. but it behaves differently for the user, since it allows the user
  78. to intersperse the options with the other arguments.
  79. As `getopt' works, it permutes the elements of ARGV so that,
  80. when it is done, all the options precede everything else. Thus
  81. all application programs are extended to handle flexible argument order.
  82. Setting the environment variable POSIXLY_CORRECT disables permutation.
  83. Then the behavior is completely standard.
  84. GNU application programs can use a third alternative mode in which
  85. they can distinguish the relative order of options and other arguments. */
  86. #include "getopt.h"
  87. /* For communication from `getopt' to the caller.
  88. When `getopt' finds an option that takes an argument,
  89. the argument value is returned here.
  90. Also, when `ordering' is RETURN_IN_ORDER,
  91. each non-option ARGV-element is returned here. */
  92. char *optarg = NULL;
  93. /* Index in ARGV of the next element to be scanned.
  94. This is used for communication to and from the caller
  95. and for communication between successive calls to `getopt'.
  96. On entry to `getopt', zero means this is the first call; initialize.
  97. When `getopt' returns -1, this is the index of the first of the
  98. non-option elements that the caller should itself scan.
  99. Otherwise, `optind' communicates from one call to the next
  100. how much of ARGV has been scanned so far. */
  101. /* 1003.2 says this must be 1 before any call. */
  102. int optind = 1;
  103. /* Formerly, initialization of getopt depended on optind==0, which
  104. causes problems with re-calling getopt as programs generally don't
  105. know that. */
  106. int __getopt_initialized = 0;
  107. /* The next char to be scanned in the option-element
  108. in which the last option character we returned was found.
  109. This allows us to pick up the scan where we left off.
  110. If this is zero, or a null string, it means resume the scan
  111. by advancing to the next ARGV-element. */
  112. static char *nextchar;
  113. /* Callers store zero here to inhibit the error message
  114. for unrecognized options. */
  115. int opterr = 1;
  116. /* Set to an option character which was unrecognized.
  117. This must be initialized on some systems to avoid linking in the
  118. system's own getopt implementation. */
  119. int optopt = '?';
  120. /* Describe how to deal with options that follow non-option ARGV-elements.
  121. If the caller did not specify anything,
  122. the default is REQUIRE_ORDER if the environment variable
  123. POSIXLY_CORRECT is defined, PERMUTE otherwise.
  124. REQUIRE_ORDER means don't recognize them as options;
  125. stop option processing when the first non-option is seen.
  126. This is what Unix does.
  127. This mode of operation is selected by either setting the environment
  128. variable POSIXLY_CORRECT, or using `+' as the first character
  129. of the list of option characters.
  130. PERMUTE is the default. We permute the contents of ARGV as we scan,
  131. so that eventually all the non-options are at the end. This allows options
  132. to be given in any order, even with programs that were not written to
  133. expect this.
  134. RETURN_IN_ORDER is an option available to programs that were written
  135. to expect options and other ARGV-elements in any order and that care about
  136. the ordering of the two. We describe each non-option ARGV-element
  137. as if it were the argument of an option with character code 1.
  138. Using `-' as the first character of the list of option characters
  139. selects this mode of operation.
  140. The special argument `--' forces an end of option-scanning regardless
  141. of the value of `ordering'. In the case of RETURN_IN_ORDER, only
  142. `--' can cause `getopt' to return -1 with `optind' != ARGC. */
  143. static enum
  144. {
  145. REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
  146. } ordering;
  147. /* Value of POSIXLY_CORRECT environment variable. */
  148. static char *posixly_correct;
  149. #ifdef __GNU_LIBRARY__
  150. /* We want to avoid inclusion of string.h with non-GNU libraries
  151. because there are many ways it can cause trouble.
  152. On some systems, it contains special magic macros that don't work
  153. in GCC. */
  154. # include <string.h>
  155. # define my_index strchr
  156. #else
  157. # if HAVE_STRING_H
  158. # include <string.h>
  159. # else
  160. # if HAVE_STRINGS_H
  161. # include <strings.h>
  162. # endif
  163. # endif
  164. /* Avoid depending on library functions or files
  165. whose names are inconsistent. */
  166. #if HAVE_STDLIB_H && HAVE_DECL_GETENV
  167. # include <stdlib.h>
  168. #elif !defined(getenv)
  169. # ifdef __cplusplus
  170. extern "C" {
  171. # endif /* __cplusplus */
  172. extern char *getenv (const char *);
  173. # ifdef __cplusplus
  174. }
  175. # endif /* __cplusplus */
  176. #endif
  177. static char *
  178. my_index (const char *str, int chr)
  179. {
  180. while (*str)
  181. {
  182. if (*str == chr)
  183. return (char *) str;
  184. str++;
  185. }
  186. return 0;
  187. }
  188. /* If using GCC, we can safely declare strlen this way.
  189. If not using GCC, it is ok not to declare it. */
  190. #ifdef __GNUC__
  191. /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
  192. That was relevant to code that was here before. */
  193. # if (!defined __STDC__ || !__STDC__) && !defined strlen
  194. /* gcc with -traditional declares the built-in strlen to return int,
  195. and has done so at least since version 2.4.5. -- rms. */
  196. extern int strlen (const char *);
  197. # endif /* not __STDC__ */
  198. #endif /* __GNUC__ */
  199. #endif /* not __GNU_LIBRARY__ */
  200. /* Handle permutation of arguments. */
  201. /* Describe the part of ARGV that contains non-options that have
  202. been skipped. `first_nonopt' is the index in ARGV of the first of them;
  203. `last_nonopt' is the index after the last of them. */
  204. static int first_nonopt;
  205. static int last_nonopt;
  206. #ifdef _LIBC
  207. /* Bash 2.0 gives us an environment variable containing flags
  208. indicating ARGV elements that should not be considered arguments. */
  209. /* Defined in getopt_init.c */
  210. extern char *__getopt_nonoption_flags;
  211. static int nonoption_flags_max_len;
  212. static int nonoption_flags_len;
  213. static int original_argc;
  214. static char *const *original_argv;
  215. /* Make sure the environment variable bash 2.0 puts in the environment
  216. is valid for the getopt call we must make sure that the ARGV passed
  217. to getopt is that one passed to the process. */
  218. static void
  219. __attribute__ ((unused))
  220. store_args_and_env (int argc, char *const *argv)
  221. {
  222. /* XXX This is no good solution. We should rather copy the args so
  223. that we can compare them later. But we must not use malloc(3). */
  224. original_argc = argc;
  225. original_argv = argv;
  226. }
  227. # ifdef text_set_element
  228. text_set_element (__libc_subinit, store_args_and_env);
  229. # endif /* text_set_element */
  230. # define SWAP_FLAGS(ch1, ch2) \
  231. if (nonoption_flags_len > 0) \
  232. { \
  233. char __tmp = __getopt_nonoption_flags[ch1]; \
  234. __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
  235. __getopt_nonoption_flags[ch2] = __tmp; \
  236. }
  237. #else /* !_LIBC */
  238. # define SWAP_FLAGS(ch1, ch2)
  239. #endif /* _LIBC */
  240. /* Exchange two adjacent subsequences of ARGV.
  241. One subsequence is elements [first_nonopt,last_nonopt)
  242. which contains all the non-options that have been skipped so far.
  243. The other is elements [last_nonopt,optind), which contains all
  244. the options processed since those non-options were skipped.
  245. `first_nonopt' and `last_nonopt' are relocated so that they describe
  246. the new indices of the non-options in ARGV after they are moved. */
  247. #if defined __STDC__ && __STDC__
  248. static void exchange (char **);
  249. #endif
  250. static void
  251. exchange (char **argv)
  252. {
  253. int bottom = first_nonopt;
  254. int middle = last_nonopt;
  255. int top = optind;
  256. char *tem;
  257. /* Exchange the shorter segment with the far end of the longer segment.
  258. That puts the shorter segment into the right place.
  259. It leaves the longer segment in the right place overall,
  260. but it consists of two parts that need to be swapped next. */
  261. #ifdef _LIBC
  262. /* First make sure the handling of the `__getopt_nonoption_flags'
  263. string can work normally. Our top argument must be in the range
  264. of the string. */
  265. if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
  266. {
  267. /* We must extend the array. The user plays games with us and
  268. presents new arguments. */
  269. char *new_str = (char *) malloc (top + 1);
  270. if (new_str == NULL)
  271. nonoption_flags_len = nonoption_flags_max_len = 0;
  272. else
  273. {
  274. memset (mempcpy (new_str, __getopt_nonoption_flags,
  275. nonoption_flags_max_len),
  276. '\0', top + 1 - nonoption_flags_max_len);
  277. nonoption_flags_max_len = top + 1;
  278. __getopt_nonoption_flags = new_str;
  279. }
  280. }
  281. #endif
  282. while (top > middle && middle > bottom)
  283. {
  284. if (top - middle > middle - bottom)
  285. {
  286. /* Bottom segment is the short one. */
  287. int len = middle - bottom;
  288. register int i;
  289. /* Swap it with the top part of the top segment. */
  290. for (i = 0; i < len; i++)
  291. {
  292. tem = argv[bottom + i];
  293. argv[bottom + i] = argv[top - (middle - bottom) + i];
  294. argv[top - (middle - bottom) + i] = tem;
  295. SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
  296. }
  297. /* Exclude the moved bottom segment from further swapping. */
  298. top -= len;
  299. }
  300. else
  301. {
  302. /* Top segment is the short one. */
  303. int len = top - middle;
  304. register int i;
  305. /* Swap it with the bottom part of the bottom segment. */
  306. for (i = 0; i < len; i++)
  307. {
  308. tem = argv[bottom + i];
  309. argv[bottom + i] = argv[middle + i];
  310. argv[middle + i] = tem;
  311. SWAP_FLAGS (bottom + i, middle + i);
  312. }
  313. /* Exclude the moved top segment from further swapping. */
  314. bottom += len;
  315. }
  316. }
  317. /* Update records for the slots the non-options now occupy. */
  318. first_nonopt += (optind - last_nonopt);
  319. last_nonopt = optind;
  320. }
  321. /* Initialize the internal data when the first call is made. */
  322. #if defined __STDC__ && __STDC__
  323. static const char *_getopt_initialize (int, char *const *, const char *);
  324. #endif
  325. static const char *
  326. _getopt_initialize (int argc ATTRIBUTE_UNUSED,
  327. char *const *argv ATTRIBUTE_UNUSED,
  328. const char *optstring)
  329. {
  330. /* Start processing options with ARGV-element 1 (since ARGV-element 0
  331. is the program name); the sequence of previously skipped
  332. non-option ARGV-elements is empty. */
  333. first_nonopt = last_nonopt = optind;
  334. nextchar = NULL;
  335. posixly_correct = getenv ("POSIXLY_CORRECT");
  336. /* Determine how to handle the ordering of options and nonoptions. */
  337. if (optstring[0] == '-')
  338. {
  339. ordering = RETURN_IN_ORDER;
  340. ++optstring;
  341. }
  342. else if (optstring[0] == '+')
  343. {
  344. ordering = REQUIRE_ORDER;
  345. ++optstring;
  346. }
  347. else if (posixly_correct != NULL)
  348. ordering = REQUIRE_ORDER;
  349. else
  350. ordering = PERMUTE;
  351. #ifdef _LIBC
  352. if (posixly_correct == NULL
  353. && argc == original_argc && argv == original_argv)
  354. {
  355. if (nonoption_flags_max_len == 0)
  356. {
  357. if (__getopt_nonoption_flags == NULL
  358. || __getopt_nonoption_flags[0] == '\0')
  359. nonoption_flags_max_len = -1;
  360. else
  361. {
  362. const char *orig_str = __getopt_nonoption_flags;
  363. int len = nonoption_flags_max_len = strlen (orig_str);
  364. if (nonoption_flags_max_len < argc)
  365. nonoption_flags_max_len = argc;
  366. __getopt_nonoption_flags =
  367. (char *) malloc (nonoption_flags_max_len);
  368. if (__getopt_nonoption_flags == NULL)
  369. nonoption_flags_max_len = -1;
  370. else
  371. memset (mempcpy (__getopt_nonoption_flags, orig_str, len),
  372. '\0', nonoption_flags_max_len - len);
  373. }
  374. }
  375. nonoption_flags_len = nonoption_flags_max_len;
  376. }
  377. else
  378. nonoption_flags_len = 0;
  379. #endif
  380. return optstring;
  381. }
  382. /* Scan elements of ARGV (whose length is ARGC) for option characters
  383. given in OPTSTRING.
  384. If an element of ARGV starts with '-', and is not exactly "-" or "--",
  385. then it is an option element. The characters of this element
  386. (aside from the initial '-') are option characters. If `getopt'
  387. is called repeatedly, it returns successively each of the option characters
  388. from each of the option elements.
  389. If `getopt' finds another option character, it returns that character,
  390. updating `optind' and `nextchar' so that the next call to `getopt' can
  391. resume the scan with the following option character or ARGV-element.
  392. If there are no more option characters, `getopt' returns -1.
  393. Then `optind' is the index in ARGV of the first ARGV-element
  394. that is not an option. (The ARGV-elements have been permuted
  395. so that those that are not options now come last.)
  396. OPTSTRING is a string containing the legitimate option characters.
  397. If an option character is seen that is not listed in OPTSTRING,
  398. return '?' after printing an error message. If you set `opterr' to
  399. zero, the error message is suppressed but we still return '?'.
  400. If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  401. so the following text in the same ARGV-element, or the text of the following
  402. ARGV-element, is returned in `optarg'. Two colons mean an option that
  403. wants an optional arg; if there is text in the current ARGV-element,
  404. it is returned in `optarg', otherwise `optarg' is set to zero.
  405. If OPTSTRING starts with `-' or `+', it requests different methods of
  406. handling the non-option ARGV-elements.
  407. See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
  408. Long-named options begin with `--' instead of `-'.
  409. Their names may be abbreviated as long as the abbreviation is unique
  410. or is an exact match for some defined option. If they have an
  411. argument, it follows the option name in the same ARGV-element, separated
  412. from the option name by a `=', or else the in next ARGV-element.
  413. When `getopt' finds a long-named option, it returns 0 if that option's
  414. `flag' field is nonzero, the value of the option's `val' field
  415. if the `flag' field is zero.
  416. The elements of ARGV aren't really const, because we permute them.
  417. But we pretend they're const in the prototype to be compatible
  418. with other systems.
  419. LONGOPTS is a vector of `struct option' terminated by an
  420. element containing a name which is zero.
  421. LONGIND returns the index in LONGOPT of the long-named option found.
  422. It is only valid when a long-named option has been found by the most
  423. recent call.
  424. If LONG_ONLY is nonzero, '-' as well as '--' can introduce
  425. long-named options. */
  426. int
  427. _getopt_internal (int argc, char *const *argv, const char *optstring,
  428. const struct option *longopts,
  429. int *longind, int long_only)
  430. {
  431. optarg = NULL;
  432. if (optind == 0 || !__getopt_initialized)
  433. {
  434. if (optind == 0)
  435. optind = 1; /* Don't scan ARGV[0], the program name. */
  436. optstring = _getopt_initialize (argc, argv, optstring);
  437. __getopt_initialized = 1;
  438. }
  439. /* Test whether ARGV[optind] points to a non-option argument.
  440. Either it does not have option syntax, or there is an environment flag
  441. from the shell indicating it is not an option. The later information
  442. is only used when the used in the GNU libc. */
  443. #ifdef _LIBC
  444. # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
  445. || (optind < nonoption_flags_len \
  446. && __getopt_nonoption_flags[optind] == '1'))
  447. #else
  448. # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
  449. #endif
  450. if (nextchar == NULL || *nextchar == '\0')
  451. {
  452. /* Advance to the next ARGV-element. */
  453. /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
  454. moved back by the user (who may also have changed the arguments). */
  455. if (last_nonopt > optind)
  456. last_nonopt = optind;
  457. if (first_nonopt > optind)
  458. first_nonopt = optind;
  459. if (ordering == PERMUTE)
  460. {
  461. /* If we have just processed some options following some non-options,
  462. exchange them so that the options come first. */
  463. if (first_nonopt != last_nonopt && last_nonopt != optind)
  464. exchange ((char **) argv);
  465. else if (last_nonopt != optind)
  466. first_nonopt = optind;
  467. /* Skip any additional non-options
  468. and extend the range of non-options previously skipped. */
  469. while (optind < argc && NONOPTION_P)
  470. optind++;
  471. last_nonopt = optind;
  472. }
  473. /* The special ARGV-element `--' means premature end of options.
  474. Skip it like a null option,
  475. then exchange with previous non-options as if it were an option,
  476. then skip everything else like a non-option. */
  477. if (optind != argc && !strcmp (argv[optind], "--"))
  478. {
  479. optind++;
  480. if (first_nonopt != last_nonopt && last_nonopt != optind)
  481. exchange ((char **) argv);
  482. else if (first_nonopt == last_nonopt)
  483. first_nonopt = optind;
  484. last_nonopt = argc;
  485. optind = argc;
  486. }
  487. /* If we have done all the ARGV-elements, stop the scan
  488. and back over any non-options that we skipped and permuted. */
  489. if (optind == argc)
  490. {
  491. /* Set the next-arg-index to point at the non-options
  492. that we previously skipped, so the caller will digest them. */
  493. if (first_nonopt != last_nonopt)
  494. optind = first_nonopt;
  495. return -1;
  496. }
  497. /* If we have come to a non-option and did not permute it,
  498. either stop the scan or describe it to the caller and pass it by. */
  499. if (NONOPTION_P)
  500. {
  501. if (ordering == REQUIRE_ORDER)
  502. return -1;
  503. optarg = argv[optind++];
  504. return 1;
  505. }
  506. /* We have found another option-ARGV-element.
  507. Skip the initial punctuation. */
  508. nextchar = (argv[optind] + 1
  509. + (longopts != NULL && argv[optind][1] == '-'));
  510. }
  511. /* Decode the current option-ARGV-element. */
  512. /* Check whether the ARGV-element is a long option.
  513. If long_only and the ARGV-element has the form "-f", where f is
  514. a valid short option, don't consider it an abbreviated form of
  515. a long option that starts with f. Otherwise there would be no
  516. way to give the -f short option.
  517. On the other hand, if there's a long option "fubar" and
  518. the ARGV-element is "-fu", do consider that an abbreviation of
  519. the long option, just like "--fu", and not "-f" with arg "u".
  520. This distinction seems to be the most useful approach. */
  521. if (longopts != NULL
  522. && (argv[optind][1] == '-'
  523. || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
  524. {
  525. char *nameend;
  526. const struct option *p;
  527. const struct option *pfound = NULL;
  528. int exact = 0;
  529. int ambig = 0;
  530. int indfound = -1;
  531. int option_index;
  532. for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
  533. /* Do nothing. */ ;
  534. /* Test all long options for either exact match
  535. or abbreviated matches. */
  536. for (p = longopts, option_index = 0; p->name; p++, option_index++)
  537. if (!strncmp (p->name, nextchar, nameend - nextchar))
  538. {
  539. if ((unsigned int) (nameend - nextchar)
  540. == (unsigned int) strlen (p->name))
  541. {
  542. /* Exact match found. */
  543. pfound = p;
  544. indfound = option_index;
  545. exact = 1;
  546. break;
  547. }
  548. else if (pfound == NULL)
  549. {
  550. /* First nonexact match found. */
  551. pfound = p;
  552. indfound = option_index;
  553. }
  554. else
  555. /* Second or later nonexact match found. */
  556. ambig = 1;
  557. }
  558. if (ambig && !exact)
  559. {
  560. if (opterr)
  561. fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
  562. argv[0], argv[optind]);
  563. nextchar += strlen (nextchar);
  564. optind++;
  565. optopt = 0;
  566. return '?';
  567. }
  568. if (pfound != NULL)
  569. {
  570. option_index = indfound;
  571. optind++;
  572. if (*nameend)
  573. {
  574. /* Don't test has_arg with >, because some C compilers don't
  575. allow it to be used on enums. */
  576. if (pfound->has_arg)
  577. optarg = nameend + 1;
  578. else
  579. {
  580. if (opterr)
  581. {
  582. if (argv[optind - 1][1] == '-')
  583. /* --option */
  584. fprintf (stderr,
  585. _("%s: option `--%s' doesn't allow an argument\n"),
  586. argv[0], pfound->name);
  587. else
  588. /* +option or -option */
  589. fprintf (stderr,
  590. _("%s: option `%c%s' doesn't allow an argument\n"),
  591. argv[0], argv[optind - 1][0], pfound->name);
  592. nextchar += strlen (nextchar);
  593. optopt = pfound->val;
  594. return '?';
  595. }
  596. }
  597. }
  598. else if (pfound->has_arg == 1)
  599. {
  600. if (optind < argc)
  601. optarg = argv[optind++];
  602. else
  603. {
  604. if (opterr)
  605. fprintf (stderr,
  606. _("%s: option `%s' requires an argument\n"),
  607. argv[0], argv[optind - 1]);
  608. nextchar += strlen (nextchar);
  609. optopt = pfound->val;
  610. return optstring[0] == ':' ? ':' : '?';
  611. }
  612. }
  613. nextchar += strlen (nextchar);
  614. if (longind != NULL)
  615. *longind = option_index;
  616. if (pfound->flag)
  617. {
  618. *(pfound->flag) = pfound->val;
  619. return 0;
  620. }
  621. return pfound->val;
  622. }
  623. /* Can't find it as a long option. If this is not getopt_long_only,
  624. or the option starts with '--' or is not a valid short
  625. option, then it's an error.
  626. Otherwise interpret it as a short option. */
  627. if (!long_only || argv[optind][1] == '-'
  628. || my_index (optstring, *nextchar) == NULL)
  629. {
  630. if (opterr)
  631. {
  632. if (argv[optind][1] == '-')
  633. /* --option */
  634. fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
  635. argv[0], nextchar);
  636. else
  637. /* +option or -option */
  638. fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
  639. argv[0], argv[optind][0], nextchar);
  640. }
  641. nextchar = (char *) "";
  642. optind++;
  643. optopt = 0;
  644. return '?';
  645. }
  646. }
  647. /* Look at and handle the next short option-character. */
  648. {
  649. char c = *nextchar++;
  650. char *temp = my_index (optstring, c);
  651. /* Increment `optind' when we start to process its last character. */
  652. if (*nextchar == '\0')
  653. ++optind;
  654. if (temp == NULL || c == ':')
  655. {
  656. if (opterr)
  657. {
  658. if (posixly_correct)
  659. /* 1003.2 specifies the format of this message. */
  660. fprintf (stderr, _("%s: illegal option -- %c\n"),
  661. argv[0], c);
  662. else
  663. fprintf (stderr, _("%s: invalid option -- %c\n"),
  664. argv[0], c);
  665. }
  666. optopt = c;
  667. return '?';
  668. }
  669. /* Convenience. Treat POSIX -W foo same as long option --foo */
  670. if (temp[0] == 'W' && temp[1] == ';')
  671. {
  672. char *nameend;
  673. const struct option *p;
  674. const struct option *pfound = NULL;
  675. int exact = 0;
  676. int ambig = 0;
  677. int indfound = 0;
  678. int option_index;
  679. /* This is an option that requires an argument. */
  680. if (*nextchar != '\0')
  681. {
  682. optarg = nextchar;
  683. /* If we end this ARGV-element by taking the rest as an arg,
  684. we must advance to the next element now. */
  685. optind++;
  686. }
  687. else if (optind == argc)
  688. {
  689. if (opterr)
  690. {
  691. /* 1003.2 specifies the format of this message. */
  692. fprintf (stderr, _("%s: option requires an argument -- %c\n"),
  693. argv[0], c);
  694. }
  695. optopt = c;
  696. if (optstring[0] == ':')
  697. c = ':';
  698. else
  699. c = '?';
  700. return c;
  701. }
  702. else
  703. /* We already incremented `optind' once;
  704. increment it again when taking next ARGV-elt as argument. */
  705. optarg = argv[optind++];
  706. /* optarg is now the argument, see if it's in the
  707. table of longopts. */
  708. for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
  709. /* Do nothing. */ ;
  710. /* Test all long options for either exact match
  711. or abbreviated matches. */
  712. for (p = longopts, option_index = 0; p->name; p++, option_index++)
  713. if (!strncmp (p->name, nextchar, nameend - nextchar))
  714. {
  715. if ((unsigned int) (nameend - nextchar) == strlen (p->name))
  716. {
  717. /* Exact match found. */
  718. pfound = p;
  719. indfound = option_index;
  720. exact = 1;
  721. break;
  722. }
  723. else if (pfound == NULL)
  724. {
  725. /* First nonexact match found. */
  726. pfound = p;
  727. indfound = option_index;
  728. }
  729. else
  730. /* Second or later nonexact match found. */
  731. ambig = 1;
  732. }
  733. if (ambig && !exact)
  734. {
  735. if (opterr)
  736. fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
  737. argv[0], argv[optind]);
  738. nextchar += strlen (nextchar);
  739. optind++;
  740. return '?';
  741. }
  742. if (pfound != NULL)
  743. {
  744. option_index = indfound;
  745. if (*nameend)
  746. {
  747. /* Don't test has_arg with >, because some C compilers don't
  748. allow it to be used on enums. */
  749. if (pfound->has_arg)
  750. optarg = nameend + 1;
  751. else
  752. {
  753. if (opterr)
  754. fprintf (stderr, _("\
  755. %s: option `-W %s' doesn't allow an argument\n"),
  756. argv[0], pfound->name);
  757. nextchar += strlen (nextchar);
  758. return '?';
  759. }
  760. }
  761. else if (pfound->has_arg == 1)
  762. {
  763. if (optind < argc)
  764. optarg = argv[optind++];
  765. else
  766. {
  767. if (opterr)
  768. fprintf (stderr,
  769. _("%s: option `%s' requires an argument\n"),
  770. argv[0], argv[optind - 1]);
  771. nextchar += strlen (nextchar);
  772. return optstring[0] == ':' ? ':' : '?';
  773. }
  774. }
  775. nextchar += strlen (nextchar);
  776. if (longind != NULL)
  777. *longind = option_index;
  778. if (pfound->flag)
  779. {
  780. *(pfound->flag) = pfound->val;
  781. return 0;
  782. }
  783. return pfound->val;
  784. }
  785. nextchar = NULL;
  786. return 'W'; /* Let the application handle it. */
  787. }
  788. if (temp[1] == ':')
  789. {
  790. if (temp[2] == ':')
  791. {
  792. /* This is an option that accepts an argument optionally. */
  793. if (*nextchar != '\0')
  794. {
  795. optarg = nextchar;
  796. optind++;
  797. }
  798. else
  799. optarg = NULL;
  800. nextchar = NULL;
  801. }
  802. else
  803. {
  804. /* This is an option that requires an argument. */
  805. if (*nextchar != '\0')
  806. {
  807. optarg = nextchar;
  808. /* If we end this ARGV-element by taking the rest as an arg,
  809. we must advance to the next element now. */
  810. optind++;
  811. }
  812. else if (optind == argc)
  813. {
  814. if (opterr)
  815. {
  816. /* 1003.2 specifies the format of this message. */
  817. fprintf (stderr,
  818. _("%s: option requires an argument -- %c\n"),
  819. argv[0], c);
  820. }
  821. optopt = c;
  822. if (optstring[0] == ':')
  823. c = ':';
  824. else
  825. c = '?';
  826. }
  827. else
  828. /* We already incremented `optind' once;
  829. increment it again when taking next ARGV-elt as argument. */
  830. optarg = argv[optind++];
  831. nextchar = NULL;
  832. }
  833. }
  834. return c;
  835. }
  836. }
  837. int
  838. getopt (int argc, char *const *argv, const char *optstring)
  839. {
  840. return _getopt_internal (argc, argv, optstring,
  841. (const struct option *) 0,
  842. (int *) 0,
  843. 0);
  844. }
  845. #endif /* Not ELIDE_CODE. */
  846. #ifdef TEST
  847. /* Compile with -DTEST to make an executable for use in testing
  848. the above definition of `getopt'. */
  849. int
  850. main (int argc, char **argv)
  851. {
  852. int c;
  853. int digit_optind = 0;
  854. while (1)
  855. {
  856. int this_option_optind = optind ? optind : 1;
  857. c = getopt (argc, argv, "abc:d:0123456789");
  858. if (c == -1)
  859. break;
  860. switch (c)
  861. {
  862. case '0':
  863. case '1':
  864. case '2':
  865. case '3':
  866. case '4':
  867. case '5':
  868. case '6':
  869. case '7':
  870. case '8':
  871. case '9':
  872. if (digit_optind != 0 && digit_optind != this_option_optind)
  873. printf ("digits occur in two different argv-elements.\n");
  874. digit_optind = this_option_optind;
  875. printf ("option %c\n", c);
  876. break;
  877. case 'a':
  878. printf ("option a\n");
  879. break;
  880. case 'b':
  881. printf ("option b\n");
  882. break;
  883. case 'c':
  884. printf ("option c with value `%s'\n", optarg);
  885. break;
  886. case '?':
  887. break;
  888. default:
  889. printf ("?? getopt returned character code 0%o ??\n", c);
  890. }
  891. }
  892. if (optind < argc)
  893. {
  894. printf ("non-option ARGV-elements: ");
  895. while (optind < argc)
  896. printf ("%s ", argv[optind++]);
  897. printf ("\n");
  898. }
  899. exit (0);
  900. }
  901. #endif /* TEST */