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