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