getopt.c 30 KB

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