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.c517
1 files changed, 517 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..73d97c0ed3
--- /dev/null
+++ b/src/lib/libc/stdlib/getopt_long.c
@@ -0,0 +1,517 @@
1/* $OpenBSD: getopt_long.c,v 1.23 2007/10/31 12:34:57 chl 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#include <err.h>
53#include <errno.h>
54#include <getopt.h>
55#include <stdlib.h>
56#include <string.h>
57
58#define REPLACE_GETOPT /* use this getopt as the system getopt(3) */
59
60#ifdef REPLACE_GETOPT
61int opterr = 1; /* if error message should be printed */
62int optind = 1; /* index into parent argv vector */
63int optopt = '?'; /* character checked for validity */
64int optreset; /* reset getopt */
65char *optarg; /* argument associated with option */
66#endif
67
68#define PRINT_ERROR ((opterr) && (*options != ':'))
69
70#define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
71#define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
72#define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
73
74/* return values */
75#define BADCH (int)'?'
76#define BADARG ((*options == ':') ? (int)':' : (int)'?')
77#define INORDER (int)1
78
79#define EMSG ""
80
81static int getopt_internal(int, char * const *, const char *,
82 const struct option *, int *, int);
83static int parse_long_options(char * const *, const char *,
84 const struct option *, int *, int);
85static int gcd(int, int);
86static void permute_args(int, int, int, char * const *);
87
88static char *place = EMSG; /* option letter processing */
89
90/* XXX: set optreset to 1 rather than these two */
91static int nonopt_start = -1; /* first non option argument (for permute) */
92static int nonopt_end = -1; /* first option after non options (for permute) */
93
94/* Error messages */
95static const char recargchar[] = "option requires an argument -- %c";
96static const char recargstring[] = "option requires an argument -- %s";
97static const char ambig[] = "ambiguous option -- %.*s";
98static const char noarg[] = "option doesn't take an argument -- %.*s";
99static const char illoptchar[] = "unknown option -- %c";
100static const char illoptstring[] = "unknown option -- %s";
101
102/*
103 * Compute the greatest common divisor of a and b.
104 */
105static int
106gcd(int a, int b)
107{
108 int c;
109
110 c = a % b;
111 while (c != 0) {
112 a = b;
113 b = c;
114 c = a % b;
115 }
116
117 return (b);
118}
119
120/*
121 * Exchange the block from nonopt_start to nonopt_end with the block
122 * from nonopt_end to opt_end (keeping the same order of arguments
123 * in each block).
124 */
125static void
126permute_args(int panonopt_start, int panonopt_end, int opt_end,
127 char * const *nargv)
128{
129 int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
130 char *swap;
131
132 /*
133 * compute lengths of blocks and number and size of cycles
134 */
135 nnonopts = panonopt_end - panonopt_start;
136 nopts = opt_end - panonopt_end;
137 ncycle = gcd(nnonopts, nopts);
138 cyclelen = (opt_end - panonopt_start) / ncycle;
139
140 for (i = 0; i < ncycle; i++) {
141 cstart = panonopt_end+i;
142 pos = cstart;
143 for (j = 0; j < cyclelen; j++) {
144 if (pos >= panonopt_end)
145 pos -= nnonopts;
146 else
147 pos += nopts;
148 swap = nargv[pos];
149 /* LINTED const cast */
150 ((char **) nargv)[pos] = nargv[cstart];
151 /* LINTED const cast */
152 ((char **)nargv)[cstart] = swap;
153 }
154 }
155}
156
157/*
158 * parse_long_options --
159 * Parse long options in argc/argv argument vector.
160 * Returns -1 if short_too is set and the option does not match long_options.
161 */
162static int
163parse_long_options(char * const *nargv, const char *options,
164 const struct option *long_options, int *idx, int short_too)
165{
166 char *current_argv, *has_equal;
167 size_t current_argv_len;
168 int i, match;
169
170 current_argv = place;
171 match = -1;
172
173 optind++;
174
175 if ((has_equal = strchr(current_argv, '=')) != NULL) {
176 /* argument found (--option=arg) */
177 current_argv_len = has_equal - current_argv;
178 has_equal++;
179 } else
180 current_argv_len = strlen(current_argv);
181
182 for (i = 0; long_options[i].name; i++) {
183 /* find matching long option */
184 if (strncmp(current_argv, long_options[i].name,
185 current_argv_len))
186 continue;
187
188 if (strlen(long_options[i].name) == current_argv_len) {
189 /* exact match */
190 match = i;
191 break;
192 }
193 /*
194 * If this is a known short option, don't allow
195 * a partial match of a single character.
196 */
197 if (short_too && current_argv_len == 1)
198 continue;
199
200 if (match == -1) /* partial match */
201 match = i;
202 else {
203 /* ambiguous abbreviation */
204 if (PRINT_ERROR)
205 warnx(ambig, (int)current_argv_len,
206 current_argv);
207 optopt = 0;
208 return (BADCH);
209 }
210 }
211 if (match != -1) { /* option found */
212 if (long_options[match].has_arg == no_argument
213 && has_equal) {
214 if (PRINT_ERROR)
215 warnx(noarg, (int)current_argv_len,
216 current_argv);
217 /*
218 * XXX: GNU sets optopt to val regardless of flag
219 */
220 if (long_options[match].flag == NULL)
221 optopt = long_options[match].val;
222 else
223 optopt = 0;
224 return (BADARG);
225 }
226 if (long_options[match].has_arg == required_argument ||
227 long_options[match].has_arg == optional_argument) {
228 if (has_equal)
229 optarg = has_equal;
230 else if (long_options[match].has_arg ==
231 required_argument) {
232 /*
233 * optional argument doesn't use next nargv
234 */
235 optarg = nargv[optind++];
236 }
237 }
238 if ((long_options[match].has_arg == required_argument)
239 && (optarg == NULL)) {
240 /*
241 * Missing argument; leading ':' indicates no error
242 * should be generated.
243 */
244 if (PRINT_ERROR)
245 warnx(recargstring,
246 current_argv);
247 /*
248 * XXX: GNU sets optopt to val regardless of flag
249 */
250 if (long_options[match].flag == NULL)
251 optopt = long_options[match].val;
252 else
253 optopt = 0;
254 --optind;
255 return (BADARG);
256 }
257 } else { /* unknown option */
258 if (short_too) {
259 --optind;
260 return (-1);
261 }
262 if (PRINT_ERROR)
263 warnx(illoptstring, current_argv);
264 optopt = 0;
265 return (BADCH);
266 }
267 if (idx)
268 *idx = match;
269 if (long_options[match].flag) {
270 *long_options[match].flag = long_options[match].val;
271 return (0);
272 } else
273 return (long_options[match].val);
274}
275
276/*
277 * getopt_internal --
278 * Parse argc/argv argument vector. Called by user level routines.
279 */
280static int
281getopt_internal(int nargc, char * const *nargv, const char *options,
282 const struct option *long_options, int *idx, int flags)
283{
284 char *oli; /* option letter list index */
285 int optchar, short_too;
286 static int posixly_correct = -1;
287
288 if (options == NULL)
289 return (-1);
290
291 /*
292 * Disable GNU extensions if POSIXLY_CORRECT is set or options
293 * string begins with a '+'.
294 */
295 if (posixly_correct == -1)
296 posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
297 if (posixly_correct || *options == '+')
298 flags &= ~FLAG_PERMUTE;
299 else if (*options == '-')
300 flags |= FLAG_ALLARGS;
301 if (*options == '+' || *options == '-')
302 options++;
303
304 /*
305 * XXX Some GNU programs (like cvs) set optind to 0 instead of
306 * XXX using optreset. Work around this braindamage.
307 */
308 if (optind == 0)
309 optind = optreset = 1;
310
311 optarg = NULL;
312 if (optreset)
313 nonopt_start = nonopt_end = -1;
314start:
315 if (optreset || !*place) { /* update scanning pointer */
316 optreset = 0;
317 if (optind >= nargc) { /* end of argument vector */
318 place = EMSG;
319 if (nonopt_end != -1) {
320 /* do permutation, if we have to */
321 permute_args(nonopt_start, nonopt_end,
322 optind, nargv);
323 optind -= nonopt_end - nonopt_start;
324 }
325 else if (nonopt_start != -1) {
326 /*
327 * If we skipped non-options, set optind
328 * to the first of them.
329 */
330 optind = nonopt_start;
331 }
332 nonopt_start = nonopt_end = -1;
333 return (-1);
334 }
335 if (*(place = nargv[optind]) != '-' ||
336 (place[1] == '\0' && strchr(options, '-') == NULL)) {
337 place = EMSG; /* found non-option */
338 if (flags & FLAG_ALLARGS) {
339 /*
340 * GNU extension:
341 * return non-option as argument to option 1
342 */
343 optarg = nargv[optind++];
344 return (INORDER);
345 }
346 if (!(flags & FLAG_PERMUTE)) {
347 /*
348 * If no permutation wanted, stop parsing
349 * at first non-option.
350 */
351 return (-1);
352 }
353 /* do permutation */
354 if (nonopt_start == -1)
355 nonopt_start = optind;
356 else if (nonopt_end != -1) {
357 permute_args(nonopt_start, nonopt_end,
358 optind, nargv);
359 nonopt_start = optind -
360 (nonopt_end - nonopt_start);
361 nonopt_end = -1;
362 }
363 optind++;
364 /* process next argument */
365 goto start;
366 }
367 if (nonopt_start != -1 && nonopt_end == -1)
368 nonopt_end = optind;
369
370 /*
371 * If we have "-" do nothing, if "--" we are done.
372 */
373 if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
374 optind++;
375 place = EMSG;
376 /*
377 * We found an option (--), so if we skipped
378 * non-options, we have to permute.
379 */
380 if (nonopt_end != -1) {
381 permute_args(nonopt_start, nonopt_end,
382 optind, nargv);
383 optind -= nonopt_end - nonopt_start;
384 }
385 nonopt_start = nonopt_end = -1;
386 return (-1);
387 }
388 }
389
390 /*
391 * Check long options if:
392 * 1) we were passed some
393 * 2) the arg is not just "-"
394 * 3) either the arg starts with -- we are getopt_long_only()
395 */
396 if (long_options != NULL && place != nargv[optind] &&
397 (*place == '-' || (flags & FLAG_LONGONLY))) {
398 short_too = 0;
399 if (*place == '-')
400 place++; /* --foo long option */
401 else if (*place != ':' && strchr(options, *place) != NULL)
402 short_too = 1; /* could be short option too */
403
404 optchar = parse_long_options(nargv, options, long_options,
405 idx, short_too);
406 if (optchar != -1) {
407 place = EMSG;
408 return (optchar);
409 }
410 }
411
412 if ((optchar = (int)*place++) == (int)':' ||
413 (optchar == (int)'-' && *place != '\0') ||
414 (oli = strchr(options, optchar)) == NULL) {
415 /*
416 * If the user specified "-" and '-' isn't listed in
417 * options, return -1 (non-option) as per POSIX.
418 * Otherwise, it is an unknown option character (or ':').
419 */
420 if (optchar == (int)'-' && *place == '\0')
421 return (-1);
422 if (!*place)
423 ++optind;
424 if (PRINT_ERROR)
425 warnx(illoptchar, optchar);
426 optopt = optchar;
427 return (BADCH);
428 }
429 if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
430 /* -W long-option */
431 if (*place) /* no space */
432 /* NOTHING */;
433 else if (++optind >= nargc) { /* no arg */
434 place = EMSG;
435 if (PRINT_ERROR)
436 warnx(recargchar, optchar);
437 optopt = optchar;
438 return (BADARG);
439 } else /* white space */
440 place = nargv[optind];
441 optchar = parse_long_options(nargv, options, long_options,
442 idx, 0);
443 place = EMSG;
444 return (optchar);
445 }
446 if (*++oli != ':') { /* doesn't take argument */
447 if (!*place)
448 ++optind;
449 } else { /* takes (optional) argument */
450 optarg = NULL;
451 if (*place) /* no white space */
452 optarg = place;
453 else if (oli[1] != ':') { /* arg not optional */
454 if (++optind >= nargc) { /* no arg */
455 place = EMSG;
456 if (PRINT_ERROR)
457 warnx(recargchar, optchar);
458 optopt = optchar;
459 return (BADARG);
460 } else
461 optarg = nargv[optind];
462 }
463 place = EMSG;
464 ++optind;
465 }
466 /* dump back option letter */
467 return (optchar);
468}
469
470#ifdef REPLACE_GETOPT
471/*
472 * getopt --
473 * Parse argc/argv argument vector.
474 *
475 * [eventually this will replace the BSD getopt]
476 */
477int
478getopt(int nargc, char * const *nargv, const char *options)
479{
480
481 /*
482 * We don't pass FLAG_PERMUTE to getopt_internal() since
483 * the BSD getopt(3) (unlike GNU) has never done this.
484 *
485 * Furthermore, since many privileged programs call getopt()
486 * before dropping privileges it makes sense to keep things
487 * as simple (and bug-free) as possible.
488 */
489 return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
490}
491#endif /* REPLACE_GETOPT */
492
493/*
494 * getopt_long --
495 * Parse argc/argv argument vector.
496 */
497int
498getopt_long(int nargc, char * const *nargv, const char *options,
499 const struct option *long_options, int *idx)
500{
501
502 return (getopt_internal(nargc, nargv, options, long_options, idx,
503 FLAG_PERMUTE));
504}
505
506/*
507 * getopt_long_only --
508 * Parse argc/argv argument vector.
509 */
510int
511getopt_long_only(int nargc, char * const *nargv, const char *options,
512 const struct option *long_options, int *idx)
513{
514
515 return (getopt_internal(nargc, nargv, options, long_options, idx,
516 FLAG_PERMUTE|FLAG_LONGONLY));
517}