getopt.c 29 KB

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