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