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