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