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