1 /**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 /**
20 * DISCLAIMER
21 * This file is part of the mingw-w64 runtime package.
22 *
23 * The mingw-w64 runtime package and its code is distributed in the hope that it
24 * will be useful but WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESSED OR
25 * IMPLIED ARE HEREBY DISCLAIMED. This includes but is not limited to
26 * warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
27 */
28
29 /*
30 * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
31 *
32 * Permission to use, copy, modify, and distribute this software for any
33 * purpose with or without fee is hereby granted, provided that the above
34 * copyright notice and this permission notice appear in all copies.
35 *
36 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
37 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
38 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
39 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
40 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
41 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
42 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
43 *
44 * Sponsored in part by the Defense Advanced Research Projects
45 * Agency (DARPA) and Air Force Research Laboratory, Air Force
46 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
47 */
48
49 /*-
50 * Copyright (c) 2000 The NetBSD Foundation, Inc.
51 * All rights reserved.
52 *
53 * This code is derived from software contributed to The NetBSD Foundation
54 * by Dieter Baron and Thomas Klausner.
55 *
56 * Redistribution and use in source and binary forms, with or without
57 * modification, are permitted provided that the following conditions
58 * are met:
59 * 1. Redistributions of source code must retain the above copyright
60 * notice, this list of conditions and the following disclaimer.
61 * 2. Redistributions in binary form must reproduce the above copyright
62 * notice, this list of conditions and the following disclaimer in the
63 * documentation and/or other materials provided with the distribution.
64 *
65 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
66 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
67 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
68 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
69 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
70 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
71 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
72 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
73 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
74 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
75 * POSSIBILITY OF SUCH DAMAGE.
76 */
77
78 #ifndef __GETOPT_H__
79
80 #pragma warning(disable:4996);
81
82 #define __GETOPT_H__
83
84 /* All the headers include this file. */
85 #include <crtdefs.h>
86 #include <errno.h>
87 #include <stdlib.h>
88 #include <string.h>
89 #include <stdarg.h>
90 #include <stdio.h>
91 #include <windows.h>
92
93 #ifdef __cplusplus
94 extern "C" {
95 #endif
96
97 #define REPLACE_GETOPT /* use this getopt as the system getopt(3) */
98
99 #ifdef REPLACE_GETOPT
100 int opterr = 1; /* if error message should be printed */
101 int optind = 1; /* index into parent argv vector */
102 int optopt = '?'; /* character checked for validity */
103 #undef optreset /* see getopt.h */
104 #define optreset __mingw_optreset
105 int optreset; /* reset getopt */
106 char *optarg; /* argument associated with option */
107 #endif
108
109 //extern int optind; /* index of first non-option in argv */
110 //extern int optopt; /* single option character, as parsed */
111 //extern int opterr; /* flag to enable built-in diagnostics... */
112 // /* (user may set to zero, to suppress) */
113 //
114 //extern char *optarg; /* pointer to argument of current option */
115
116 #define PRINT_ERROR ((opterr) && (*options != ':'))
117
118 #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
119 #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
120 #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
121
122 /* return values */
123 #define BADCH (int)'?'
124 #define BADARG ((*options == ':') ? (int)':' : (int)'?')
125 #define INORDER (int)1
126
127 #ifndef __CYGWIN__
128 #define __progname __argv[0]
129 #else
130 extern char __declspec(dllimport) *__progname;
131 #endif
132
133 #ifdef __CYGWIN__
134 static char EMSG[] = "";
135 #else
136 #define EMSG ""
137 #endif
138
139 static int getopt_internal(int, char * const *, const char *,
140 const struct option *, int *, int);
141 static int parse_long_options(char * const *, const char *,
142 const struct option *, int *, int);
143 static int gcd(int, int);
144 static void permute_args(int, int, int, char * const *);
145
146 static char *place = EMSG; /* option letter processing */
147
148 /* XXX: set optreset to 1 rather than these two */
149 static int nonopt_start = -1; /* first non option argument (for permute) */
150 static int nonopt_end = -1; /* first option after non options (for permute) */
151
152 /* Error messages */
153 static const char recargchar[] = "option requires an argument -- %c";
154 static const char recargstring[] = "option requires an argument -- %s";
155 static const char ambig[] = "ambiguous option -- %.*s";
156 static const char noarg[] = "option doesn't take an argument -- %.*s";
157 static const char illoptchar[] = "unknown option -- %c";
158 static const char illoptstring[] = "unknown option -- %s";
159
160 static void
_vwarnx(const char * fmt,va_list ap)161 _vwarnx(const char *fmt,va_list ap)
162 {
163 (void)fprintf(stderr,"%s: ",__progname);
164 if (fmt != NULL)
165 (void)vfprintf(stderr,fmt,ap);
166 (void)fprintf(stderr,"\n");
167 }
168
169 static void
warnx(const char * fmt,...)170 warnx(const char *fmt,...)
171 {
172 va_list ap;
173 va_start(ap,fmt);
174 _vwarnx(fmt,ap);
175 va_end(ap);
176 }
177
178 /*
179 * Compute the greatest common divisor of a and b.
180 */
181 static int
gcd(int a,int b)182 gcd(int a, int b)
183 {
184 int c;
185
186 c = a % b;
187 while (c != 0) {
188 a = b;
189 b = c;
190 c = a % b;
191 }
192
193 return (b);
194 }
195
196 /*
197 * Exchange the block from nonopt_start to nonopt_end with the block
198 * from nonopt_end to opt_end (keeping the same order of arguments
199 * in each block).
200 */
201 static void
permute_args(int panonopt_start,int panonopt_end,int opt_end,char * const * nargv)202 permute_args(int panonopt_start, int panonopt_end, int opt_end,
203 char * const *nargv)
204 {
205 int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
206 char *swap;
207
208 /*
209 * compute lengths of blocks and number and size of cycles
210 */
211 nnonopts = panonopt_end - panonopt_start;
212 nopts = opt_end - panonopt_end;
213 ncycle = gcd(nnonopts, nopts);
214 cyclelen = (opt_end - panonopt_start) / ncycle;
215
216 for (i = 0; i < ncycle; i++) {
217 cstart = panonopt_end+i;
218 pos = cstart;
219 for (j = 0; j < cyclelen; j++) {
220 if (pos >= panonopt_end)
221 pos -= nnonopts;
222 else
223 pos += nopts;
224 swap = nargv[pos];
225 /* LINTED const cast */
226 ((char **) nargv)[pos] = nargv[cstart];
227 /* LINTED const cast */
228 ((char **)nargv)[cstart] = swap;
229 }
230 }
231 }
232
233 #ifdef REPLACE_GETOPT
234 /*
235 * getopt --
236 * Parse argc/argv argument vector.
237 *
238 * [eventually this will replace the BSD getopt]
239 */
240 int
getopt(int nargc,char * const * nargv,const char * options)241 getopt(int nargc, char * const *nargv, const char *options)
242 {
243
244 /*
245 * We don't pass FLAG_PERMUTE to getopt_internal() since
246 * the BSD getopt(3) (unlike GNU) has never done this.
247 *
248 * Furthermore, since many privileged programs call getopt()
249 * before dropping privileges it makes sense to keep things
250 * as simple (and bug-free) as possible.
251 */
252 return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
253 }
254 #endif /* REPLACE_GETOPT */
255
256 //extern int getopt(int nargc, char * const *nargv, const char *options);
257
258 #ifdef _BSD_SOURCE
259 /*
260 * BSD adds the non-standard `optreset' feature, for reinitialisation
261 * of `getopt' parsing. We support this feature, for applications which
262 * proclaim their BSD heritage, before including this header; however,
263 * to maintain portability, developers are advised to avoid it.
264 */
265 # define optreset __mingw_optreset
266 extern int optreset;
267 #endif
268 #ifdef __cplusplus
269 }
270 #endif
271 /*
272 * POSIX requires the `getopt' API to be specified in `unistd.h';
273 * thus, `unistd.h' includes this header. However, we do not want
274 * to expose the `getopt_long' or `getopt_long_only' APIs, when
275 * included in this manner. Thus, close the standard __GETOPT_H__
276 * declarations block, and open an additional __GETOPT_LONG_H__
277 * specific block, only when *not* __UNISTD_H_SOURCED__, in which
278 * to declare the extended API.
279 */
280 #endif /* !defined(__GETOPT_H__) */
281
282 #if !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__)
283 #define __GETOPT_LONG_H__
284
285 #ifdef __cplusplus
286 extern "C" {
287 #endif
288
289 struct option /* specification for a long form option... */
290 {
291 const char *name; /* option name, without leading hyphens */
292 int has_arg; /* does it take an argument? */
293 int *flag; /* where to save its status, or NULL */
294 int val; /* its associated status value */
295 };
296
297 enum /* permitted values for its `has_arg' field... */
298 {
299 no_argument = 0, /* option never takes an argument */
300 required_argument, /* option always requires an argument */
301 optional_argument /* option may take an argument */
302 };
303
304 /*
305 * parse_long_options --
306 * Parse long options in argc/argv argument vector.
307 * Returns -1 if short_too is set and the option does not match long_options.
308 */
309 static int
parse_long_options(char * const * nargv,const char * options,const struct option * long_options,int * idx,int short_too)310 parse_long_options(char * const *nargv, const char *options,
311 const struct option *long_options, int *idx, int short_too)
312 {
313 char *current_argv, *has_equal;
314 size_t current_argv_len;
315 int i, ambiguous, match;
316
317 #define IDENTICAL_INTERPRETATION(_x, _y) \
318 (long_options[(_x)].has_arg == long_options[(_y)].has_arg && \
319 long_options[(_x)].flag == long_options[(_y)].flag && \
320 long_options[(_x)].val == long_options[(_y)].val)
321
322 current_argv = place;
323 match = -1;
324 ambiguous = 0;
325
326 optind++;
327
328 if ((has_equal = strchr(current_argv, '=')) != NULL) {
329 /* argument found (--option=arg) */
330 current_argv_len = has_equal - current_argv;
331 has_equal++;
332 } else
333 current_argv_len = strlen(current_argv);
334
335 for (i = 0; long_options[i].name; i++) {
336 /* find matching long option */
337 if (strncmp(current_argv, long_options[i].name,
338 current_argv_len))
339 continue;
340
341 if (strlen(long_options[i].name) == current_argv_len) {
342 /* exact match */
343 match = i;
344 ambiguous = 0;
345 break;
346 }
347 /*
348 * If this is a known short option, don't allow
349 * a partial match of a single character.
350 */
351 if (short_too && current_argv_len == 1)
352 continue;
353
354 if (match == -1) /* partial match */
355 match = i;
356 else if (!IDENTICAL_INTERPRETATION(i, match))
357 ambiguous = 1;
358 }
359 if (ambiguous) {
360 /* ambiguous abbreviation */
361 if (PRINT_ERROR)
362 warnx(ambig, (int)current_argv_len,
363 current_argv);
364 optopt = 0;
365 return (BADCH);
366 }
367 if (match != -1) { /* option found */
368 if (long_options[match].has_arg == no_argument
369 && has_equal) {
370 if (PRINT_ERROR)
371 warnx(noarg, (int)current_argv_len,
372 current_argv);
373 /*
374 * XXX: GNU sets optopt to val regardless of flag
375 */
376 if (long_options[match].flag == NULL)
377 optopt = long_options[match].val;
378 else
379 optopt = 0;
380 return (BADARG);
381 }
382 if (long_options[match].has_arg == required_argument ||
383 long_options[match].has_arg == optional_argument) {
384 if (has_equal)
385 optarg = has_equal;
386 else if (long_options[match].has_arg ==
387 required_argument) {
388 /*
389 * optional argument doesn't use next nargv
390 */
391 optarg = nargv[optind++];
392 }
393 }
394 if ((long_options[match].has_arg == required_argument)
395 && (optarg == NULL)) {
396 /*
397 * Missing argument; leading ':' indicates no error
398 * should be generated.
399 */
400 if (PRINT_ERROR)
401 warnx(recargstring,
402 current_argv);
403 /*
404 * XXX: GNU sets optopt to val regardless of flag
405 */
406 if (long_options[match].flag == NULL)
407 optopt = long_options[match].val;
408 else
409 optopt = 0;
410 --optind;
411 return (BADARG);
412 }
413 } else { /* unknown option */
414 if (short_too) {
415 --optind;
416 return (-1);
417 }
418 if (PRINT_ERROR)
419 warnx(illoptstring, current_argv);
420 optopt = 0;
421 return (BADCH);
422 }
423 if (idx)
424 *idx = match;
425 if (long_options[match].flag) {
426 *long_options[match].flag = long_options[match].val;
427 return (0);
428 } else
429 return (long_options[match].val);
430 #undef IDENTICAL_INTERPRETATION
431 }
432
433 /*
434 * getopt_internal --
435 * Parse argc/argv argument vector. Called by user level routines.
436 */
437 static int
getopt_internal(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx,int flags)438 getopt_internal(int nargc, char * const *nargv, const char *options,
439 const struct option *long_options, int *idx, int flags)
440 {
441 char *oli; /* option letter list index */
442 int optchar, short_too;
443 static int posixly_correct = -1;
444
445 if (options == NULL)
446 return (-1);
447
448 /*
449 * XXX Some GNU programs (like cvs) set optind to 0 instead of
450 * XXX using optreset. Work around this braindamage.
451 */
452 if (optind == 0)
453 optind = optreset = 1;
454
455 /*
456 * Disable GNU extensions if POSIXLY_CORRECT is set or options
457 * string begins with a '+'.
458 *
459 * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or
460 * optreset != 0 for GNU compatibility.
461 */
462 if (posixly_correct == -1 || optreset != 0)
463 posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
464 if (*options == '-')
465 flags |= FLAG_ALLARGS;
466 else if (posixly_correct || *options == '+')
467 flags &= ~FLAG_PERMUTE;
468 if (*options == '+' || *options == '-')
469 options++;
470
471 optarg = NULL;
472 if (optreset)
473 nonopt_start = nonopt_end = -1;
474 start:
475 if (optreset || !*place) { /* update scanning pointer */
476 optreset = 0;
477 if (optind >= nargc) { /* end of argument vector */
478 place = EMSG;
479 if (nonopt_end != -1) {
480 /* do permutation, if we have to */
481 permute_args(nonopt_start, nonopt_end,
482 optind, nargv);
483 optind -= nonopt_end - nonopt_start;
484 }
485 else if (nonopt_start != -1) {
486 /*
487 * If we skipped non-options, set optind
488 * to the first of them.
489 */
490 optind = nonopt_start;
491 }
492 nonopt_start = nonopt_end = -1;
493 return (-1);
494 }
495 if (*(place = nargv[optind]) != '-' ||
496 (place[1] == '\0' && strchr(options, '-') == NULL)) {
497 place = EMSG; /* found non-option */
498 if (flags & FLAG_ALLARGS) {
499 /*
500 * GNU extension:
501 * return non-option as argument to option 1
502 */
503 optarg = nargv[optind++];
504 return (INORDER);
505 }
506 if (!(flags & FLAG_PERMUTE)) {
507 /*
508 * If no permutation wanted, stop parsing
509 * at first non-option.
510 */
511 return (-1);
512 }
513 /* do permutation */
514 if (nonopt_start == -1)
515 nonopt_start = optind;
516 else if (nonopt_end != -1) {
517 permute_args(nonopt_start, nonopt_end,
518 optind, nargv);
519 nonopt_start = optind -
520 (nonopt_end - nonopt_start);
521 nonopt_end = -1;
522 }
523 optind++;
524 /* process next argument */
525 goto start;
526 }
527 if (nonopt_start != -1 && nonopt_end == -1)
528 nonopt_end = optind;
529
530 /*
531 * If we have "-" do nothing, if "--" we are done.
532 */
533 if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
534 optind++;
535 place = EMSG;
536 /*
537 * We found an option (--), so if we skipped
538 * non-options, we have to permute.
539 */
540 if (nonopt_end != -1) {
541 permute_args(nonopt_start, nonopt_end,
542 optind, nargv);
543 optind -= nonopt_end - nonopt_start;
544 }
545 nonopt_start = nonopt_end = -1;
546 return (-1);
547 }
548 }
549
550 /*
551 * Check long options if:
552 * 1) we were passed some
553 * 2) the arg is not just "-"
554 * 3) either the arg starts with -- we are getopt_long_only()
555 */
556 if (long_options != NULL && place != nargv[optind] &&
557 (*place == '-' || (flags & FLAG_LONGONLY))) {
558 short_too = 0;
559 if (*place == '-')
560 place++; /* --foo long option */
561 else if (*place != ':' && strchr(options, *place) != NULL)
562 short_too = 1; /* could be short option too */
563
564 optchar = parse_long_options(nargv, options, long_options,
565 idx, short_too);
566 if (optchar != -1) {
567 place = EMSG;
568 return (optchar);
569 }
570 }
571
572 if ((optchar = (int)*place++) == (int)':' ||
573 (optchar == (int)'-' && *place != '\0') ||
574 (oli = (char*)strchr(options, optchar)) == NULL) {
575 /*
576 * If the user specified "-" and '-' isn't listed in
577 * options, return -1 (non-option) as per POSIX.
578 * Otherwise, it is an unknown option character (or ':').
579 */
580 if (optchar == (int)'-' && *place == '\0')
581 return (-1);
582 if (!*place)
583 ++optind;
584 if (PRINT_ERROR)
585 warnx(illoptchar, optchar);
586 optopt = optchar;
587 return (BADCH);
588 }
589 if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
590 /* -W long-option */
591 if (*place) /* no space */
592 /* NOTHING */;
593 else if (++optind >= nargc) { /* no arg */
594 place = EMSG;
595 if (PRINT_ERROR)
596 warnx(recargchar, optchar);
597 optopt = optchar;
598 return (BADARG);
599 } else /* white space */
600 place = nargv[optind];
601 optchar = parse_long_options(nargv, options, long_options,
602 idx, 0);
603 place = EMSG;
604 return (optchar);
605 }
606 if (*++oli != ':') { /* doesn't take argument */
607 if (!*place)
608 ++optind;
609 } else { /* takes (optional) argument */
610 optarg = NULL;
611 if (*place) /* no white space */
612 optarg = place;
613 else if (oli[1] != ':') { /* arg not optional */
614 if (++optind >= nargc) { /* no arg */
615 place = EMSG;
616 if (PRINT_ERROR)
617 warnx(recargchar, optchar);
618 optopt = optchar;
619 return (BADARG);
620 } else
621 optarg = nargv[optind];
622 }
623 place = EMSG;
624 ++optind;
625 }
626 /* dump back option letter */
627 return (optchar);
628 }
629
630 /*
631 * getopt_long --
632 * Parse argc/argv argument vector.
633 */
634 int
getopt_long(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx)635 getopt_long(int nargc, char * const *nargv, const char *options,
636 const struct option *long_options, int *idx)
637 {
638
639 return (getopt_internal(nargc, nargv, options, long_options, idx,
640 FLAG_PERMUTE));
641 }
642
643 /*
644 * getopt_long_only --
645 * Parse argc/argv argument vector.
646 */
647 int
getopt_long_only(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx)648 getopt_long_only(int nargc, char * const *nargv, const char *options,
649 const struct option *long_options, int *idx)
650 {
651
652 return (getopt_internal(nargc, nargv, options, long_options, idx,
653 FLAG_PERMUTE|FLAG_LONGONLY));
654 }
655
656 //extern int getopt_long(int nargc, char * const *nargv, const char *options,
657 // const struct option *long_options, int *idx);
658 //extern int getopt_long_only(int nargc, char * const *nargv, const char *options,
659 // const struct option *long_options, int *idx);
660 /*
661 * Previous MinGW implementation had...
662 */
663 #ifndef HAVE_DECL_GETOPT
664 /*
665 * ...for the long form API only; keep this for compatibility.
666 */
667 # define HAVE_DECL_GETOPT 1
668 #endif
669
670 #ifdef __cplusplus
671 }
672 #endif
673
674 #endif /* !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) */
675