prepare_memory bug: initialization missing
[debian/dhcpd-pools.git] / src / getopt.c
1 /* Getopt for GNU.
2    NOTE: getopt is now part of the C library, so if you don't know what
3    "Keep this file name-space clean" means, talk to drepper@gnu.org
4    before changing it!
5    Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001
6         Free Software Foundation, Inc.
7    This file is part of the GNU C Library.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2, or (at your option)
12    any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software Foundation,
21    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
22 \f
23 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
24    Ditto for AIX 3.2 and <stdlib.h>.  */
25 #ifndef _NO_PROTO
26 # define _NO_PROTO
27 #endif
28
29 #include <features.h>
30
31 #if !defined __STDC__ || !__STDC__
32 /* This is a separate conditional since some stdc systems
33    reject `defined (const)'.  */
34 # ifndef const
35 #  define const
36 # endif
37 #endif
38
39 /* Comment out all this code if we are using the GNU C Library, and are not
40    actually compiling the library itself.  This code is part of the GNU C
41    Library, but also included in many other GNU distributions.  Compiling
42    and linking in this code is a waste when using the GNU C library
43    (especially if it is a shared library).  Rather than having every GNU
44    program understand `configure --with-gnu-libc' and omit the object files,
45    it is simpler to just do this in the source for each such file.  */
46
47 #define GETOPT_INTERFACE_VERSION 2
48 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
49 # include <gnu-versions.h>
50 # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
51 #  define ELIDE_CODE
52 # endif
53 #endif
54
55 #ifndef ELIDE_CODE
56
57
58 /* This needs to come after some library #include
59    to get __GNU_LIBRARY__ defined.  */
60 #ifdef  __GNU_LIBRARY__
61 /* Don't include stdlib.h for non-GNU C libraries because some of them
62    contain conflicting prototypes for getopt.  */
63 # include <stdlib.h>
64 # include <unistd.h>
65 #endif                          /* GNU C library.  */
66
67 #ifdef VMS
68 # include <unixlib.h>
69 # if HAVE_STRING_H - 0
70 #  include <string.h>
71 # endif
72 #endif
73
74 #ifndef _
75 /* This is for other GNU distributions with internationalized messages.  */
76 # if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC
77 #  include <libintl.h>
78 #  ifndef _
79 #   define _(msgid)     gettext (msgid)
80 #  endif
81 # else
82 #  define _(msgid)      (msgid)
83 # endif
84 #endif
85
86 /* This version of `getopt' appears to the caller like standard Unix `getopt'
87    but it behaves differently for the user, since it allows the user
88    to intersperse the options with the other arguments.
89
90    As `getopt' works, it permutes the elements of ARGV so that,
91    when it is done, all the options precede everything else.  Thus
92    all application programs are extended to handle flexible argument order.
93
94    Setting the environment variable POSIXLY_CORRECT disables permutation.
95    Then the behavior is completely standard.
96
97    GNU application programs can use a third alternative mode in which
98    they can distinguish the relative order of options and other arguments.  */
99
100 #include "getopt.h"
101
102 /* For communication from `getopt' to the caller.
103    When `getopt' finds an option that takes an argument,
104    the argument value is returned here.
105    Also, when `ordering' is RETURN_IN_ORDER,
106    each non-option ARGV-element is returned here.  */
107
108 char *optarg;
109
110 /* Index in ARGV of the next element to be scanned.
111    This is used for communication to and from the caller
112    and for communication between successive calls to `getopt'.
113
114    On entry to `getopt', zero means this is the first call; initialize.
115
116    When `getopt' returns -1, this is the index of the first of the
117    non-option elements that the caller should itself scan.
118
119    Otherwise, `optind' communicates from one call to the next
120    how much of ARGV has been scanned so far.  */
121
122 /* 1003.2 says this must be 1 before any call.  */
123 int optind = 1;
124
125 /* Formerly, initialization of getopt depended on optind==0, which
126    causes problems with re-calling getopt as programs generally don't
127    know that. */
128
129 int __getopt_initialized;
130
131 /* The next char to be scanned in the option-element
132    in which the last option character we returned was found.
133    This allows us to pick up the scan where we left off.
134
135    If this is zero, or a null string, it means resume the scan
136    by advancing to the next ARGV-element.  */
137
138 static char *nextchar;
139
140 /* Callers store zero here to inhibit the error message
141    for unrecognized options.  */
142
143 int opterr = 1;
144
145 /* Set to an option character which was unrecognized.
146    This must be initialized on some systems to avoid linking in the
147    system's own getopt implementation.  */
148
149 int optopt = '?';
150
151 /* Describe how to deal with options that follow non-option ARGV-elements.
152
153    If the caller did not specify anything,
154    the default is REQUIRE_ORDER if the environment variable
155    POSIXLY_CORRECT is defined, PERMUTE otherwise.
156
157    REQUIRE_ORDER means don't recognize them as options;
158    stop option processing when the first non-option is seen.
159    This is what Unix does.
160    This mode of operation is selected by either setting the environment
161    variable POSIXLY_CORRECT, or using `+' as the first character
162    of the list of option characters.
163
164    PERMUTE is the default.  We permute the contents of ARGV as we scan,
165    so that eventually all the non-options are at the end.  This allows options
166    to be given in any order, even with programs that were not written to
167    expect this.
168
169    RETURN_IN_ORDER is an option available to programs that were written
170    to expect options and other ARGV-elements in any order and that care about
171    the ordering of the two.  We describe each non-option ARGV-element
172    as if it were the argument of an option with character code 1.
173    Using `-' as the first character of the list of option characters
174    selects this mode of operation.
175
176    The special argument `--' forces an end of option-scanning regardless
177    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
178    `--' can cause `getopt' to return -1 with `optind' != ARGC.  */
179
180 static enum {
181         REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
182 } ordering;
183
184 /* Value of POSIXLY_CORRECT environment variable.  */
185 static char *posixly_correct;
186 \f
187 #ifdef  __GNU_LIBRARY__
188 /* We want to avoid inclusion of string.h with non-GNU libraries
189    because there are many ways it can cause trouble.
190    On some systems, it contains special magic macros that don't work
191    in GCC.  */
192 # include <string.h>
193 # define my_index       strchr
194 #else
195
196 # if HAVE_STRING_H
197 #  include <string.h>
198 # else
199 #  include <strings.h>
200 # endif
201
202 /* Avoid depending on library functions or files
203    whose names are inconsistent.  */
204
205 #ifndef getenv
206 extern char *getenv();
207 #endif
208
209 static char *my_index(str, chr)
210 const char *str;
211 int chr;
212 {
213         while (*str) {
214                 if (*str == chr)
215                         return (char *) str;
216                 str++;
217         }
218         return 0;
219 }
220
221 /* If using GCC, we can safely declare strlen this way.
222    If not using GCC, it is ok not to declare it.  */
223 #ifdef __GNUC__
224 /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
225    That was relevant to code that was here before.  */
226 # if (!defined __STDC__ || !__STDC__) && !defined strlen
227 /* gcc with -traditional declares the built-in strlen to return int,
228    and has done so at least since version 2.4.5. -- rms.  */
229 extern int strlen(const char *);
230 # endif                         /* not __STDC__ */
231 #endif                          /* __GNUC__ */
232
233 #endif                          /* not __GNU_LIBRARY__ */
234 \f
235 /* Handle permutation of arguments.  */
236
237 /* Describe the part of ARGV that contains non-options that have
238    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
239    `last_nonopt' is the index after the last of them.  */
240
241 static int first_nonopt;
242 static int last_nonopt;
243
244 #ifdef _LIBC
245 /* Bash 2.0 gives us an environment variable containing flags
246    indicating ARGV elements that should not be considered arguments.  */
247
248 #ifdef USE_NONOPTION_FLAGS
249 /* Defined in getopt_init.c  */
250 extern char *__getopt_nonoption_flags;
251
252 static int nonoption_flags_max_len;
253 static int nonoption_flags_len;
254 #endif
255
256 static int original_argc;
257 static char *const *original_argv;
258
259 /* Make sure the environment variable bash 2.0 puts in the environment
260    is valid for the getopt call we must make sure that the ARGV passed
261    to getopt is that one passed to the process.  */
262 static void
263     __attribute__ ((unused)) store_args_and_env(int argc,
264                                                 char *const *argv)
265 {
266         /* XXX This is no good solution.  We should rather copy the args so
267            that we can compare them later.  But we must not use malloc(3).  */
268         original_argc = argc;
269         original_argv = argv;
270 }
271
272 # ifdef text_set_element
273 text_set_element(__libc_subinit, store_args_and_env);
274 # endif                         /* text_set_element */
275
276 # ifdef USE_NONOPTION_FLAGS
277 #  define SWAP_FLAGS(ch1, ch2) \
278   if (nonoption_flags_len > 0)                                                \
279     {                                                                         \
280       char __tmp = __getopt_nonoption_flags[ch1];                             \
281       __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2];          \
282       __getopt_nonoption_flags[ch2] = __tmp;                                  \
283     }
284 # else
285 #  define SWAP_FLAGS(ch1, ch2)
286 # endif
287 #else                           /* !_LIBC */
288 # define SWAP_FLAGS(ch1, ch2)
289 #endif                          /* _LIBC */
290
291 /* Exchange two adjacent subsequences of ARGV.
292    One subsequence is elements [first_nonopt,last_nonopt)
293    which contains all the non-options that have been skipped so far.
294    The other is elements [last_nonopt,optind), which contains all
295    the options processed since those non-options were skipped.
296
297    `first_nonopt' and `last_nonopt' are relocated so that they describe
298    the new indices of the non-options in ARGV after they are moved.  */
299
300 #if defined __STDC__ && __STDC__
301 static void exchange(char **);
302 #endif
303
304 static void exchange(argv)
305 char **argv;
306 {
307         int bottom = first_nonopt;
308         int middle = last_nonopt;
309         int top = optind;
310         char *tem;
311
312         /* Exchange the shorter segment with the far end of the longer segment.
313            That puts the shorter segment into the right place.
314            It leaves the longer segment in the right place overall,
315            but it consists of two parts that need to be swapped next.  */
316
317 #if defined _LIBC && defined USE_NONOPTION_FLAGS
318         /* First make sure the handling of the `__getopt_nonoption_flags'
319            string can work normally.  Our top argument must be in the range
320            of the string.  */
321         if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) {
322                 /* We must extend the array.  The user plays games with us and
323                    presents new arguments.  */
324                 char *new_str = malloc(top + 1);
325                 if (new_str == NULL)
326                         nonoption_flags_len = nonoption_flags_max_len = 0;
327                 else {
328                         memset(__mempcpy(new_str, __getopt_nonoption_flags,
329                                          nonoption_flags_max_len),
330                                '\0', top + 1 - nonoption_flags_max_len);
331                         nonoption_flags_max_len = top + 1;
332                         __getopt_nonoption_flags = new_str;
333                 }
334         }
335 #endif
336
337         while (top > middle && middle > bottom) {
338                 if (top - middle > middle - bottom) {
339                         /* Bottom segment is the short one.  */
340                         int len = middle - bottom;
341                         register int i;
342
343                         /* Swap it with the top part of the top segment.  */
344                         for (i = 0; i < len; i++) {
345                                 tem = argv[bottom + i];
346                                 argv[bottom + i] =
347                                     argv[top - (middle - bottom) + i];
348                                 argv[top - (middle - bottom) + i] = tem;
349                                 SWAP_FLAGS(bottom + i,
350                                            top - (middle - bottom) + i);
351                         }
352                         /* Exclude the moved bottom segment from further swapping.  */
353                         top -= len;
354                 } else {
355                         /* Top segment is the short one.  */
356                         int len = top - middle;
357                         register int i;
358
359                         /* Swap it with the bottom part of the bottom segment.  */
360                         for (i = 0; i < len; i++) {
361                                 tem = argv[bottom + i];
362                                 argv[bottom + i] = argv[middle + i];
363                                 argv[middle + i] = tem;
364                                 SWAP_FLAGS(bottom + i, middle + i);
365                         }
366                         /* Exclude the moved top segment from further swapping.  */
367                         bottom += len;
368                 }
369         }
370
371         /* Update records for the slots the non-options now occupy.  */
372
373         first_nonopt += (optind - last_nonopt);
374         last_nonopt = optind;
375 }
376
377 /* Initialize the internal data when the first call is made.  */
378
379 #if defined __STDC__ && __STDC__
380 static const char *_getopt_initialize(int, char *const *, const char *);
381 #endif
382 static const char *_getopt_initialize(argc, argv, optstring)
383 int argc;
384 char *const *argv;
385 const char *optstring;
386 {
387         /* Start processing options with ARGV-element 1 (since ARGV-element 0
388            is the program name); the sequence of previously skipped
389            non-option ARGV-elements is empty.  */
390
391         first_nonopt = last_nonopt = optind;
392
393         nextchar = NULL;
394
395         posixly_correct = getenv("POSIXLY_CORRECT");
396
397         /* Determine how to handle the ordering of options and nonoptions.  */
398
399         if (optstring[0] == '-') {
400                 ordering = RETURN_IN_ORDER;
401                 ++optstring;
402         } else if (optstring[0] == '+') {
403                 ordering = REQUIRE_ORDER;
404                 ++optstring;
405         } else if (posixly_correct != NULL)
406                 ordering = REQUIRE_ORDER;
407         else
408                 ordering = PERMUTE;
409
410 #if defined _LIBC && defined USE_NONOPTION_FLAGS
411         if (posixly_correct == NULL
412             && argc == original_argc && argv == original_argv) {
413                 if (nonoption_flags_max_len == 0) {
414                         if (__getopt_nonoption_flags == NULL
415                             || __getopt_nonoption_flags[0] == '\0')
416                                 nonoption_flags_max_len = -1;
417                         else {
418                                 const char *orig_str =
419                                     __getopt_nonoption_flags;
420                                 int len = nonoption_flags_max_len =
421                                     strlen(orig_str);
422                                 if (nonoption_flags_max_len < argc)
423                                         nonoption_flags_max_len = argc;
424                                 __getopt_nonoption_flags = (char *)
425                                     malloc(nonoption_flags_max_len);
426                                 if (__getopt_nonoption_flags == NULL)
427                                         nonoption_flags_max_len = -1;
428                                 else
429                                         memset(__mempcpy
430                                                (__getopt_nonoption_flags,
431                                                 orig_str, len), '\0',
432                                                nonoption_flags_max_len -
433                                                len);
434                         }
435                 }
436                 nonoption_flags_len = nonoption_flags_max_len;
437         } else
438                 nonoption_flags_len = 0;
439 #endif
440
441         return optstring;
442 }
443 \f
444 /* Scan elements of ARGV (whose length is ARGC) for option characters
445    given in OPTSTRING.
446
447    If an element of ARGV starts with '-', and is not exactly "-" or "--",
448    then it is an option element.  The characters of this element
449    (aside from the initial '-') are option characters.  If `getopt'
450    is called repeatedly, it returns successively each of the option characters
451    from each of the option elements.
452
453    If `getopt' finds another option character, it returns that character,
454    updating `optind' and `nextchar' so that the next call to `getopt' can
455    resume the scan with the following option character or ARGV-element.
456
457    If there are no more option characters, `getopt' returns -1.
458    Then `optind' is the index in ARGV of the first ARGV-element
459    that is not an option.  (The ARGV-elements have been permuted
460    so that those that are not options now come last.)
461
462    OPTSTRING is a string containing the legitimate option characters.
463    If an option character is seen that is not listed in OPTSTRING,
464    return '?' after printing an error message.  If you set `opterr' to
465    zero, the error message is suppressed but we still return '?'.
466
467    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
468    so the following text in the same ARGV-element, or the text of the following
469    ARGV-element, is returned in `optarg'.  Two colons mean an option that
470    wants an optional arg; if there is text in the current ARGV-element,
471    it is returned in `optarg', otherwise `optarg' is set to zero.
472
473    If OPTSTRING starts with `-' or `+', it requests different methods of
474    handling the non-option ARGV-elements.
475    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
476
477    Long-named options begin with `--' instead of `-'.
478    Their names may be abbreviated as long as the abbreviation is unique
479    or is an exact match for some defined option.  If they have an
480    argument, it follows the option name in the same ARGV-element, separated
481    from the option name by a `=', or else the in next ARGV-element.
482    When `getopt' finds a long-named option, it returns 0 if that option's
483    `flag' field is nonzero, the value of the option's `val' field
484    if the `flag' field is zero.
485
486    The elements of ARGV aren't really const, because we permute them.
487    But we pretend they're const in the prototype to be compatible
488    with other systems.
489
490    LONGOPTS is a vector of `struct option' terminated by an
491    element containing a name which is zero.
492
493    LONGIND returns the index in LONGOPT of the long-named option found.
494    It is only valid when a long-named option has been found by the most
495    recent call.
496
497    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
498    long-named options.  */
499
500 int _getopt_internal(argc, argv, optstring, longopts, longind, long_only)
501 int argc;
502 char *const *argv;
503 const char *optstring;
504 const struct option *longopts;
505 int *longind;
506 int long_only;
507 {
508         int print_errors = opterr;
509         if (optstring[0] == ':')
510                 print_errors = 0;
511
512         if (argc < 1)
513                 return -1;
514
515         optarg = NULL;
516
517         if (optind == 0 || !__getopt_initialized) {
518                 if (optind == 0)
519                         optind = 1;     /* Don't scan ARGV[0], the program name.  */
520                 optstring = _getopt_initialize(argc, argv, optstring);
521                 __getopt_initialized = 1;
522         }
523
524         /* Test whether ARGV[optind] points to a non-option argument.
525            Either it does not have option syntax, or there is an environment flag
526            from the shell indicating it is not an option.  The later information
527            is only used when the used in the GNU libc.  */
528 #if defined _LIBC && defined USE_NONOPTION_FLAGS
529 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0'       \
530                       || (optind < nonoption_flags_len                        \
531                           && __getopt_nonoption_flags[optind] == '1'))
532 #else
533 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
534 #endif
535
536         if (nextchar == NULL || *nextchar == '\0') {
537                 /* Advance to the next ARGV-element.  */
538
539                 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
540                    moved back by the user (who may also have changed the arguments).  */
541                 if (last_nonopt > optind)
542                         last_nonopt = optind;
543                 if (first_nonopt > optind)
544                         first_nonopt = optind;
545
546                 if (ordering == PERMUTE) {
547                         /* If we have just processed some options following some non-options,
548                            exchange them so that the options come first.  */
549
550                         if (first_nonopt != last_nonopt
551                             && last_nonopt != optind)
552                                 exchange((char **) argv);
553                         else if (last_nonopt != optind)
554                                 first_nonopt = optind;
555
556                         /* Skip any additional non-options
557                            and extend the range of non-options previously skipped.  */
558
559                         while (optind < argc && NONOPTION_P)
560                                 optind++;
561                         last_nonopt = optind;
562                 }
563
564                 /* The special ARGV-element `--' means premature end of options.
565                    Skip it like a null option,
566                    then exchange with previous non-options as if it were an option,
567                    then skip everything else like a non-option.  */
568
569                 if (optind != argc && !strcmp(argv[optind], "--")) {
570                         optind++;
571
572                         if (first_nonopt != last_nonopt
573                             && last_nonopt != optind)
574                                 exchange((char **) argv);
575                         else if (first_nonopt == last_nonopt)
576                                 first_nonopt = optind;
577                         last_nonopt = argc;
578
579                         optind = argc;
580                 }
581
582                 /* If we have done all the ARGV-elements, stop the scan
583                    and back over any non-options that we skipped and permuted.  */
584
585                 if (optind == argc) {
586                         /* Set the next-arg-index to point at the non-options
587                            that we previously skipped, so the caller will digest them.  */
588                         if (first_nonopt != last_nonopt)
589                                 optind = first_nonopt;
590                         return -1;
591                 }
592
593                 /* If we have come to a non-option and did not permute it,
594                    either stop the scan or describe it to the caller and pass it by.  */
595
596                 if (NONOPTION_P) {
597                         if (ordering == REQUIRE_ORDER)
598                                 return -1;
599                         optarg = argv[optind++];
600                         return 1;
601                 }
602
603                 /* We have found another option-ARGV-element.
604                    Skip the initial punctuation.  */
605
606                 nextchar = (argv[optind] + 1
607                             + (longopts != NULL
608                                && argv[optind][1] == '-'));
609         }
610
611         /* Decode the current option-ARGV-element.  */
612
613         /* Check whether the ARGV-element is a long option.
614
615            If long_only and the ARGV-element has the form "-f", where f is
616            a valid short option, don't consider it an abbreviated form of
617            a long option that starts with f.  Otherwise there would be no
618            way to give the -f short option.
619
620            On the other hand, if there's a long option "fubar" and
621            the ARGV-element is "-fu", do consider that an abbreviation of
622            the long option, just like "--fu", and not "-f" with arg "u".
623
624            This distinction seems to be the most useful approach.  */
625
626         if (longopts != NULL
627             && (argv[optind][1] == '-' || (long_only && (argv[optind][2]
628                                                          ||
629                                                          !my_index
630                                                          (optstring,
631                                                           argv[optind]
632                                                           [1]))))) {
633                 char *nameend;
634                 const struct option *p;
635                 const struct option *pfound = NULL;
636                 int exact = 0;
637                 int ambig = 0;
638                 int indfound = -1;
639                 int option_index;
640
641                 for (nameend = nextchar; *nameend && *nameend != '=';
642                      nameend++)
643                         /* Do nothing.  */ ;
644
645                 /* Test all long options for either exact match
646                    or abbreviated matches.  */
647                 for (p = longopts, option_index = 0; p->name;
648                      p++, option_index++)
649                         if (!strncmp
650                             (p->name, nextchar, nameend - nextchar)) {
651                                 if ((unsigned int) (nameend - nextchar)
652                                     == (unsigned int) strlen(p->name)) {
653                                         /* Exact match found.  */
654                                         pfound = p;
655                                         indfound = option_index;
656                                         exact = 1;
657                                         break;
658                                 } else if (pfound == NULL) {
659                                         /* First nonexact match found.  */
660                                         pfound = p;
661                                         indfound = option_index;
662                                 } else if (long_only
663                                            || pfound->has_arg != p->has_arg
664                                            || pfound->flag != p->flag
665                                            || pfound->val != p->val)
666                                         /* Second or later nonexact match found.  */
667                                         ambig = 1;
668                         }
669
670                 if (ambig && !exact) {
671                         if (print_errors)
672                                 fprintf(stderr,
673                                         _
674                                         ("%s: option `%s' is ambiguous\n"),
675                                         argv[0], argv[optind]);
676                         nextchar += strlen(nextchar);
677                         optind++;
678                         optopt = 0;
679                         return '?';
680                 }
681
682                 if (pfound != NULL) {
683                         option_index = indfound;
684                         optind++;
685                         if (*nameend) {
686                                 /* Don't test has_arg with >, because some C compilers don't
687                                    allow it to be used on enums.  */
688                                 if (pfound->has_arg)
689                                         optarg = nameend + 1;
690                                 else {
691                                         if (print_errors) {
692                                                 if (argv[optind - 1][1] ==
693                                                     '-')
694                                                         /* --option */
695                                                         fprintf(stderr,
696                                                                 _
697                                                                 ("%s: option `--%s' doesn't allow an argument\n"),
698                                                                 argv[0],
699                                                                 pfound->
700                                                                 name);
701                                                 else
702                                                         /* +option or -option */
703                                                         fprintf(stderr,
704                                                                 _
705                                                                 ("%s: option `%c%s' doesn't allow an argument\n"),
706                                                                 argv[0],
707                                                                 argv[optind
708                                                                      -
709                                                                      1][0],
710                                                                 pfound->
711                                                                 name);
712                                         }
713
714                                         nextchar += strlen(nextchar);
715
716                                         optopt = pfound->val;
717                                         return '?';
718                                 }
719                         } else if (pfound->has_arg == 1) {
720                                 if (optind < argc)
721                                         optarg = argv[optind++];
722                                 else {
723                                         if (print_errors)
724                                                 fprintf(stderr,
725                                                         _
726                                                         ("%s: option `%s' requires an argument\n"),
727                                                         argv[0],
728                                                         argv[optind - 1]);
729                                         nextchar += strlen(nextchar);
730                                         optopt = pfound->val;
731                                         return optstring[0] ==
732                                             ':' ? ':' : '?';
733                                 }
734                         }
735                         nextchar += strlen(nextchar);
736                         if (longind != NULL)
737                                 *longind = option_index;
738                         if (pfound->flag) {
739                                 *(pfound->flag) = pfound->val;
740                                 return 0;
741                         }
742                         return pfound->val;
743                 }
744
745                 /* Can't find it as a long option.  If this is not getopt_long_only,
746                    or the option starts with '--' or is not a valid short
747                    option, then it's an error.
748                    Otherwise interpret it as a short option.  */
749                 if (!long_only || argv[optind][1] == '-'
750                     || my_index(optstring, *nextchar) == NULL) {
751                         if (print_errors) {
752                                 if (argv[optind][1] == '-')
753                                         /* --option */
754                                         fprintf(stderr,
755                                                 _
756                                                 ("%s: unrecognized option `--%s'\n"),
757                                                 argv[0], nextchar);
758                                 else
759                                         /* +option or -option */
760                                         fprintf(stderr,
761                                                 _
762                                                 ("%s: unrecognized option `%c%s'\n"),
763                                                 argv[0], argv[optind][0],
764                                                 nextchar);
765                         }
766                         nextchar = (char *) "";
767                         optind++;
768                         optopt = 0;
769                         return '?';
770                 }
771         }
772
773         /* Look at and handle the next short option-character.  */
774
775         {
776                 char c = *nextchar++;
777                 char *temp = my_index(optstring, c);
778
779                 /* Increment `optind' when we start to process its last character.  */
780                 if (*nextchar == '\0')
781                         ++optind;
782
783                 if (temp == NULL || c == ':') {
784                         if (print_errors) {
785                                 if (posixly_correct)
786                                         /* 1003.2 specifies the format of this message.  */
787                                         fprintf(stderr,
788                                                 _
789                                                 ("%s: illegal option -- %c\n"),
790                                                 argv[0], c);
791                                 else
792                                         fprintf(stderr,
793                                                 _
794                                                 ("%s: invalid option -- %c\n"),
795                                                 argv[0], c);
796                         }
797                         optopt = c;
798                         return '?';
799                 }
800                 /* Convenience. Treat POSIX -W foo same as long option --foo */
801                 if (temp[0] == 'W' && temp[1] == ';') {
802                         char *nameend;
803                         const struct option *p;
804                         const struct option *pfound = NULL;
805                         int exact = 0;
806                         int ambig = 0;
807                         int indfound = 0;
808                         int option_index;
809
810                         /* This is an option that requires an argument.  */
811                         if (*nextchar != '\0') {
812                                 optarg = nextchar;
813                                 /* If we end this ARGV-element by taking the rest as an arg,
814                                    we must advance to the next element now.  */
815                                 optind++;
816                         } else if (optind == argc) {
817                                 if (print_errors) {
818                                         /* 1003.2 specifies the format of this message.  */
819                                         fprintf(stderr,
820                                                 _
821                                                 ("%s: option requires an argument -- %c\n"),
822                                                 argv[0], c);
823                                 }
824                                 optopt = c;
825                                 if (optstring[0] == ':')
826                                         c = ':';
827                                 else
828                                         c = '?';
829                                 return c;
830                         } else
831                                 /* We already incremented `optind' once;
832                                    increment it again when taking next ARGV-elt as argument.  */
833                                 optarg = argv[optind++];
834
835                         /* optarg is now the argument, see if it's in the
836                            table of longopts.  */
837
838                         for (nextchar = nameend = optarg;
839                              *nameend && *nameend != '='; nameend++)
840                                 /* Do nothing.  */ ;
841
842                         /* Test all long options for either exact match
843                            or abbreviated matches.  */
844                         for (p = longopts, option_index = 0; p->name;
845                              p++, option_index++)
846                                 if (!strncmp
847                                     (p->name, nextchar,
848                                      nameend - nextchar)) {
849                                         if ((unsigned int) (nameend -
850                                                             nextchar) ==
851                                             strlen(p->name)) {
852                                                 /* Exact match found.  */
853                                                 pfound = p;
854                                                 indfound = option_index;
855                                                 exact = 1;
856                                                 break;
857                                         } else if (pfound == NULL) {
858                                                 /* First nonexact match found.  */
859                                                 pfound = p;
860                                                 indfound = option_index;
861                                         } else
862                                                 /* Second or later nonexact match found.  */
863                                                 ambig = 1;
864                                 }
865                         if (ambig && !exact) {
866                                 if (print_errors)
867                                         fprintf(stderr,
868                                                 _
869                                                 ("%s: option `-W %s' is ambiguous\n"),
870                                                 argv[0], argv[optind]);
871                                 nextchar += strlen(nextchar);
872                                 optind++;
873                                 return '?';
874                         }
875                         if (pfound != NULL) {
876                                 option_index = indfound;
877                                 if (*nameend) {
878                                         /* Don't test has_arg with >, because some C compilers don't
879                                            allow it to be used on enums.  */
880                                         if (pfound->has_arg)
881                                                 optarg = nameend + 1;
882                                         else {
883                                                 if (print_errors)
884                                                         fprintf(stderr, _("\
885 %s: option `-W %s' doesn't allow an argument\n"), argv[0], pfound->
886                                                                 name);
887
888                                                 nextchar +=
889                                                     strlen(nextchar);
890                                                 return '?';
891                                         }
892                                 } else if (pfound->has_arg == 1) {
893                                         if (optind < argc)
894                                                 optarg = argv[optind++];
895                                         else {
896                                                 if (print_errors)
897                                                         fprintf(stderr,
898                                                                 _
899                                                                 ("%s: option `%s' requires an argument\n"),
900                                                                 argv[0],
901                                                                 argv[optind
902                                                                      - 1]);
903                                                 nextchar +=
904                                                     strlen(nextchar);
905                                                 return optstring[0] ==
906                                                     ':' ? ':' : '?';
907                                         }
908                                 }
909                                 nextchar += strlen(nextchar);
910                                 if (longind != NULL)
911                                         *longind = option_index;
912                                 if (pfound->flag) {
913                                         *(pfound->flag) = pfound->val;
914                                         return 0;
915                                 }
916                                 return pfound->val;
917                         }
918                         nextchar = NULL;
919                         return 'W';     /* Let the application handle it.   */
920                 }
921                 if (temp[1] == ':') {
922                         if (temp[2] == ':') {
923                                 /* This is an option that accepts an argument optionally.  */
924                                 if (*nextchar != '\0') {
925                                         optarg = nextchar;
926                                         optind++;
927                                 } else
928                                         optarg = NULL;
929                                 nextchar = NULL;
930                         } else {
931                                 /* This is an option that requires an argument.  */
932                                 if (*nextchar != '\0') {
933                                         optarg = nextchar;
934                                         /* If we end this ARGV-element by taking the rest as an arg,
935                                            we must advance to the next element now.  */
936                                         optind++;
937                                 } else if (optind == argc) {
938                                         if (print_errors) {
939                                                 /* 1003.2 specifies the format of this message.  */
940                                                 fprintf(stderr,
941                                                         _
942                                                         ("%s: option requires an argument -- %c\n"),
943                                                         argv[0], c);
944                                         }
945                                         optopt = c;
946                                         if (optstring[0] == ':')
947                                                 c = ':';
948                                         else
949                                                 c = '?';
950                                 } else
951                                         /* We already incremented `optind' once;
952                                            increment it again when taking next ARGV-elt as argument.  */
953                                         optarg = argv[optind++];
954                                 nextchar = NULL;
955                         }
956                 }
957                 return c;
958         }
959 }
960
961 int getopt(argc, argv, optstring)
962 int argc;
963 char *const *argv;
964 const char *optstring;
965 {
966         return _getopt_internal(argc, argv, optstring,
967                                 (const struct option *) 0, (int *) 0, 0);
968 }
969
970 #endif                          /* Not ELIDE_CODE.  */
971 \f
972 #ifdef TEST
973
974 /* Compile with -DTEST to make an executable for use in testing
975    the above definition of `getopt'.  */
976
977 int main(argc, argv)
978 int argc;
979 char **argv;
980 {
981         int c;
982         int digit_optind = 0;
983
984         while (1) {
985                 int this_option_optind = optind ? optind : 1;
986
987                 c = getopt(argc, argv, "abc:d:0123456789");
988                 if (c == -1)
989                         break;
990
991                 switch (c) {
992                 case '0':
993                 case '1':
994                 case '2':
995                 case '3':
996                 case '4':
997                 case '5':
998                 case '6':
999                 case '7':
1000                 case '8':
1001                 case '9':
1002                         if (digit_optind != 0
1003                             && digit_optind != this_option_optind)
1004                                 printf
1005                                     ("digits occur in two different argv-elements.\n");
1006                         digit_optind = this_option_optind;
1007                         printf("option %c\n", c);
1008                         break;
1009
1010                 case 'a':
1011                         printf("option a\n");
1012                         break;
1013
1014                 case 'b':
1015                         printf("option b\n");
1016                         break;
1017
1018                 case 'c':
1019                         printf("option c with value `%s'\n", optarg);
1020                         break;
1021
1022                 case '?':
1023                         break;
1024
1025                 default:
1026                         printf
1027                             ("?? getopt returned character code 0%o ??\n",
1028                              c);
1029                 }
1030         }
1031
1032         if (optind < argc) {
1033                 printf("non-option ARGV-elements: ");
1034                 while (optind < argc)
1035                         printf("%s ", argv[optind++]);
1036                 printf("\n");
1037         }
1038
1039         exit(0);
1040 }
1041
1042 #endif                          /* TEST */