getopt.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. /* $OpenBSD: getopt_long.c,v 1.26 2013/06/08 22:47:56 millert Exp $ */
  2. /* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $ */
  3. /*
  4. * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
  5. *
  6. * Permission to use, copy, modify, and distribute this software for any
  7. * purpose with or without fee is hereby granted, provided that the above
  8. * copyright notice and this permission notice appear in all copies.
  9. *
  10. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  11. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  12. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  13. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  14. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  15. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  16. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  17. *
  18. * Sponsored in part by the Defense Advanced Research Projects
  19. * Agency (DARPA) and Air Force Research Laboratory, Air Force
  20. * Materiel Command, USAF, under agreement number F39502-99-1-0512.
  21. */
  22. /*-
  23. * Copyright (c) 2000 The NetBSD Foundation, Inc.
  24. * All rights reserved.
  25. *
  26. * This code is derived from software contributed to The NetBSD Foundation
  27. * by Dieter Baron and Thomas Klausner.
  28. *
  29. * Redistribution and use in source and binary forms, with or without
  30. * modification, are permitted provided that the following conditions
  31. * are met:
  32. * 1. Redistributions of source code must retain the above copyright
  33. * notice, this list of conditions and the following disclaimer.
  34. * 2. Redistributions in binary form must reproduce the above copyright
  35. * notice, this list of conditions and the following disclaimer in the
  36. * documentation and/or other materials provided with the distribution.
  37. *
  38. * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
  39. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  40. * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  41. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
  42. * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  43. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  44. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  45. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  46. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  47. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  48. * POSSIBILITY OF SUCH DAMAGE.
  49. */
  50. #if 0
  51. #if defined(LIBC_SCCS) && !defined(lint)
  52. static char *rcsid = "$OpenBSD: getopt_long.c,v 1.16 2004/02/04 18:17:25 millert Exp $";
  53. #endif /* LIBC_SCCS and not lint */
  54. #endif
  55. #pragma GCC diagnostic ignored "-Wwrite-strings"
  56. #pragma GCC diagnostic ignored "-Wcast-qual"
  57. #define warnx(...) fprintf(stderr, __VA_ARGS__)
  58. #include <sys/cdefs.h>
  59. #include <errno.h>
  60. #include <getopt.h>
  61. #include <stdlib.h>
  62. #include <string.h>
  63. #include <stdio.h>
  64. #define GNU_COMPATIBLE /* Be more compatible, configure's use us! */
  65. #define REPLACE_GETOPT /* use this getopt as the system getopt(3) */
  66. #ifdef REPLACE_GETOPT
  67. int opterr = 1; /* if error message should be printed */
  68. int optind = 1; /* index into parent argv vector */
  69. int optopt = '?'; /* character checked for validity */
  70. int optreset; /* reset getopt */
  71. char *optarg; /* argument associated with option */
  72. #endif
  73. #define PRINT_ERROR ((opterr) && (*options != ':'))
  74. #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
  75. #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
  76. #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
  77. /* return values */
  78. #define BADCH (int)'?'
  79. #define BADARG ((*options == ':') ? (int)':' : (int)'?')
  80. #define INORDER (int)1
  81. #define EMSG ""
  82. #ifdef GNU_COMPATIBLE
  83. #define NO_PREFIX (-1)
  84. #define D_PREFIX 0
  85. #define DD_PREFIX 1
  86. #define W_PREFIX 2
  87. #endif
  88. static int getopt_internal(int, char * const *, const char *,
  89. const struct option *, int *, int);
  90. static int parse_long_options(char * const *, const char *,
  91. const struct option *, int *, int, int);
  92. static int gcd(int, int);
  93. static void permute_args(int, int, int, char * const *);
  94. static char *place = EMSG; /* option letter processing */
  95. /* XXX: set optreset to 1 rather than these two */
  96. static int nonopt_start = -1; /* first non option argument (for permute) */
  97. static int nonopt_end = -1; /* first option after non options (for permute) */
  98. /* Error messages */
  99. static const char recargchar[] = "option requires an argument -- %c\n";
  100. static const char illoptchar[] = "illegal option -- %c\n"; /* From P1003.2 */
  101. static int dash_prefix = NO_PREFIX;
  102. static const char gnuoptchar[] = "invalid option -- %c\n";
  103. static const char recargstring[] = "option `%s%s' requires an argument\n";
  104. static const char ambig[] = "option `%s%.*s' is ambiguous\n";
  105. static const char noarg[] = "option `%s%.*s' doesn't allow an argument\n";
  106. static const char illoptstring[] = "unrecognized option `%s%s'\n";
  107. /*
  108. * Compute the greatest common divisor of a and b.
  109. */
  110. static int
  111. gcd(int a, int b)
  112. {
  113. int c;
  114. c = a % b;
  115. while (c != 0) {
  116. a = b;
  117. b = c;
  118. c = a % b;
  119. }
  120. return (b);
  121. }
  122. /*
  123. * Exchange the block from nonopt_start to nonopt_end with the block
  124. * from nonopt_end to opt_end (keeping the same order of arguments
  125. * in each block).
  126. */
  127. static void
  128. permute_args(int panonopt_start, int panonopt_end, int opt_end,
  129. char * const *nargv)
  130. {
  131. int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
  132. char *swap;
  133. /*
  134. * compute lengths of blocks and number and size of cycles
  135. */
  136. nnonopts = panonopt_end - panonopt_start;
  137. nopts = opt_end - panonopt_end;
  138. ncycle = gcd(nnonopts, nopts);
  139. cyclelen = (opt_end - panonopt_start) / ncycle;
  140. for (i = 0; i < ncycle; i++) {
  141. cstart = panonopt_end+i;
  142. pos = cstart;
  143. for (j = 0; j < cyclelen; j++) {
  144. if (pos >= panonopt_end)
  145. pos -= nnonopts;
  146. else
  147. pos += nopts;
  148. swap = nargv[pos];
  149. /* LINTED const cast */
  150. ((char **) nargv)[pos] = nargv[cstart];
  151. /* LINTED const cast */
  152. ((char **)nargv)[cstart] = swap;
  153. }
  154. }
  155. }
  156. /*
  157. * parse_long_options --
  158. * Parse long options in argc/argv argument vector.
  159. * Returns -1 if short_too is set and the option does not match long_options.
  160. */
  161. static int
  162. parse_long_options(char * const *nargv, const char *options,
  163. const struct option *long_options, int *idx, int short_too, int flags)
  164. {
  165. char *current_argv, *has_equal;
  166. #ifdef GNU_COMPATIBLE
  167. char *current_dash;
  168. #endif
  169. size_t current_argv_len;
  170. int i, match, exact_match, second_partial_match;
  171. current_argv = place;
  172. #ifdef GNU_COMPATIBLE
  173. switch (dash_prefix) {
  174. case D_PREFIX:
  175. current_dash = "-";
  176. break;
  177. case DD_PREFIX:
  178. current_dash = "--";
  179. break;
  180. case W_PREFIX:
  181. current_dash = "-W ";
  182. break;
  183. default:
  184. current_dash = "";
  185. break;
  186. }
  187. #endif
  188. match = -1;
  189. exact_match = 0;
  190. second_partial_match = 0;
  191. optind++;
  192. if ((has_equal = strchr(current_argv, '=')) != NULL) {
  193. /* argument found (--option=arg) */
  194. current_argv_len = has_equal - current_argv;
  195. has_equal++;
  196. } else
  197. current_argv_len = strlen(current_argv);
  198. for (i = 0; long_options[i].name; i++) {
  199. /* find matching long option */
  200. if (strncmp(current_argv, long_options[i].name,
  201. current_argv_len))
  202. continue;
  203. if (strlen(long_options[i].name) == current_argv_len) {
  204. /* exact match */
  205. match = i;
  206. exact_match = 1;
  207. break;
  208. }
  209. /*
  210. * If this is a known short option, don't allow
  211. * a partial match of a single character.
  212. */
  213. if (short_too && current_argv_len == 1)
  214. continue;
  215. if (match == -1) /* first partial match */
  216. match = i;
  217. else if ((flags & FLAG_LONGONLY) ||
  218. long_options[i].has_arg !=
  219. long_options[match].has_arg ||
  220. long_options[i].flag != long_options[match].flag ||
  221. long_options[i].val != long_options[match].val)
  222. second_partial_match = 1;
  223. }
  224. if (!exact_match && second_partial_match) {
  225. /* ambiguous abbreviation */
  226. if (PRINT_ERROR)
  227. warnx(ambig,
  228. #ifdef GNU_COMPATIBLE
  229. current_dash,
  230. #endif
  231. (int)current_argv_len,
  232. current_argv);
  233. optopt = 0;
  234. return (BADCH);
  235. }
  236. if (match != -1) { /* option found */
  237. if (long_options[match].has_arg == no_argument
  238. && has_equal) {
  239. if (PRINT_ERROR)
  240. warnx(noarg,
  241. #ifdef GNU_COMPATIBLE
  242. current_dash,
  243. #endif
  244. (int)current_argv_len,
  245. current_argv);
  246. /*
  247. * XXX: GNU sets optopt to val regardless of flag
  248. */
  249. if (long_options[match].flag == NULL)
  250. optopt = long_options[match].val;
  251. else
  252. optopt = 0;
  253. #ifdef GNU_COMPATIBLE
  254. return (BADCH);
  255. #else
  256. return (BADARG);
  257. #endif
  258. }
  259. if (long_options[match].has_arg == required_argument ||
  260. long_options[match].has_arg == optional_argument) {
  261. if (has_equal)
  262. optarg = has_equal;
  263. else if (long_options[match].has_arg ==
  264. required_argument) {
  265. /*
  266. * optional argument doesn't use next nargv
  267. */
  268. optarg = nargv[optind++];
  269. }
  270. }
  271. if ((long_options[match].has_arg == required_argument)
  272. && (optarg == NULL)) {
  273. /*
  274. * Missing argument; leading ':' indicates no error
  275. * should be generated.
  276. */
  277. if (PRINT_ERROR)
  278. warnx(recargstring,
  279. #ifdef GNU_COMPATIBLE
  280. current_dash,
  281. #endif
  282. current_argv);
  283. /*
  284. * XXX: GNU sets optopt to val regardless of flag
  285. */
  286. if (long_options[match].flag == NULL)
  287. optopt = long_options[match].val;
  288. else
  289. optopt = 0;
  290. --optind;
  291. return (BADARG);
  292. }
  293. } else { /* unknown option */
  294. if (short_too) {
  295. --optind;
  296. return (-1);
  297. }
  298. if (PRINT_ERROR)
  299. warnx(illoptstring,
  300. #ifdef GNU_COMPATIBLE
  301. current_dash,
  302. #endif
  303. current_argv);
  304. optopt = 0;
  305. return (BADCH);
  306. }
  307. if (idx)
  308. *idx = match;
  309. if (long_options[match].flag) {
  310. *long_options[match].flag = long_options[match].val;
  311. return (0);
  312. } else
  313. return (long_options[match].val);
  314. }
  315. /*
  316. * getopt_internal --
  317. * Parse argc/argv argument vector. Called by user level routines.
  318. */
  319. static int
  320. getopt_internal(int nargc, char * const *nargv, const char *options,
  321. const struct option *long_options, int *idx, int flags)
  322. {
  323. char *oli; /* option letter list index */
  324. int optchar, short_too;
  325. static int posixly_correct = -1;
  326. if (options == NULL)
  327. return (-1);
  328. /*
  329. * XXX Some GNU programs (like cvs) set optind to 0 instead of
  330. * XXX using optreset. Work around this braindamage.
  331. */
  332. if (optind == 0)
  333. optind = optreset = 1;
  334. /*
  335. * Disable GNU extensions if POSIXLY_CORRECT is set or options
  336. * string begins with a '+'.
  337. */
  338. if (posixly_correct == -1 || optreset)
  339. posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
  340. if (*options == '-')
  341. flags |= FLAG_ALLARGS;
  342. else if (posixly_correct || *options == '+')
  343. flags &= ~FLAG_PERMUTE;
  344. if (*options == '+' || *options == '-')
  345. options++;
  346. optarg = NULL;
  347. if (optreset)
  348. nonopt_start = nonopt_end = -1;
  349. start:
  350. if (optreset || !*place) { /* update scanning pointer */
  351. optreset = 0;
  352. if (optind >= nargc) { /* end of argument vector */
  353. place = EMSG;
  354. if (nonopt_end != -1) {
  355. /* do permutation, if we have to */
  356. permute_args(nonopt_start, nonopt_end,
  357. optind, nargv);
  358. optind -= nonopt_end - nonopt_start;
  359. }
  360. else if (nonopt_start != -1) {
  361. /*
  362. * If we skipped non-options, set optind
  363. * to the first of them.
  364. */
  365. optind = nonopt_start;
  366. }
  367. nonopt_start = nonopt_end = -1;
  368. return (-1);
  369. }
  370. if (*(place = nargv[optind]) != '-' ||
  371. #ifdef GNU_COMPATIBLE
  372. place[1] == '\0') {
  373. #else
  374. (place[1] == '\0' && strchr(options, '-') == NULL)) {
  375. #endif
  376. place = EMSG; /* found non-option */
  377. if (flags & FLAG_ALLARGS) {
  378. /*
  379. * GNU extension:
  380. * return non-option as argument to option 1
  381. */
  382. optarg = nargv[optind++];
  383. return (INORDER);
  384. }
  385. if (!(flags & FLAG_PERMUTE)) {
  386. /*
  387. * If no permutation wanted, stop parsing
  388. * at first non-option.
  389. */
  390. return (-1);
  391. }
  392. /* do permutation */
  393. if (nonopt_start == -1)
  394. nonopt_start = optind;
  395. else if (nonopt_end != -1) {
  396. permute_args(nonopt_start, nonopt_end,
  397. optind, nargv);
  398. nonopt_start = optind -
  399. (nonopt_end - nonopt_start);
  400. nonopt_end = -1;
  401. }
  402. optind++;
  403. /* process next argument */
  404. goto start;
  405. }
  406. if (nonopt_start != -1 && nonopt_end == -1)
  407. nonopt_end = optind;
  408. /*
  409. * If we have "-" do nothing, if "--" we are done.
  410. */
  411. if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
  412. optind++;
  413. place = EMSG;
  414. /*
  415. * We found an option (--), so if we skipped
  416. * non-options, we have to permute.
  417. */
  418. if (nonopt_end != -1) {
  419. permute_args(nonopt_start, nonopt_end,
  420. optind, nargv);
  421. optind -= nonopt_end - nonopt_start;
  422. }
  423. nonopt_start = nonopt_end = -1;
  424. return (-1);
  425. }
  426. }
  427. /*
  428. * Check long options if:
  429. * 1) we were passed some
  430. * 2) the arg is not just "-"
  431. * 3) either the arg starts with -- we are getopt_long_only()
  432. */
  433. if (long_options != NULL && place != nargv[optind] &&
  434. (*place == '-' || (flags & FLAG_LONGONLY))) {
  435. short_too = 0;
  436. #ifdef GNU_COMPATIBLE
  437. dash_prefix = D_PREFIX;
  438. #endif
  439. if (*place == '-') {
  440. place++; /* --foo long option */
  441. if (*place == '\0')
  442. return (BADARG); /* malformed option */
  443. #ifdef GNU_COMPATIBLE
  444. dash_prefix = DD_PREFIX;
  445. #endif
  446. } else if (*place != ':' && strchr(options, *place) != NULL)
  447. short_too = 1; /* could be short option too */
  448. optchar = parse_long_options(nargv, options, long_options,
  449. idx, short_too, flags);
  450. if (optchar != -1) {
  451. place = EMSG;
  452. return (optchar);
  453. }
  454. }
  455. if ((optchar = (int)*place++) == (int)':' ||
  456. (optchar == (int)'-' && *place != '\0') ||
  457. (oli = strchr(options, optchar)) == NULL) {
  458. /*
  459. * If the user specified "-" and '-' isn't listed in
  460. * options, return -1 (non-option) as per POSIX.
  461. * Otherwise, it is an unknown option character (or ':').
  462. */
  463. if (optchar == (int)'-' && *place == '\0')
  464. return (-1);
  465. if (!*place)
  466. ++optind;
  467. #ifdef GNU_COMPATIBLE
  468. if (PRINT_ERROR)
  469. warnx(posixly_correct ? illoptchar : gnuoptchar,
  470. optchar);
  471. #else
  472. if (PRINT_ERROR)
  473. warnx(illoptchar, optchar);
  474. #endif
  475. optopt = optchar;
  476. return (BADCH);
  477. }
  478. if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
  479. /* -W long-option */
  480. if (*place) /* no space */
  481. /* NOTHING */;
  482. else if (++optind >= nargc) { /* no arg */
  483. place = EMSG;
  484. if (PRINT_ERROR)
  485. warnx(recargchar, optchar);
  486. optopt = optchar;
  487. return (BADARG);
  488. } else /* white space */
  489. place = nargv[optind];
  490. #ifdef GNU_COMPATIBLE
  491. dash_prefix = W_PREFIX;
  492. #endif
  493. optchar = parse_long_options(nargv, options, long_options,
  494. idx, 0, flags);
  495. place = EMSG;
  496. return (optchar);
  497. }
  498. if (*++oli != ':') { /* doesn't take argument */
  499. if (!*place)
  500. ++optind;
  501. } else { /* takes (optional) argument */
  502. optarg = NULL;
  503. if (*place) /* no white space */
  504. optarg = place;
  505. else if (oli[1] != ':') { /* arg not optional */
  506. if (++optind >= nargc) { /* no arg */
  507. place = EMSG;
  508. if (PRINT_ERROR)
  509. warnx(recargchar, optchar);
  510. optopt = optchar;
  511. return (BADARG);
  512. } else
  513. optarg = nargv[optind];
  514. }
  515. place = EMSG;
  516. ++optind;
  517. }
  518. /* dump back option letter */
  519. return (optchar);
  520. }
  521. #ifdef REPLACE_GETOPT
  522. /*
  523. * getopt --
  524. * Parse argc/argv argument vector.
  525. *
  526. * [eventually this will replace the BSD getopt]
  527. */
  528. int
  529. getopt(int nargc, char * const *nargv, const char *options)
  530. {
  531. /*
  532. * We don't pass FLAG_PERMUTE to getopt_internal() since
  533. * the BSD getopt(3) (unlike GNU) has never done this.
  534. *
  535. * Furthermore, since many privileged programs call getopt()
  536. * before dropping privileges it makes sense to keep things
  537. * as simple (and bug-free) as possible.
  538. */
  539. return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
  540. }
  541. #endif /* REPLACE_GETOPT */
  542. /*
  543. * getopt_long --
  544. * Parse argc/argv argument vector.
  545. */
  546. int
  547. getopt_long(int nargc, char * const *nargv, const char *options,
  548. const struct option *long_options, int *idx)
  549. {
  550. return (getopt_internal(nargc, nargv, options, long_options, idx,
  551. FLAG_PERMUTE));
  552. }
  553. /*
  554. * getopt_long_only --
  555. * Parse argc/argv argument vector.
  556. */
  557. int
  558. getopt_long_only(int nargc, char * const *nargv, const char *options,
  559. const struct option *long_options, int *idx)
  560. {
  561. return (getopt_internal(nargc, nargv, options, long_options, idx,
  562. FLAG_PERMUTE|FLAG_LONGONLY));
  563. }