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