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 // next line modified D. Lemire (last modified on June 1st 2021)
116 static char EMSG[] = "";
117
118 static int getopt_internal(int, char * const *, const char *,
119 const struct option *, int *, int);
120 static int parse_long_options(char * const *, const char *,
121 const struct option *, int *, int);
122 static int gcd(int, int);
123 static void permute_args(int, int, int, char * const *);
124
125 static char *place = EMSG; /* option letter processing */
126
127 /* XXX: set optreset to 1 rather than these two */
128 static int nonopt_start = -1; /* first non option argument (for permute) */
129 static int nonopt_end = -1; /* first option after non options (for permute) */
130
131 /* Error messages */
132 static const char recargchar[] = "option requires an argument -- %c";
133 static const char recargstring[] = "option requires an argument -- %s";
134 static const char ambig[] = "ambiguous option -- %.*s";
135 static const char noarg[] = "option doesn't take an argument -- %.*s";
136 static const char illoptchar[] = "unknown option -- %c";
137 static const char illoptstring[] = "unknown option -- %s";
138
139 static void
_vwarnx(const char * fmt,va_list ap)140 _vwarnx(const char *fmt,va_list ap)
141 {
142 (void)fprintf(stderr,"%s: ",__progname);
143 if (fmt != NULL)
144 (void)vfprintf(stderr,fmt,ap);
145 (void)fprintf(stderr,"\n");
146 }
147
148 static void
warnx(const char * fmt,...)149 warnx(const char *fmt,...)
150 {
151 va_list ap;
152 va_start(ap,fmt);
153 _vwarnx(fmt,ap);
154 va_end(ap);
155 }
156
157 /*
158 * Compute the greatest common divisor of a and b.
159 */
160 static int
gcd(int a,int b)161 gcd(int a, int b)
162 {
163 int c;
164
165 c = a % b;
166 while (c != 0) {
167 a = b;
168 b = c;
169 c = a % b;
170 }
171
172 return (b);
173 }
174
175 /*
176 * Exchange the block from nonopt_start to nonopt_end with the block
177 * from nonopt_end to opt_end (keeping the same order of arguments
178 * in each block).
179 */
180 static void
permute_args(int panonopt_start,int panonopt_end,int opt_end,char * const * nargv)181 permute_args(int panonopt_start, int panonopt_end, int opt_end,
182 char * const *nargv)
183 {
184 int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
185 char *swap;
186
187 /*
188 * compute lengths of blocks and number and size of cycles
189 */
190 nnonopts = panonopt_end - panonopt_start;
191 nopts = opt_end - panonopt_end;
192 ncycle = gcd(nnonopts, nopts);
193 cyclelen = (opt_end - panonopt_start) / ncycle;
194
195 for (i = 0; i < ncycle; i++) {
196 cstart = panonopt_end+i;
197 pos = cstart;
198 for (j = 0; j < cyclelen; j++) {
199 if (pos >= panonopt_end)
200 pos -= nnonopts;
201 else
202 pos += nopts;
203 swap = nargv[pos];
204 /* LINTED const cast */
205 ((char **) nargv)[pos] = nargv[cstart];
206 /* LINTED const cast */
207 ((char **)nargv)[cstart] = swap;
208 }
209 }
210 }
211
212 #ifdef REPLACE_GETOPT
213 /*
214 * getopt --
215 * Parse argc/argv argument vector.
216 *
217 * [eventually this will replace the BSD getopt]
218 */
219 int
getopt(int nargc,char * const * nargv,const char * options)220 getopt(int nargc, char * const *nargv, const char *options)
221 {
222
223 /*
224 * We don't pass FLAG_PERMUTE to getopt_internal() since
225 * the BSD getopt(3) (unlike GNU) has never done this.
226 *
227 * Furthermore, since many privileged programs call getopt()
228 * before dropping privileges it makes sense to keep things
229 * as simple (and bug-free) as possible.
230 */
231 return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
232 }
233 #endif /* REPLACE_GETOPT */
234
235 //extern int getopt(int nargc, char * const *nargv, const char *options);
236
237 #ifdef _BSD_SOURCE
238 /*
239 * BSD adds the non-standard `optreset' feature, for reinitialisation
240 * of `getopt' parsing. We support this feature, for applications which
241 * proclaim their BSD heritage, before including this header; however,
242 * to maintain portability, developers are advised to avoid it.
243 */
244 # define optreset __mingw_optreset
245 extern int optreset;
246 #endif
247 #ifdef __cplusplus
248 }
249 #endif
250 /*
251 * POSIX requires the `getopt' API to be specified in `unistd.h';
252 * thus, `unistd.h' includes this header. However, we do not want
253 * to expose the `getopt_long' or `getopt_long_only' APIs, when
254 * included in this manner. Thus, close the standard __GETOPT_H__
255 * declarations block, and open an additional __GETOPT_LONG_H__
256 * specific block, only when *not* __UNISTD_H_SOURCED__, in which
257 * to declare the extended API.
258 */
259 #endif /* !defined(__GETOPT_H__) */
260
261 #if !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__)
262 #define __GETOPT_LONG_H__
263
264 #ifdef __cplusplus
265 extern "C" {
266 #endif
267
268 struct option /* specification for a long form option... */
269 {
270 const char *name; /* option name, without leading hyphens */
271 int has_arg; /* does it take an argument? */
272 int *flag; /* where to save its status, or NULL */
273 int val; /* its associated status value */
274 };
275
276 enum /* permitted values for its `has_arg' field... */
277 {
278 no_argument = 0, /* option never takes an argument */
279 required_argument, /* option always requires an argument */
280 optional_argument /* option may take an argument */
281 };
282
283 /*
284 * parse_long_options --
285 * Parse long options in argc/argv argument vector.
286 * Returns -1 if short_too is set and the option does not match long_options.
287 */
288 static int
parse_long_options(char * const * nargv,const char * options,const struct option * long_options,int * idx,int short_too)289 parse_long_options(char * const *nargv, const char *options,
290 const struct option *long_options, int *idx, int short_too)
291 {
292 char *current_argv, *has_equal;
293 size_t current_argv_len;
294 int i, ambiguous, match;
295
296 #define IDENTICAL_INTERPRETATION(_x, _y) \
297 (long_options[(_x)].has_arg == long_options[(_y)].has_arg && \
298 long_options[(_x)].flag == long_options[(_y)].flag && \
299 long_options[(_x)].val == long_options[(_y)].val)
300
301 current_argv = place;
302 match = -1;
303 ambiguous = 0;
304
305 optind++;
306
307 if ((has_equal = strchr(current_argv, '=')) != NULL) {
308 /* argument found (--option=arg) */
309 current_argv_len = has_equal - current_argv;
310 has_equal++;
311 } else
312 current_argv_len = strlen(current_argv);
313
314 for (i = 0; long_options[i].name; i++) {
315 /* find matching long option */
316 if (strncmp(current_argv, long_options[i].name,
317 current_argv_len))
318 continue;
319
320 if (strlen(long_options[i].name) == current_argv_len) {
321 /* exact match */
322 match = i;
323 ambiguous = 0;
324 break;
325 }
326 /*
327 * If this is a known short option, don't allow
328 * a partial match of a single character.
329 */
330 if (short_too && current_argv_len == 1)
331 continue;
332
333 if (match == -1) /* partial match */
334 match = i;
335 else if (!IDENTICAL_INTERPRETATION(i, match))
336 ambiguous = 1;
337 }
338 if (ambiguous) {
339 /* ambiguous abbreviation */
340 if (PRINT_ERROR)
341 warnx(ambig, (int)current_argv_len,
342 current_argv);
343 optopt = 0;
344 return (BADCH);
345 }
346 if (match != -1) { /* option found */
347 if (long_options[match].has_arg == no_argument
348 && has_equal) {
349 if (PRINT_ERROR)
350 warnx(noarg, (int)current_argv_len,
351 current_argv);
352 /*
353 * XXX: GNU sets optopt to val regardless of flag
354 */
355 if (long_options[match].flag == NULL)
356 optopt = long_options[match].val;
357 else
358 optopt = 0;
359 return (BADARG);
360 }
361 if (long_options[match].has_arg == required_argument ||
362 long_options[match].has_arg == optional_argument) {
363 if (has_equal)
364 optarg = has_equal;
365 else if (long_options[match].has_arg ==
366 required_argument) {
367 /*
368 * optional argument doesn't use next nargv
369 */
370 optarg = nargv[optind++];
371 }
372 }
373 if ((long_options[match].has_arg == required_argument)
374 && (optarg == NULL)) {
375 /*
376 * Missing argument; leading ':' indicates no error
377 * should be generated.
378 */
379 if (PRINT_ERROR)
380 warnx(recargstring,
381 current_argv);
382 /*
383 * XXX: GNU sets optopt to val regardless of flag
384 */
385 if (long_options[match].flag == NULL)
386 optopt = long_options[match].val;
387 else
388 optopt = 0;
389 --optind;
390 return (BADARG);
391 }
392 } else { /* unknown option */
393 if (short_too) {
394 --optind;
395 return (-1);
396 }
397 if (PRINT_ERROR)
398 warnx(illoptstring, current_argv);
399 optopt = 0;
400 return (BADCH);
401 }
402 if (idx)
403 *idx = match;
404 if (long_options[match].flag) {
405 *long_options[match].flag = long_options[match].val;
406 return (0);
407 } else
408 return (long_options[match].val);
409 #undef IDENTICAL_INTERPRETATION
410 }
411
412 /*
413 * getopt_internal --
414 * Parse argc/argv argument vector. Called by user level routines.
415 */
416 static int
getopt_internal(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx,int flags)417 getopt_internal(int nargc, char * const *nargv, const char *options,
418 const struct option *long_options, int *idx, int flags)
419 {
420 char *oli; /* option letter list index */
421 int optchar, short_too;
422 static int posixly_correct = -1;
423
424 if (options == NULL)
425 return (-1);
426
427 /*
428 * XXX Some GNU programs (like cvs) set optind to 0 instead of
429 * XXX using optreset. Work around this braindamage.
430 */
431 if (optind == 0)
432 optind = optreset = 1;
433
434 /*
435 * Disable GNU extensions if POSIXLY_CORRECT is set or options
436 * string begins with a '+'.
437 *
438 * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or
439 * optreset != 0 for GNU compatibility.
440 */
441 if (posixly_correct == -1 || optreset != 0)
442 posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
443 if (*options == '-')
444 flags |= FLAG_ALLARGS;
445 else if (posixly_correct || *options == '+')
446 flags &= ~FLAG_PERMUTE;
447 if (*options == '+' || *options == '-')
448 options++;
449
450 optarg = NULL;
451 if (optreset)
452 nonopt_start = nonopt_end = -1;
453 start:
454 if (optreset || !*place) { /* update scanning pointer */
455 optreset = 0;
456 if (optind >= nargc) { /* end of argument vector */
457 place = EMSG;
458 if (nonopt_end != -1) {
459 /* do permutation, if we have to */
460 permute_args(nonopt_start, nonopt_end,
461 optind, nargv);
462 optind -= nonopt_end - nonopt_start;
463 }
464 else if (nonopt_start != -1) {
465 /*
466 * If we skipped non-options, set optind
467 * to the first of them.
468 */
469 optind = nonopt_start;
470 }
471 nonopt_start = nonopt_end = -1;
472 return (-1);
473 }
474 if (*(place = nargv[optind]) != '-' ||
475 (place[1] == '\0' && strchr(options, '-') == NULL)) {
476 place = EMSG; /* found non-option */
477 if (flags & FLAG_ALLARGS) {
478 /*
479 * GNU extension:
480 * return non-option as argument to option 1
481 */
482 optarg = nargv[optind++];
483 return (INORDER);
484 }
485 if (!(flags & FLAG_PERMUTE)) {
486 /*
487 * If no permutation wanted, stop parsing
488 * at first non-option.
489 */
490 return (-1);
491 }
492 /* do permutation */
493 if (nonopt_start == -1)
494 nonopt_start = optind;
495 else if (nonopt_end != -1) {
496 permute_args(nonopt_start, nonopt_end,
497 optind, nargv);
498 nonopt_start = optind -
499 (nonopt_end - nonopt_start);
500 nonopt_end = -1;
501 }
502 optind++;
503 /* process next argument */
504 goto start;
505 }
506 if (nonopt_start != -1 && nonopt_end == -1)
507 nonopt_end = optind;
508
509 /*
510 * If we have "-" do nothing, if "--" we are done.
511 */
512 if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
513 optind++;
514 place = EMSG;
515 /*
516 * We found an option (--), so if we skipped
517 * non-options, we have to permute.
518 */
519 if (nonopt_end != -1) {
520 permute_args(nonopt_start, nonopt_end,
521 optind, nargv);
522 optind -= nonopt_end - nonopt_start;
523 }
524 nonopt_start = nonopt_end = -1;
525 return (-1);
526 }
527 }
528
529 /*
530 * Check long options if:
531 * 1) we were passed some
532 * 2) the arg is not just "-"
533 * 3) either the arg starts with -- we are getopt_long_only()
534 */
535 if (long_options != NULL && place != nargv[optind] &&
536 (*place == '-' || (flags & FLAG_LONGONLY))) {
537 short_too = 0;
538 if (*place == '-')
539 place++; /* --foo long option */
540 else if (*place != ':' && strchr(options, *place) != NULL)
541 short_too = 1; /* could be short option too */
542
543 optchar = parse_long_options(nargv, options, long_options,
544 idx, short_too);
545 if (optchar != -1) {
546 place = EMSG;
547 return (optchar);
548 }
549 }
550
551 if ((optchar = (int)*place++) == (int)':' ||
552 (optchar == (int)'-' && *place != '\0') ||
553 (oli = (char*)strchr(options, optchar)) == NULL) {
554 /*
555 * If the user specified "-" and '-' isn't listed in
556 * options, return -1 (non-option) as per POSIX.
557 * Otherwise, it is an unknown option character (or ':').
558 */
559 if (optchar == (int)'-' && *place == '\0')
560 return (-1);
561 if (!*place)
562 ++optind;
563 if (PRINT_ERROR)
564 warnx(illoptchar, optchar);
565 optopt = optchar;
566 return (BADCH);
567 }
568 if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
569 /* -W long-option */
570 if (*place) /* no space */
571 /* NOTHING */;
572 else if (++optind >= nargc) { /* no arg */
573 place = EMSG;
574 if (PRINT_ERROR)
575 warnx(recargchar, optchar);
576 optopt = optchar;
577 return (BADARG);
578 } else /* white space */
579 place = nargv[optind];
580 optchar = parse_long_options(nargv, options, long_options,
581 idx, 0);
582 place = EMSG;
583 return (optchar);
584 }
585 if (*++oli != ':') { /* doesn't take argument */
586 if (!*place)
587 ++optind;
588 } else { /* takes (optional) argument */
589 optarg = NULL;
590 if (*place) /* no white space */
591 optarg = place;
592 else if (oli[1] != ':') { /* arg not optional */
593 if (++optind >= nargc) { /* no arg */
594 place = EMSG;
595 if (PRINT_ERROR)
596 warnx(recargchar, optchar);
597 optopt = optchar;
598 return (BADARG);
599 } else
600 optarg = nargv[optind];
601 }
602 place = EMSG;
603 ++optind;
604 }
605 /* dump back option letter */
606 return (optchar);
607 }
608
609 /*
610 * getopt_long --
611 * Parse argc/argv argument vector.
612 */
613 int
getopt_long(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx)614 getopt_long(int nargc, char * const *nargv, const char *options,
615 const struct option *long_options, int *idx)
616 {
617
618 return (getopt_internal(nargc, nargv, options, long_options, idx,
619 FLAG_PERMUTE));
620 }
621
622 /*
623 * getopt_long_only --
624 * Parse argc/argv argument vector.
625 */
626 int
getopt_long_only(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx)627 getopt_long_only(int nargc, char * const *nargv, const char *options,
628 const struct option *long_options, int *idx)
629 {
630
631 return (getopt_internal(nargc, nargv, options, long_options, idx,
632 FLAG_PERMUTE|FLAG_LONGONLY));
633 }
634
635 //extern int getopt_long(int nargc, char * const *nargv, const char *options,
636 // const struct option *long_options, int *idx);
637 //extern int getopt_long_only(int nargc, char * const *nargv, const char *options,
638 // const struct option *long_options, int *idx);
639 /*
640 * Previous MinGW implementation had...
641 */
642 #ifndef HAVE_DECL_GETOPT
643 /*
644 * ...for the long form API only; keep this for compatibility.
645 */
646 # define HAVE_DECL_GETOPT 1
647 #endif
648
649 #ifdef __cplusplus
650 }
651 #endif
652
653 #endif /* !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) */