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