getopt.c 30 KB

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