getopt_long.c 14 KB

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