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