getopt.c 34 KB

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