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