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