1
0

getopt.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /*-
  2. * Copyright (c) 2000 The NetBSD Foundation, Inc.
  3. * All rights reserved.
  4. *
  5. * This code is derived from software contributed to The NetBSD Foundation
  6. * by Dieter Baron and Thomas Klausner.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. * 2. Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in the
  15. * documentation and/or other materials provided with the distribution.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
  18. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  19. * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  20. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
  21. * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  22. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  23. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  24. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  25. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  26. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  27. * POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * $NetBSD: getopt_long.c,v 1.3 2008/04/29 05:46:09 martin Exp $
  30. */
  31. #include <assert.h>
  32. #include <errno.h>
  33. #include <stdarg.h>
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #include "getopt.h"
  38. #ifndef _DIAGASSERT
  39. #define _DIAGASSERT(e)
  40. #endif
  41. int opterr = 1; /* if error message should be printed */
  42. int optind = 1; /* index into parent argv vector */
  43. int optopt = '?'; /* character checked for validity */
  44. int optreset; /* reset getopt */
  45. char *optarg; /* argument associated with option */
  46. #define IGNORE_FIRST (*options == '-' || *options == '+')
  47. #define PRINT_ERROR ((opterr) && ((*options != ':') \
  48. || (IGNORE_FIRST && options[1] != ':')))
  49. #define IS_POSIXLY_CORRECT (getenv("POSIXLY_CORRECT") != NULL)
  50. #define PERMUTE (!IS_POSIXLY_CORRECT && !IGNORE_FIRST)
  51. /* XXX: GNU ignores PC if *options == '-' */
  52. #define IN_ORDER (!IS_POSIXLY_CORRECT && *options == '-')
  53. /* return values */
  54. #define BADCH (int)'?'
  55. #define BADARG (int)':'
  56. #define INORDER (int)1
  57. #define EMSG ""
  58. static int getopt_internal(int, char * const *, const char *);
  59. static int gcd(int, int);
  60. static void permute_args(int, int, int, char * const *);
  61. static void xwarnx(const char *, ...);
  62. static char *place = EMSG; /* option letter processing */
  63. /* XXX: set optreset to 1 rather than these two */
  64. static int nonopt_start = -1; /* first non option argument (for permute) */
  65. static int nonopt_end = -1; /* first option after non options (for permute) */
  66. /* Error messages */
  67. static const char recargchar[] = "option requires an argument -- %c";
  68. static const char recargstring[] = "option requires an argument -- %s";
  69. static const char ambig[] = "ambiguous option -- %.*s";
  70. static const char noarg[] = "option doesn't take an argument -- %.*s";
  71. static const char illoptchar[] = "illegal option -- %c";
  72. static const char illoptstring[] = "illegal option -- %s";
  73. static const char *progname;
  74. /* Replacement for warnx(3) for systems without it. */
  75. static void xwarnx(const char *fmt, ...) {
  76. va_list ap;
  77. va_start(ap, fmt);
  78. if (progname)
  79. (void) fprintf(stderr, "%s: ", progname);
  80. if (fmt)
  81. (void) vfprintf(stderr, fmt, ap);
  82. (void) fprintf(stderr, "\n");
  83. va_end(ap);
  84. }
  85. /*
  86. * Compute the greatest common divisor of a and b.
  87. */
  88. static int
  89. gcd(int a, int b)
  90. {
  91. int c;
  92. c = a % b;
  93. while (c != 0) {
  94. a = b;
  95. b = c;
  96. c = a % b;
  97. }
  98. return b;
  99. }
  100. /*
  101. * Exchange the block from nonopt_start to nonopt_end with the block
  102. * from nonopt_end to opt_end (keeping the same order of arguments
  103. * in each block).
  104. */
  105. static void
  106. permute_args(int nonopt_start, int nonopt_end, int opt_end, char * const *nargv)
  107. {
  108. int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
  109. char *swap;
  110. /*
  111. * compute lengths of blocks and number and size of cycles
  112. */
  113. nnonopts = nonopt_end - nonopt_start;
  114. nopts = opt_end - nonopt_end;
  115. ncycle = gcd(nnonopts, nopts);
  116. cyclelen = (opt_end - nonopt_start) / ncycle;
  117. for (i = 0; i < ncycle; i++) {
  118. cstart = nonopt_end+i;
  119. pos = cstart;
  120. for (j = 0; j < cyclelen; j++) {
  121. if (pos >= nonopt_end)
  122. pos -= nnonopts;
  123. else
  124. pos += nopts;
  125. swap = nargv[pos];
  126. /* LINTED const cast */
  127. ((char **) nargv)[pos] = nargv[cstart];
  128. /* LINTED const cast */
  129. ((char **)nargv)[cstart] = swap;
  130. }
  131. }
  132. }
  133. /*
  134. * getopt_internal --
  135. * Parse argc/argv argument vector. Called by user level routines.
  136. * Returns -2 if -- is found (can be long option or end of options marker).
  137. */
  138. static int
  139. getopt_internal(int nargc, char * const *nargv, const char *options)
  140. {
  141. char *oli; /* option letter list index */
  142. int optchar;
  143. _DIAGASSERT(nargv != NULL);
  144. _DIAGASSERT(options != NULL);
  145. optarg = NULL;
  146. /*
  147. * XXX Some programs (like rsyncd) expect to be able to
  148. * XXX re-initialize optind to 0 and have getopt_long(3)
  149. * XXX properly function again. Work around this braindamage.
  150. */
  151. if (optind == 0)
  152. optind = 1;
  153. if (optreset)
  154. nonopt_start = nonopt_end = -1;
  155. start:
  156. if (optreset || !*place) { /* update scanning pointer */
  157. optreset = 0;
  158. if (optind >= nargc) { /* end of argument vector */
  159. place = EMSG;
  160. if (nonopt_end != -1) {
  161. /* do permutation, if we have to */
  162. permute_args(nonopt_start, nonopt_end,
  163. optind, nargv);
  164. optind -= nonopt_end - nonopt_start;
  165. }
  166. else if (nonopt_start != -1) {
  167. /*
  168. * If we skipped non-options, set optind
  169. * to the first of them.
  170. */
  171. optind = nonopt_start;
  172. }
  173. nonopt_start = nonopt_end = -1;
  174. return -1;
  175. }
  176. if (*(place = nargv[optind]) != '-') { /* found non-option */
  177. place = EMSG;
  178. if (IN_ORDER) {
  179. /*
  180. * GNU extension:
  181. * return non-option as argument to option 1
  182. */
  183. optarg = nargv[optind++];
  184. return INORDER;
  185. }
  186. if (!PERMUTE) {
  187. /*
  188. * if no permutation wanted, stop parsing
  189. * at first non-option
  190. */
  191. return -1;
  192. }
  193. /* do permutation */
  194. if (nonopt_start == -1)
  195. nonopt_start = optind;
  196. else if (nonopt_end != -1) {
  197. permute_args(nonopt_start, nonopt_end,
  198. optind, nargv);
  199. nonopt_start = optind -
  200. (nonopt_end - nonopt_start);
  201. nonopt_end = -1;
  202. }
  203. optind++;
  204. /* process next argument */
  205. goto start;
  206. }
  207. if (nonopt_start != -1 && nonopt_end == -1)
  208. nonopt_end = optind;
  209. if (place[1] && *++place == '-') { /* found "--" */
  210. place++;
  211. return -2;
  212. }
  213. }
  214. if ((optchar = (int)*place++) == (int)':' ||
  215. (oli = strchr(options + (IGNORE_FIRST ? 1 : 0), optchar)) == NULL) {
  216. /* option letter unknown or ':' */
  217. if (!*place)
  218. ++optind;
  219. if (PRINT_ERROR)
  220. xwarnx(illoptchar, optchar);
  221. optopt = optchar;
  222. return BADCH;
  223. }
  224. if (optchar == 'W' && oli[1] == ';') { /* -W long-option */
  225. /* XXX: what if no long options provided (called by getopt)? */
  226. if (*place)
  227. return -2;
  228. if (++optind >= nargc) { /* no arg */
  229. place = EMSG;
  230. if (PRINT_ERROR)
  231. xwarnx(recargchar, optchar);
  232. optopt = optchar;
  233. /* XXX: GNU returns '?' if options[0] != ':' */
  234. return BADARG;
  235. } else /* white space */
  236. place = nargv[optind];
  237. /*
  238. * Handle -W arg the same as --arg (which causes getopt to
  239. * stop parsing).
  240. */
  241. return -2;
  242. }
  243. if (*++oli != ':') { /* doesn't take argument */
  244. if (!*place)
  245. ++optind;
  246. } else { /* takes (optional) argument */
  247. optarg = NULL;
  248. if (*place) /* no white space */
  249. optarg = place;
  250. /* XXX: disable test for :: if PC? (GNU doesn't) */
  251. else if (oli[1] != ':') { /* arg not optional */
  252. if (++optind >= nargc) { /* no arg */
  253. place = EMSG;
  254. if (PRINT_ERROR)
  255. xwarnx(recargchar, optchar);
  256. optopt = optchar;
  257. /* XXX: GNU returns '?' if options[0] != ':' */
  258. return BADARG;
  259. } else
  260. optarg = nargv[optind];
  261. }
  262. place = EMSG;
  263. ++optind;
  264. }
  265. /* dump back option letter */
  266. return optchar;
  267. }
  268. /*
  269. * getopt --
  270. * Parse argc/argv argument vector.
  271. *
  272. * [eventually this will replace the real getopt]
  273. */
  274. int
  275. getopt(int nargc, char * const *nargv, const char *options)
  276. {
  277. int retval;
  278. progname = nargv[0];
  279. if ((retval = getopt_internal(nargc, nargv, options)) == -2) {
  280. ++optind;
  281. /*
  282. * We found an option (--), so if we skipped non-options,
  283. * we have to permute.
  284. */
  285. if (nonopt_end != -1) {
  286. permute_args(nonopt_start, nonopt_end, optind,
  287. nargv);
  288. optind -= nonopt_end - nonopt_start;
  289. }
  290. nonopt_start = nonopt_end = -1;
  291. retval = -1;
  292. }
  293. return retval;
  294. }
  295. /*
  296. * getopt_long --
  297. * Parse argc/argv argument vector.
  298. */
  299. int
  300. getopt_long(int nargc,
  301. char * const *nargv,
  302. const char *options,
  303. const struct option *long_options,
  304. int *idx)
  305. {
  306. int retval;
  307. _DIAGASSERT(nargv != NULL);
  308. _DIAGASSERT(options != NULL);
  309. _DIAGASSERT(long_options != NULL);
  310. /* idx may be NULL */
  311. progname = nargv[0];
  312. if ((retval = getopt_internal(nargc, nargv, options)) == -2) {
  313. char *current_argv, *has_equal;
  314. size_t current_argv_len;
  315. int i, match;
  316. current_argv = place;
  317. match = -1;
  318. optind++;
  319. place = EMSG;
  320. if (*current_argv == '\0') { /* found "--" */
  321. /*
  322. * We found an option (--), so if we skipped
  323. * non-options, we have to permute.
  324. */
  325. if (nonopt_end != -1) {
  326. permute_args(nonopt_start, nonopt_end,
  327. optind, nargv);
  328. optind -= nonopt_end - nonopt_start;
  329. }
  330. nonopt_start = nonopt_end = -1;
  331. return -1;
  332. }
  333. if ((has_equal = strchr(current_argv, '=')) != NULL) {
  334. /* argument found (--option=arg) */
  335. current_argv_len = has_equal - current_argv;
  336. has_equal++;
  337. } else
  338. current_argv_len = strlen(current_argv);
  339. for (i = 0; long_options[i].name; i++) {
  340. /* find matching long option */
  341. if (strncmp(current_argv, long_options[i].name,
  342. current_argv_len))
  343. continue;
  344. if (strlen(long_options[i].name) ==
  345. (unsigned)current_argv_len) {
  346. /* exact match */
  347. match = i;
  348. break;
  349. }
  350. if (match == -1) /* partial match */
  351. match = i;
  352. else {
  353. /* ambiguous abbreviation */
  354. if (PRINT_ERROR)
  355. xwarnx(ambig, (int)current_argv_len,
  356. current_argv);
  357. optopt = 0;
  358. return BADCH;
  359. }
  360. }
  361. if (match != -1) { /* option found */
  362. if (long_options[match].has_arg == no_argument
  363. && has_equal) {
  364. if (PRINT_ERROR)
  365. xwarnx(noarg, (int)current_argv_len,
  366. current_argv);
  367. /*
  368. * XXX: GNU sets optopt to val regardless of
  369. * flag
  370. */
  371. if (long_options[match].flag == NULL)
  372. optopt = long_options[match].val;
  373. else
  374. optopt = 0;
  375. /* XXX: GNU returns '?' if options[0] != ':' */
  376. return BADARG;
  377. }
  378. if (long_options[match].has_arg == required_argument ||
  379. long_options[match].has_arg == optional_argument) {
  380. if (has_equal)
  381. optarg = has_equal;
  382. else if (long_options[match].has_arg ==
  383. required_argument) {
  384. /*
  385. * optional argument doesn't use
  386. * next nargv
  387. */
  388. optarg = nargv[optind++];
  389. }
  390. }
  391. if ((long_options[match].has_arg == required_argument)
  392. && (optarg == NULL)) {
  393. /*
  394. * Missing argument; leading ':'
  395. * indicates no error should be generated
  396. */
  397. if (PRINT_ERROR)
  398. xwarnx(recargstring, current_argv);
  399. /*
  400. * XXX: GNU sets optopt to val regardless
  401. * of flag
  402. */
  403. if (long_options[match].flag == NULL)
  404. optopt = long_options[match].val;
  405. else
  406. optopt = 0;
  407. /* XXX: GNU returns '?' if options[0] != ':' */
  408. --optind;
  409. return BADARG;
  410. }
  411. } else { /* unknown option */
  412. if (PRINT_ERROR)
  413. xwarnx(illoptstring, current_argv);
  414. optopt = 0;
  415. return BADCH;
  416. }
  417. if (long_options[match].flag) {
  418. *long_options[match].flag = long_options[match].val;
  419. retval = 0;
  420. } else
  421. retval = long_options[match].val;
  422. if (idx)
  423. *idx = match;
  424. }
  425. return retval;
  426. }