getopt_long.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. /* $OpenBSD: getopt_long.c,v 1.22 2006/10/04 21:29:04 jmc 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. #include <errno.h>
  51. #include "getopt_long.h"
  52. #include <stdlib.h>
  53. #include <stdio.h>
  54. #include <string.h>
  55. #include <stdarg.h>
  56. #define GNU_COMPATIBLE /* Be more compatible, configure's use us! */
  57. #define PRINT_ERROR ((opterr) && (*options != ':'))
  58. #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
  59. #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
  60. #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
  61. /* return values */
  62. #define BADCH (int)'?'
  63. #define BADARG ((*options == ':') ? (int)':' : (int)'?')
  64. #define INORDER (int)1
  65. #define EMSG ""
  66. #ifdef GNU_COMPATIBLE
  67. #define NO_PREFIX (-1)
  68. #define D_PREFIX 0
  69. #define DD_PREFIX 1
  70. #define W_PREFIX 2
  71. #endif
  72. char *optarg;
  73. int optind, opterr = 1, optopt;
  74. static int getopt_internal(int, char * const *, const char *,
  75. const struct option *, int *, int);
  76. static int parse_long_options(char * const *, const char *,
  77. const struct option *, int *, int, int);
  78. static int gcd(int, int);
  79. static void permute_args(int, int, int, char * const *);
  80. static const char *place = EMSG; /* option letter processing */
  81. static int nonopt_start = -1; /* first non option argument (for permute) */
  82. static int nonopt_end = -1; /* first option after non options (for permute) */
  83. /* Error messages */
  84. static const char recargchar[] = "option requires an argument -- %c";
  85. static const char illoptchar[] = "illegal option -- %c"; /* From P1003.2 */
  86. #ifdef GNU_COMPATIBLE
  87. static int dash_prefix = NO_PREFIX;
  88. static const char gnuoptchar[] = "invalid option -- %c";
  89. static const char recargstring[] = "option `%s%s' requires an argument";
  90. static const char ambig[] = "option `%s%.*s' is ambiguous";
  91. static const char noarg[] = "option `%s%.*s' doesn't allow an argument";
  92. static const char illoptstring[] = "unrecognized option `%s%s'";
  93. #else
  94. static const char recargstring[] = "option requires an argument -- %s";
  95. static const char ambig[] = "ambiguous option -- %.*s";
  96. static const char noarg[] = "option doesn't take an argument -- %.*s";
  97. static const char illoptstring[] = "unknown option -- %s";
  98. #endif
  99. /*
  100. * Compute the greatest common divisor of a and b.
  101. */
  102. static int
  103. gcd(int a, int b)
  104. {
  105. int c;
  106. c = a % b;
  107. while (c != 0) {
  108. a = b;
  109. b = c;
  110. c = a % b;
  111. }
  112. return (b);
  113. }
  114. /*
  115. * Exchange the block from nonopt_start to nonopt_end with the block
  116. * from nonopt_end to opt_end (keeping the same order of arguments
  117. * in each block).
  118. */
  119. static void
  120. permute_args(int panonopt_start, int panonopt_end, int opt_end,
  121. char * const *nargv)
  122. {
  123. int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
  124. char *swap;
  125. /*
  126. * compute lengths of blocks and number and size of cycles
  127. */
  128. nnonopts = panonopt_end - panonopt_start;
  129. nopts = opt_end - panonopt_end;
  130. ncycle = gcd(nnonopts, nopts);
  131. cyclelen = (opt_end - panonopt_start) / ncycle;
  132. for (i = 0; i < ncycle; i++) {
  133. cstart = panonopt_end+i;
  134. pos = cstart;
  135. for (j = 0; j < cyclelen; j++) {
  136. if (pos >= panonopt_end)
  137. pos -= nnonopts;
  138. else
  139. pos += nopts;
  140. swap = nargv[pos];
  141. /* LINTED const cast */
  142. ((char **) nargv)[pos] = nargv[cstart];
  143. /* LINTED const cast */
  144. ((char **)nargv)[cstart] = swap;
  145. }
  146. }
  147. }
  148. static void
  149. warnx(const char *fmt, ...)
  150. {
  151. extern char *program_name;
  152. va_list ap;
  153. va_start(ap, fmt);
  154. fprintf(stderr, "%s: ", program_name);
  155. vfprintf(stderr, fmt, ap);
  156. fprintf(stderr, "\n");
  157. va_end(ap);
  158. }
  159. /*
  160. * parse_long_options --
  161. * Parse long options in argc/argv argument vector.
  162. * Returns -1 if short_too is set and the option does not match long_options.
  163. */
  164. static int
  165. parse_long_options(char * const *nargv, const char *options,
  166. const struct option *long_options, int *idx, int short_too, int flags)
  167. {
  168. const char *current_argv, *has_equal;
  169. #ifdef GNU_COMPATIBLE
  170. const char *current_dash;
  171. #endif
  172. size_t current_argv_len;
  173. int i, match, exact_match, second_partial_match;
  174. current_argv = place;
  175. #ifdef GNU_COMPATIBLE
  176. switch (dash_prefix) {
  177. case D_PREFIX:
  178. current_dash = "-";
  179. break;
  180. case DD_PREFIX:
  181. current_dash = "--";
  182. break;
  183. case W_PREFIX:
  184. current_dash = "-W ";
  185. break;
  186. default:
  187. current_dash = "";
  188. break;
  189. }
  190. #endif
  191. match = -1;
  192. exact_match = 0;
  193. second_partial_match = 0;
  194. optind++;
  195. if ((has_equal = strchr(current_argv, '=')) != NULL) {
  196. /* argument found (--option=arg) */
  197. current_argv_len = has_equal - current_argv;
  198. has_equal++;
  199. } else
  200. current_argv_len = strlen(current_argv);
  201. for (i = 0; long_options[i].name; i++) {
  202. /* find matching long option */
  203. if (strncmp(current_argv, long_options[i].name,
  204. current_argv_len))
  205. continue;
  206. if (strlen(long_options[i].name) == current_argv_len) {
  207. /* exact match */
  208. match = i;
  209. exact_match = 1;
  210. break;
  211. }
  212. /*
  213. * If this is a known short option, don't allow
  214. * a partial match of a single character.
  215. */
  216. if (short_too && current_argv_len == 1)
  217. continue;
  218. if (match == -1) /* first partial match */
  219. match = i;
  220. else if ((flags & FLAG_LONGONLY) ||
  221. long_options[i].has_arg !=
  222. long_options[match].has_arg ||
  223. long_options[i].flag != long_options[match].flag ||
  224. long_options[i].val != long_options[match].val)
  225. second_partial_match = 1;
  226. }
  227. if (!exact_match && second_partial_match) {
  228. /* ambiguous abbreviation */
  229. if (PRINT_ERROR)
  230. warnx(ambig,
  231. #ifdef GNU_COMPATIBLE
  232. current_dash,
  233. #endif
  234. (int)current_argv_len,
  235. current_argv);
  236. optopt = 0;
  237. return (BADCH);
  238. }
  239. if (match != -1) { /* option found */
  240. if (long_options[match].has_arg == no_argument
  241. && has_equal) {
  242. if (PRINT_ERROR)
  243. warnx(noarg,
  244. #ifdef GNU_COMPATIBLE
  245. current_dash,
  246. #endif
  247. (int)current_argv_len,
  248. current_argv);
  249. /*
  250. * XXX: GNU sets optopt to val regardless of flag
  251. */
  252. if (long_options[match].flag == NULL)
  253. optopt = long_options[match].val;
  254. else
  255. optopt = 0;
  256. #ifdef GNU_COMPATIBLE
  257. return (BADCH);
  258. #else
  259. return (BADARG);
  260. #endif
  261. }
  262. if (long_options[match].has_arg == required_argument ||
  263. long_options[match].has_arg == optional_argument) {
  264. if (has_equal)
  265. optarg = (char *)has_equal;
  266. else if (long_options[match].has_arg ==
  267. required_argument) {
  268. /*
  269. * optional argument doesn't use next nargv
  270. */
  271. optarg = nargv[optind++];
  272. }
  273. }
  274. if ((long_options[match].has_arg == required_argument)
  275. && (optarg == NULL)) {
  276. /*
  277. * Missing argument; leading ':' indicates no error
  278. * should be generated.
  279. */
  280. if (PRINT_ERROR)
  281. warnx(recargstring,
  282. #ifdef GNU_COMPATIBLE
  283. current_dash,
  284. #endif
  285. current_argv);
  286. /*
  287. * XXX: GNU sets optopt to val regardless of flag
  288. */
  289. if (long_options[match].flag == NULL)
  290. optopt = long_options[match].val;
  291. else
  292. optopt = 0;
  293. --optind;
  294. return (BADARG);
  295. }
  296. } else { /* unknown option */
  297. if (short_too) {
  298. --optind;
  299. return (-1);
  300. }
  301. if (PRINT_ERROR)
  302. warnx(illoptstring,
  303. #ifdef GNU_COMPATIBLE
  304. current_dash,
  305. #endif
  306. current_argv);
  307. optopt = 0;
  308. return (BADCH);
  309. }
  310. if (idx)
  311. *idx = match;
  312. if (long_options[match].flag) {
  313. *long_options[match].flag = long_options[match].val;
  314. return (0);
  315. } else
  316. return (long_options[match].val);
  317. }
  318. /*
  319. * getopt_internal --
  320. * Parse argc/argv argument vector. Called by user level routines.
  321. */
  322. static int
  323. getopt_internal(int nargc, char * const *nargv, const char *options,
  324. const struct option *long_options, int *idx, int flags)
  325. {
  326. char *oli; /* option letter list index */
  327. int optchar, short_too;
  328. int posixly_correct; /* no static, can be changed on the fly */
  329. if (options == NULL)
  330. return (-1);
  331. /*
  332. * Disable GNU extensions if POSIXLY_CORRECT is set or options
  333. * string begins with a '+'.
  334. */
  335. posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
  336. #ifdef GNU_COMPATIBLE
  337. if (*options == '-')
  338. flags |= FLAG_ALLARGS;
  339. else if (posixly_correct || *options == '+')
  340. flags &= ~FLAG_PERMUTE;
  341. #else
  342. if (posixly_correct || *options == '+')
  343. flags &= ~FLAG_PERMUTE;
  344. else if (*options == '-')
  345. flags |= FLAG_ALLARGS;
  346. #endif
  347. if (*options == '+' || *options == '-')
  348. options++;
  349. /*
  350. * XXX Some GNU programs (like cvs) set optind to 0 instead of
  351. * XXX using optreset. Work around this braindamage.
  352. */
  353. if (optind == 0)
  354. optind = 1;
  355. optarg = NULL;
  356. start:
  357. if (!*place) { /* update scanning pointer */
  358. if (optind >= nargc) { /* end of argument vector */
  359. place = EMSG;
  360. if (nonopt_end != -1) {
  361. /* do permutation, if we have to */
  362. permute_args(nonopt_start, nonopt_end,
  363. optind, nargv);
  364. optind -= nonopt_end - nonopt_start;
  365. }
  366. else if (nonopt_start != -1) {
  367. /*
  368. * If we skipped non-options, set optind
  369. * to the first of them.
  370. */
  371. optind = nonopt_start;
  372. }
  373. nonopt_start = nonopt_end = -1;
  374. return (-1);
  375. }
  376. if (*(place = nargv[optind]) != '-' ||
  377. #ifdef GNU_COMPATIBLE
  378. place[1] == '\0') {
  379. #else
  380. (place[1] == '\0' && strchr(options, '-') == NULL)) {
  381. #endif
  382. place = EMSG; /* found non-option */
  383. if (flags & FLAG_ALLARGS) {
  384. /*
  385. * GNU extension:
  386. * return non-option as argument to option 1
  387. */
  388. optarg = nargv[optind++];
  389. return (INORDER);
  390. }
  391. if (!(flags & FLAG_PERMUTE)) {
  392. /*
  393. * If no permutation wanted, stop parsing
  394. * at first non-option.
  395. */
  396. return (-1);
  397. }
  398. /* do permutation */
  399. if (nonopt_start == -1)
  400. nonopt_start = optind;
  401. else if (nonopt_end != -1) {
  402. permute_args(nonopt_start, nonopt_end,
  403. optind, nargv);
  404. nonopt_start = optind -
  405. (nonopt_end - nonopt_start);
  406. nonopt_end = -1;
  407. }
  408. optind++;
  409. /* process next argument */
  410. goto start;
  411. }
  412. if (nonopt_start != -1 && nonopt_end == -1)
  413. nonopt_end = optind;
  414. /*
  415. * If we have "-" do nothing, if "--" we are done.
  416. */
  417. if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
  418. optind++;
  419. place = EMSG;
  420. /*
  421. * We found an option (--), so if we skipped
  422. * non-options, we have to permute.
  423. */
  424. if (nonopt_end != -1) {
  425. permute_args(nonopt_start, nonopt_end,
  426. optind, nargv);
  427. optind -= nonopt_end - nonopt_start;
  428. }
  429. nonopt_start = nonopt_end = -1;
  430. return (-1);
  431. }
  432. }
  433. /*
  434. * Check long options if:
  435. * 1) we were passed some
  436. * 2) the arg is not just "-"
  437. * 3) either the arg starts with -- we are getopt_long_only()
  438. */
  439. if (long_options != NULL && place != nargv[optind] &&
  440. (*place == '-' || (flags & FLAG_LONGONLY))) {
  441. short_too = 0;
  442. #ifdef GNU_COMPATIBLE
  443. dash_prefix = D_PREFIX;
  444. #endif
  445. if (*place == '-') {
  446. place++; /* --foo long option */
  447. #ifdef GNU_COMPATIBLE
  448. dash_prefix = DD_PREFIX;
  449. #endif
  450. } else if (*place != ':' && strchr(options, *place) != NULL)
  451. short_too = 1; /* could be short option too */
  452. optchar = parse_long_options(nargv, options, long_options,
  453. idx, short_too, flags);
  454. if (optchar != -1) {
  455. place = EMSG;
  456. return (optchar);
  457. }
  458. }
  459. if ((optchar = (int)*place++) == (int)':' ||
  460. (optchar == (int)'-' && *place != '\0') ||
  461. (oli = strchr(options, optchar)) == NULL) {
  462. /*
  463. * If the user specified "-" and '-' isn't listed in
  464. * options, return -1 (non-option) as per POSIX.
  465. * Otherwise, it is an unknown option character (or ':').
  466. */
  467. if (optchar == (int)'-' && *place == '\0')
  468. return (-1);
  469. if (!*place)
  470. ++optind;
  471. #ifdef GNU_COMPATIBLE
  472. if (PRINT_ERROR)
  473. warnx(posixly_correct ? illoptchar : gnuoptchar,
  474. optchar);
  475. #else
  476. if (PRINT_ERROR)
  477. warnx(illoptchar, optchar);
  478. #endif
  479. optopt = optchar;
  480. return (BADCH);
  481. }
  482. if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
  483. /* -W long-option */
  484. if (*place) /* no space */
  485. /* NOTHING */;
  486. else if (++optind >= nargc) { /* no arg */
  487. place = EMSG;
  488. if (PRINT_ERROR)
  489. warnx(recargchar, optchar);
  490. optopt = optchar;
  491. return (BADARG);
  492. } else /* white space */
  493. place = nargv[optind];
  494. #ifdef GNU_COMPATIBLE
  495. dash_prefix = W_PREFIX;
  496. #endif
  497. optchar = parse_long_options(nargv, options, long_options,
  498. idx, 0, flags);
  499. place = EMSG;
  500. return (optchar);
  501. }
  502. if (*++oli != ':') { /* doesn't take argument */
  503. if (!*place)
  504. ++optind;
  505. } else { /* takes (optional) argument */
  506. optarg = NULL;
  507. if (*place) /* no white space */
  508. optarg = (char *)place;
  509. else if (oli[1] != ':') { /* arg not optional */
  510. if (++optind >= nargc) { /* no arg */
  511. place = EMSG;
  512. if (PRINT_ERROR)
  513. warnx(recargchar, optchar);
  514. optopt = optchar;
  515. return (BADARG);
  516. } else
  517. optarg = nargv[optind];
  518. }
  519. place = EMSG;
  520. ++optind;
  521. }
  522. /* dump back option letter */
  523. return (optchar);
  524. }
  525. #ifdef REPLACE_GETOPT
  526. /*
  527. * getopt --
  528. * Parse argc/argv argument vector.
  529. *
  530. * [eventually this will replace the BSD getopt]
  531. */
  532. int
  533. getopt(int nargc, char * const *nargv, const char *options)
  534. {
  535. /*
  536. * We don't pass FLAG_PERMUTE to getopt_internal() since
  537. * the BSD getopt(3) (unlike GNU) has never done this.
  538. *
  539. * Furthermore, since many privileged programs call getopt()
  540. * before dropping privileges it makes sense to keep things
  541. * as simple (and bug-free) as possible.
  542. */
  543. return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
  544. }
  545. #endif /* REPLACE_GETOPT */
  546. /*
  547. * getopt_long --
  548. * Parse argc/argv argument vector.
  549. */
  550. int
  551. getopt_long(int nargc, char * const *nargv, const char *options,
  552. const struct option *long_options, int *idx)
  553. {
  554. return (getopt_internal(nargc, nargv, options, long_options, idx,
  555. FLAG_PERMUTE));
  556. }
  557. /*
  558. * getopt_long_only --
  559. * Parse argc/argv argument vector.
  560. */
  561. int
  562. getopt_long_only(int nargc, char * const *nargv, const char *options,
  563. const struct option *long_options, int *idx)
  564. {
  565. return (getopt_internal(nargc, nargv, options, long_options, idx,
  566. FLAG_PERMUTE|FLAG_LONGONLY));
  567. }