getopt.c 29 KB

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