Imported Upstream version 2.17
[debian/cpmtools] / 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,2002,2003,2004,2006
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 along
20    with this program; if not, write to the Free Software Foundation,
21    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
22 \f
23 #ifndef _LIBC
24 # include "config.h"
25 #endif
26
27 #include "getopt_.h"
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33
34 #ifdef __VMS
35 # include <unixlib.h>
36 #endif
37
38 #ifdef _LIBC
39 # include <libintl.h>
40 #else
41 #if 0
42 # include <gettext.h>
43 # define _(msgid) gettext (msgid)
44 #else
45 # define _(msgid) (msgid)
46 #endif
47 #endif
48
49 #if defined _LIBC && defined USE_IN_LIBIO
50 # include <wchar.h>
51 #endif
52
53 #ifndef attribute_hidden
54 # define attribute_hidden
55 #endif
56
57 /* Unlike standard Unix `getopt', functions like `getopt_long'
58    let the user intersperse the options with the other arguments.
59
60    As `getopt_long' works, it permutes the elements of ARGV so that,
61    when it is done, all the options precede everything else.  Thus
62    all application programs are extended to handle flexible argument order.
63
64    Using `getopt' or setting the environment variable POSIXLY_CORRECT
65    disables permutation.
66    Then the application's behavior is completely standard.
67
68    GNU application programs can use a third alternative mode in which
69    they can distinguish the relative order of options and other arguments.  */
70
71 #include "getopt_int.h"
72
73 /* For communication from `getopt' to the caller.
74    When `getopt' finds an option that takes an argument,
75    the argument value is returned here.
76    Also, when `ordering' is RETURN_IN_ORDER,
77    each non-option ARGV-element is returned here.  */
78
79 char *optarg;
80
81 /* Index in ARGV of the next element to be scanned.
82    This is used for communication to and from the caller
83    and for communication between successive calls to `getopt'.
84
85    On entry to `getopt', zero means this is the first call; initialize.
86
87    When `getopt' returns -1, this is the index of the first of the
88    non-option elements that the caller should itself scan.
89
90    Otherwise, `optind' communicates from one call to the next
91    how much of ARGV has been scanned so far.  */
92
93 /* 1003.2 says this must be 1 before any call.  */
94 int optind = 1;
95
96 /* Callers store zero here to inhibit the error message
97    for unrecognized options.  */
98
99 int opterr = 1;
100
101 /* Set to an option character which was unrecognized.
102    This must be initialized on some systems to avoid linking in the
103    system's own getopt implementation.  */
104
105 int optopt = '?';
106
107 /* Keep a global copy of all internal members of getopt_data.  */
108
109 static struct _getopt_data getopt_data;
110
111 \f
112 #if defined HAVE_DECL_GETENV && !HAVE_DECL_GETENV
113 extern char *getenv ();
114 #endif
115 \f
116 #ifdef _LIBC
117 /* Stored original parameters.
118    XXX This is no good solution.  We should rather copy the args so
119    that we can compare them later.  But we must not use malloc(3).  */
120 extern int __libc_argc;
121 extern char **__libc_argv;
122
123 /* Bash 2.0 gives us an environment variable containing flags
124    indicating ARGV elements that should not be considered arguments.  */
125
126 # ifdef USE_NONOPTION_FLAGS
127 /* Defined in getopt_init.c  */
128 extern char *__getopt_nonoption_flags;
129 # endif
130
131 # ifdef USE_NONOPTION_FLAGS
132 #  define SWAP_FLAGS(ch1, ch2) \
133   if (d->__nonoption_flags_len > 0)                                           \
134     {                                                                         \
135       char __tmp = __getopt_nonoption_flags[ch1];                             \
136       __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2];          \
137       __getopt_nonoption_flags[ch2] = __tmp;                                  \
138     }
139 # else
140 #  define SWAP_FLAGS(ch1, ch2)
141 # endif
142 #else   /* !_LIBC */
143 # define SWAP_FLAGS(ch1, ch2)
144 #endif  /* _LIBC */
145
146 /* Exchange two adjacent subsequences of ARGV.
147    One subsequence is elements [first_nonopt,last_nonopt)
148    which contains all the non-options that have been skipped so far.
149    The other is elements [last_nonopt,optind), which contains all
150    the options processed since those non-options were skipped.
151
152    `first_nonopt' and `last_nonopt' are relocated so that they describe
153    the new indices of the non-options in ARGV after they are moved.  */
154
155 static void
156 exchange (char **argv, struct _getopt_data *d)
157 {
158   int bottom = d->__first_nonopt;
159   int middle = d->__last_nonopt;
160   int top = d->optind;
161   char *tem;
162
163   /* Exchange the shorter segment with the far end of the longer segment.
164      That puts the shorter segment into the right place.
165      It leaves the longer segment in the right place overall,
166      but it consists of two parts that need to be swapped next.  */
167
168 #if defined _LIBC && defined USE_NONOPTION_FLAGS
169   /* First make sure the handling of the `__getopt_nonoption_flags'
170      string can work normally.  Our top argument must be in the range
171      of the string.  */
172   if (d->__nonoption_flags_len > 0 && top >= d->__nonoption_flags_max_len)
173     {
174       /* We must extend the array.  The user plays games with us and
175          presents new arguments.  */
176       char *new_str = malloc (top + 1);
177       if (new_str == NULL)
178         d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0;
179       else
180         {
181           memset (__mempcpy (new_str, __getopt_nonoption_flags,
182                              d->__nonoption_flags_max_len),
183                   '\0', top + 1 - d->__nonoption_flags_max_len);
184           d->__nonoption_flags_max_len = top + 1;
185           __getopt_nonoption_flags = new_str;
186         }
187     }
188 #endif
189
190   while (top > middle && middle > bottom)
191     {
192       if (top - middle > middle - bottom)
193         {
194           /* Bottom segment is the short one.  */
195           int len = middle - bottom;
196           register int i;
197
198           /* Swap it with the top part of the top segment.  */
199           for (i = 0; i < len; i++)
200             {
201               tem = argv[bottom + i];
202               argv[bottom + i] = argv[top - (middle - bottom) + i];
203               argv[top - (middle - bottom) + i] = tem;
204               SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
205             }
206           /* Exclude the moved bottom segment from further swapping.  */
207           top -= len;
208         }
209       else
210         {
211           /* Top segment is the short one.  */
212           int len = top - middle;
213           register int i;
214
215           /* Swap it with the bottom part of the bottom segment.  */
216           for (i = 0; i < len; i++)
217             {
218               tem = argv[bottom + i];
219               argv[bottom + i] = argv[middle + i];
220               argv[middle + i] = tem;
221               SWAP_FLAGS (bottom + i, middle + i);
222             }
223           /* Exclude the moved top segment from further swapping.  */
224           bottom += len;
225         }
226     }
227
228   /* Update records for the slots the non-options now occupy.  */
229
230   d->__first_nonopt += (d->optind - d->__last_nonopt);
231   d->__last_nonopt = d->optind;
232 }
233
234 /* Initialize the internal data when the first call is made.  */
235
236 static const char *
237 _getopt_initialize (int argc, char **argv, const char *optstring,
238                     int posixly_correct, struct _getopt_data *d)
239 {
240   /* Start processing options with ARGV-element 1 (since ARGV-element 0
241      is the program name); the sequence of previously skipped
242      non-option ARGV-elements is empty.  */
243
244   d->__first_nonopt = d->__last_nonopt = d->optind;
245
246   d->__nextchar = NULL;
247
248   d->__posixly_correct = posixly_correct || !!getenv ("POSIXLY_CORRECT");
249
250   /* Determine how to handle the ordering of options and nonoptions.  */
251
252   if (optstring[0] == '-')
253     {
254       d->__ordering = RETURN_IN_ORDER;
255       ++optstring;
256     }
257   else if (optstring[0] == '+')
258     {
259       d->__ordering = REQUIRE_ORDER;
260       ++optstring;
261     }
262   else if (d->__posixly_correct)
263     d->__ordering = REQUIRE_ORDER;
264   else
265     d->__ordering = PERMUTE;
266
267 #if defined _LIBC && defined USE_NONOPTION_FLAGS
268   if (!d->__posixly_correct
269       && argc == __libc_argc && argv == __libc_argv)
270     {
271       if (d->__nonoption_flags_max_len == 0)
272         {
273           if (__getopt_nonoption_flags == NULL
274               || __getopt_nonoption_flags[0] == '\0')
275             d->__nonoption_flags_max_len = -1;
276           else
277             {
278               const char *orig_str = __getopt_nonoption_flags;
279               int len = d->__nonoption_flags_max_len = strlen (orig_str);
280               if (d->__nonoption_flags_max_len < argc)
281                 d->__nonoption_flags_max_len = argc;
282               __getopt_nonoption_flags =
283                 (char *) malloc (d->__nonoption_flags_max_len);
284               if (__getopt_nonoption_flags == NULL)
285                 d->__nonoption_flags_max_len = -1;
286               else
287                 memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
288                         '\0', d->__nonoption_flags_max_len - len);
289             }
290         }
291       d->__nonoption_flags_len = d->__nonoption_flags_max_len;
292     }
293   else
294     d->__nonoption_flags_len = 0;
295 #endif
296
297   return optstring;
298 }
299 \f
300 /* Scan elements of ARGV (whose length is ARGC) for option characters
301    given in OPTSTRING.
302
303    If an element of ARGV starts with '-', and is not exactly "-" or "--",
304    then it is an option element.  The characters of this element
305    (aside from the initial '-') are option characters.  If `getopt'
306    is called repeatedly, it returns successively each of the option characters
307    from each of the option elements.
308
309    If `getopt' finds another option character, it returns that character,
310    updating `optind' and `nextchar' so that the next call to `getopt' can
311    resume the scan with the following option character or ARGV-element.
312
313    If there are no more option characters, `getopt' returns -1.
314    Then `optind' is the index in ARGV of the first ARGV-element
315    that is not an option.  (The ARGV-elements have been permuted
316    so that those that are not options now come last.)
317
318    OPTSTRING is a string containing the legitimate option characters.
319    If an option character is seen that is not listed in OPTSTRING,
320    return '?' after printing an error message.  If you set `opterr' to
321    zero, the error message is suppressed but we still return '?'.
322
323    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
324    so the following text in the same ARGV-element, or the text of the following
325    ARGV-element, is returned in `optarg'.  Two colons mean an option that
326    wants an optional arg; if there is text in the current ARGV-element,
327    it is returned in `optarg', otherwise `optarg' is set to zero.
328
329    If OPTSTRING starts with `-' or `+', it requests different methods of
330    handling the non-option ARGV-elements.
331    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
332
333    Long-named options begin with `--' instead of `-'.
334    Their names may be abbreviated as long as the abbreviation is unique
335    or is an exact match for some defined option.  If they have an
336    argument, it follows the option name in the same ARGV-element, separated
337    from the option name by a `=', or else the in next ARGV-element.
338    When `getopt' finds a long-named option, it returns 0 if that option's
339    `flag' field is nonzero, the value of the option's `val' field
340    if the `flag' field is zero.
341
342    LONGOPTS is a vector of `struct option' terminated by an
343    element containing a name which is zero.
344
345    LONGIND returns the index in LONGOPT of the long-named option found.
346    It is only valid when a long-named option has been found by the most
347    recent call.
348
349    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
350    long-named options.
351
352    If POSIXLY_CORRECT is nonzero, behave as if the POSIXLY_CORRECT
353    environment variable were set.  */
354
355 int
356 _getopt_internal_r (int argc, char **argv, const char *optstring,
357                     const struct option *longopts, int *longind,
358                     int long_only, int posixly_correct, struct _getopt_data *d)
359 {
360   int print_errors = d->opterr;
361   if (optstring[0] == ':')
362     print_errors = 0;
363
364   if (argc < 1)
365     return -1;
366
367   d->optarg = NULL;
368
369   if (d->optind == 0 || !d->__initialized)
370     {
371       if (d->optind == 0)
372         d->optind = 1;  /* Don't scan ARGV[0], the program name.  */
373       optstring = _getopt_initialize (argc, argv, optstring,
374                                       posixly_correct, d);
375       d->__initialized = 1;
376     }
377
378   /* Test whether ARGV[optind] points to a non-option argument.
379      Either it does not have option syntax, or there is an environment flag
380      from the shell indicating it is not an option.  The later information
381      is only used when the used in the GNU libc.  */
382 #if defined _LIBC && defined USE_NONOPTION_FLAGS
383 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \
384                       || (d->optind < d->__nonoption_flags_len                \
385                           && __getopt_nonoption_flags[d->optind] == '1'))
386 #else
387 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
388 #endif
389
390   if (d->__nextchar == NULL || *d->__nextchar == '\0')
391     {
392       /* Advance to the next ARGV-element.  */
393
394       /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
395          moved back by the user (who may also have changed the arguments).  */
396       if (d->__last_nonopt > d->optind)
397         d->__last_nonopt = d->optind;
398       if (d->__first_nonopt > d->optind)
399         d->__first_nonopt = d->optind;
400
401       if (d->__ordering == PERMUTE)
402         {
403           /* If we have just processed some options following some non-options,
404              exchange them so that the options come first.  */
405
406           if (d->__first_nonopt != d->__last_nonopt
407               && d->__last_nonopt != d->optind)
408             exchange ((char **) argv, d);
409           else if (d->__last_nonopt != d->optind)
410             d->__first_nonopt = d->optind;
411
412           /* Skip any additional non-options
413              and extend the range of non-options previously skipped.  */
414
415           while (d->optind < argc && NONOPTION_P)
416             d->optind++;
417           d->__last_nonopt = d->optind;
418         }
419
420       /* The special ARGV-element `--' means premature end of options.
421          Skip it like a null option,
422          then exchange with previous non-options as if it were an option,
423          then skip everything else like a non-option.  */
424
425       if (d->optind != argc && !strcmp (argv[d->optind], "--"))
426         {
427           d->optind++;
428
429           if (d->__first_nonopt != d->__last_nonopt
430               && d->__last_nonopt != d->optind)
431             exchange ((char **) argv, d);
432           else if (d->__first_nonopt == d->__last_nonopt)
433             d->__first_nonopt = d->optind;
434           d->__last_nonopt = argc;
435
436           d->optind = argc;
437         }
438
439       /* If we have done all the ARGV-elements, stop the scan
440          and back over any non-options that we skipped and permuted.  */
441
442       if (d->optind == argc)
443         {
444           /* Set the next-arg-index to point at the non-options
445              that we previously skipped, so the caller will digest them.  */
446           if (d->__first_nonopt != d->__last_nonopt)
447             d->optind = d->__first_nonopt;
448           return -1;
449         }
450
451       /* If we have come to a non-option and did not permute it,
452          either stop the scan or describe it to the caller and pass it by.  */
453
454       if (NONOPTION_P)
455         {
456           if (d->__ordering == REQUIRE_ORDER)
457             return -1;
458           d->optarg = argv[d->optind++];
459           return 1;
460         }
461
462       /* We have found another option-ARGV-element.
463          Skip the initial punctuation.  */
464
465       d->__nextchar = (argv[d->optind] + 1
466                   + (longopts != NULL && argv[d->optind][1] == '-'));
467     }
468
469   /* Decode the current option-ARGV-element.  */
470
471   /* Check whether the ARGV-element is a long option.
472
473      If long_only and the ARGV-element has the form "-f", where f is
474      a valid short option, don't consider it an abbreviated form of
475      a long option that starts with f.  Otherwise there would be no
476      way to give the -f short option.
477
478      On the other hand, if there's a long option "fubar" and
479      the ARGV-element is "-fu", do consider that an abbreviation of
480      the long option, just like "--fu", and not "-f" with arg "u".
481
482      This distinction seems to be the most useful approach.  */
483
484   if (longopts != NULL
485       && (argv[d->optind][1] == '-'
486           || (long_only && (argv[d->optind][2]
487                             || !strchr (optstring, argv[d->optind][1])))))
488     {
489       char *nameend;
490       const struct option *p;
491       const struct option *pfound = NULL;
492       int exact = 0;
493       int ambig = 0;
494       int indfound = -1;
495       int option_index;
496
497       for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
498         /* Do nothing.  */ ;
499
500       /* Test all long options for either exact match
501          or abbreviated matches.  */
502       for (p = longopts, option_index = 0; p->name; p++, option_index++)
503         if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
504           {
505             if ((unsigned int) (nameend - d->__nextchar)
506                 == (unsigned int) strlen (p->name))
507               {
508                 /* Exact match found.  */
509                 pfound = p;
510                 indfound = option_index;
511                 exact = 1;
512                 break;
513               }
514             else if (pfound == NULL)
515               {
516                 /* First nonexact match found.  */
517                 pfound = p;
518                 indfound = option_index;
519               }
520             else if (long_only
521                      || pfound->has_arg != p->has_arg
522                      || pfound->flag != p->flag
523                      || pfound->val != p->val)
524               /* Second or later nonexact match found.  */
525               ambig = 1;
526           }
527
528       if (ambig && !exact)
529         {
530           if (print_errors)
531             {
532 #if defined _LIBC && defined USE_IN_LIBIO
533               char *buf;
534
535               if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"),
536                               argv[0], argv[d->optind]) >= 0)
537                 {
538                   _IO_flockfile (stderr);
539
540                   int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
541                   ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
542
543                   __fxprintf (NULL, "%s", buf);
544
545                   ((_IO_FILE *) stderr)->_flags2 = old_flags2;
546                   _IO_funlockfile (stderr);
547
548                   free (buf);
549                 }
550 #else
551               fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
552                        argv[0], argv[d->optind]);
553 #endif
554             }
555           d->__nextchar += strlen (d->__nextchar);
556           d->optind++;
557           d->optopt = 0;
558           return '?';
559         }
560
561       if (pfound != NULL)
562         {
563           option_index = indfound;
564           d->optind++;
565           if (*nameend)
566             {
567               /* Don't test has_arg with >, because some C compilers don't
568                  allow it to be used on enums.  */
569               if (pfound->has_arg)
570                 d->optarg = nameend + 1;
571               else
572                 {
573                   if (print_errors)
574                     {
575 #if defined _LIBC && defined USE_IN_LIBIO
576                       char *buf;
577                       int n;
578 #endif
579
580                       if (argv[d->optind - 1][1] == '-')
581                         {
582                           /* --option */
583 #if defined _LIBC && defined USE_IN_LIBIO
584                           n = __asprintf (&buf, _("\
585 %s: option `--%s' doesn't allow an argument\n"),
586                                           argv[0], pfound->name);
587 #else
588                           fprintf (stderr, _("\
589 %s: option `--%s' doesn't allow an argument\n"),
590                                    argv[0], pfound->name);
591 #endif
592                         }
593                       else
594                         {
595                           /* +option or -option */
596 #if defined _LIBC && defined USE_IN_LIBIO
597                           n = __asprintf (&buf, _("\
598 %s: option `%c%s' doesn't allow an argument\n"),
599                                           argv[0], argv[d->optind - 1][0],
600                                           pfound->name);
601 #else
602                           fprintf (stderr, _("\
603 %s: option `%c%s' doesn't allow an argument\n"),
604                                    argv[0], argv[d->optind - 1][0],
605                                    pfound->name);
606 #endif
607                         }
608
609 #if defined _LIBC && defined USE_IN_LIBIO
610                       if (n >= 0)
611                         {
612                           _IO_flockfile (stderr);
613
614                           int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
615                           ((_IO_FILE *) stderr)->_flags2
616                             |= _IO_FLAGS2_NOTCANCEL;
617
618                           __fxprintf (NULL, "%s", buf);
619
620                           ((_IO_FILE *) stderr)->_flags2 = old_flags2;
621                           _IO_funlockfile (stderr);
622
623                           free (buf);
624                         }
625 #endif
626                     }
627
628                   d->__nextchar += strlen (d->__nextchar);
629
630                   d->optopt = pfound->val;
631                   return '?';
632                 }
633             }
634           else if (pfound->has_arg == 1)
635             {
636               if (d->optind < argc)
637                 d->optarg = argv[d->optind++];
638               else
639                 {
640                   if (print_errors)
641                     {
642 #if defined _LIBC && defined USE_IN_LIBIO
643                       char *buf;
644
645                       if (__asprintf (&buf, _("\
646 %s: option `%s' requires an argument\n"),
647                                       argv[0], argv[d->optind - 1]) >= 0)
648                         {
649                           _IO_flockfile (stderr);
650
651                           int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
652                           ((_IO_FILE *) stderr)->_flags2
653                             |= _IO_FLAGS2_NOTCANCEL;
654
655                           __fxprintf (NULL, "%s", buf);
656
657                           ((_IO_FILE *) stderr)->_flags2 = old_flags2;
658                           _IO_funlockfile (stderr);
659
660                           free (buf);
661                         }
662 #else
663                       fprintf (stderr,
664                                _("%s: option `%s' requires an argument\n"),
665                                argv[0], argv[d->optind - 1]);
666 #endif
667                     }
668                   d->__nextchar += strlen (d->__nextchar);
669                   d->optopt = pfound->val;
670                   return optstring[0] == ':' ? ':' : '?';
671                 }
672             }
673           d->__nextchar += strlen (d->__nextchar);
674           if (longind != NULL)
675             *longind = option_index;
676           if (pfound->flag)
677             {
678               *(pfound->flag) = pfound->val;
679               return 0;
680             }
681           return pfound->val;
682         }
683
684       /* Can't find it as a long option.  If this is not getopt_long_only,
685          or the option starts with '--' or is not a valid short
686          option, then it's an error.
687          Otherwise interpret it as a short option.  */
688       if (!long_only || argv[d->optind][1] == '-'
689           || strchr (optstring, *d->__nextchar) == NULL)
690         {
691           if (print_errors)
692             {
693 #if defined _LIBC && defined USE_IN_LIBIO
694               char *buf;
695               int n;
696 #endif
697
698               if (argv[d->optind][1] == '-')
699                 {
700                   /* --option */
701 #if defined _LIBC && defined USE_IN_LIBIO
702                   n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"),
703                                   argv[0], d->__nextchar);
704 #else
705                   fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
706                            argv[0], d->__nextchar);
707 #endif
708                 }
709               else
710                 {
711                   /* +option or -option */
712 #if defined _LIBC && defined USE_IN_LIBIO
713                   n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"),
714                                   argv[0], argv[d->optind][0], d->__nextchar);
715 #else
716                   fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
717                            argv[0], argv[d->optind][0], d->__nextchar);
718 #endif
719                 }
720
721 #if defined _LIBC && defined USE_IN_LIBIO
722               if (n >= 0)
723                 {
724                   _IO_flockfile (stderr);
725
726                   int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
727                   ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
728
729                   __fxprintf (NULL, "%s", buf);
730
731                   ((_IO_FILE *) stderr)->_flags2 = old_flags2;
732                   _IO_funlockfile (stderr);
733
734                   free (buf);
735                 }
736 #endif
737             }
738           d->__nextchar = (char *) "";
739           d->optind++;
740           d->optopt = 0;
741           return '?';
742         }
743     }
744
745   /* Look at and handle the next short option-character.  */
746
747   {
748     char c = *d->__nextchar++;
749     char *temp = strchr (optstring, c);
750
751     /* Increment `optind' when we start to process its last character.  */
752     if (*d->__nextchar == '\0')
753       ++d->optind;
754
755     if (temp == NULL || c == ':')
756       {
757         if (print_errors)
758           {
759 #if defined _LIBC && defined USE_IN_LIBIO
760               char *buf;
761               int n;
762 #endif
763
764             if (d->__posixly_correct)
765               {
766                 /* 1003.2 specifies the format of this message.  */
767 #if defined _LIBC && defined USE_IN_LIBIO
768                 n = __asprintf (&buf, _("%s: illegal option -- %c\n"),
769                                 argv[0], c);
770 #else
771                 fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
772 #endif
773               }
774             else
775               {
776 #if defined _LIBC && defined USE_IN_LIBIO
777                 n = __asprintf (&buf, _("%s: invalid option -- %c\n"),
778                                 argv[0], c);
779 #else
780                 fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c);
781 #endif
782               }
783
784 #if defined _LIBC && defined USE_IN_LIBIO
785             if (n >= 0)
786               {
787                 _IO_flockfile (stderr);
788
789                 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
790                 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
791
792                 __fxprintf (NULL, "%s", buf);
793
794                 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
795                 _IO_funlockfile (stderr);
796
797                 free (buf);
798               }
799 #endif
800           }
801         d->optopt = c;
802         return '?';
803       }
804     /* Convenience. Treat POSIX -W foo same as long option --foo */
805     if (temp[0] == 'W' && temp[1] == ';')
806       {
807         char *nameend;
808         const struct option *p;
809         const struct option *pfound = NULL;
810         int exact = 0;
811         int ambig = 0;
812         int indfound = 0;
813         int option_index;
814
815         /* This is an option that requires an argument.  */
816         if (*d->__nextchar != '\0')
817           {
818             d->optarg = d->__nextchar;
819             /* If we end this ARGV-element by taking the rest as an arg,
820                we must advance to the next element now.  */
821             d->optind++;
822           }
823         else if (d->optind == argc)
824           {
825             if (print_errors)
826               {
827                 /* 1003.2 specifies the format of this message.  */
828 #if defined _LIBC && defined USE_IN_LIBIO
829                 char *buf;
830
831                 if (__asprintf (&buf,
832                                 _("%s: option requires an argument -- %c\n"),
833                                 argv[0], c) >= 0)
834                   {
835                     _IO_flockfile (stderr);
836
837                     int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
838                     ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
839
840                     __fxprintf (NULL, "%s", buf);
841
842                     ((_IO_FILE *) stderr)->_flags2 = old_flags2;
843                     _IO_funlockfile (stderr);
844
845                     free (buf);
846                   }
847 #else
848                 fprintf (stderr, _("%s: option requires an argument -- %c\n"),
849                          argv[0], c);
850 #endif
851               }
852             d->optopt = c;
853             if (optstring[0] == ':')
854               c = ':';
855             else
856               c = '?';
857             return c;
858           }
859         else
860           /* We already incremented `d->optind' once;
861              increment it again when taking next ARGV-elt as argument.  */
862           d->optarg = argv[d->optind++];
863
864         /* optarg is now the argument, see if it's in the
865            table of longopts.  */
866
867         for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '=';
868              nameend++)
869           /* Do nothing.  */ ;
870
871         /* Test all long options for either exact match
872            or abbreviated matches.  */
873         for (p = longopts, option_index = 0; p->name; p++, option_index++)
874           if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
875             {
876               if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name))
877                 {
878                   /* Exact match found.  */
879                   pfound = p;
880                   indfound = option_index;
881                   exact = 1;
882                   break;
883                 }
884               else if (pfound == NULL)
885                 {
886                   /* First nonexact match found.  */
887                   pfound = p;
888                   indfound = option_index;
889                 }
890               else
891                 /* Second or later nonexact match found.  */
892                 ambig = 1;
893             }
894         if (ambig && !exact)
895           {
896             if (print_errors)
897               {
898 #if defined _LIBC && defined USE_IN_LIBIO
899                 char *buf;
900
901                 if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"),
902                                 argv[0], argv[d->optind]) >= 0)
903                   {
904                     _IO_flockfile (stderr);
905
906                     int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
907                     ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
908
909                     __fxprintf (NULL, "%s", buf);
910
911                     ((_IO_FILE *) stderr)->_flags2 = old_flags2;
912                     _IO_funlockfile (stderr);
913
914                     free (buf);
915                   }
916 #else
917                 fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
918                          argv[0], argv[d->optind]);
919 #endif
920               }
921             d->__nextchar += strlen (d->__nextchar);
922             d->optind++;
923             return '?';
924           }
925         if (pfound != NULL)
926           {
927             option_index = indfound;
928             if (*nameend)
929               {
930                 /* Don't test has_arg with >, because some C compilers don't
931                    allow it to be used on enums.  */
932                 if (pfound->has_arg)
933                   d->optarg = nameend + 1;
934                 else
935                   {
936                     if (print_errors)
937                       {
938 #if defined _LIBC && defined USE_IN_LIBIO
939                         char *buf;
940
941                         if (__asprintf (&buf, _("\
942 %s: option `-W %s' doesn't allow an argument\n"),
943                                         argv[0], pfound->name) >= 0)
944                           {
945                             _IO_flockfile (stderr);
946
947                             int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
948                             ((_IO_FILE *) stderr)->_flags2
949                               |= _IO_FLAGS2_NOTCANCEL;
950
951                             __fxprintf (NULL, "%s", buf);
952
953                             ((_IO_FILE *) stderr)->_flags2 = old_flags2;
954                             _IO_funlockfile (stderr);
955
956                             free (buf);
957                           }
958 #else
959                         fprintf (stderr, _("\
960 %s: option `-W %s' doesn't allow an argument\n"),
961                                  argv[0], pfound->name);
962 #endif
963                       }
964
965                     d->__nextchar += strlen (d->__nextchar);
966                     return '?';
967                   }
968               }
969             else if (pfound->has_arg == 1)
970               {
971                 if (d->optind < argc)
972                   d->optarg = argv[d->optind++];
973                 else
974                   {
975                     if (print_errors)
976                       {
977 #if defined _LIBC && defined USE_IN_LIBIO
978                         char *buf;
979
980                         if (__asprintf (&buf, _("\
981 %s: option `%s' requires an argument\n"),
982                                         argv[0], argv[d->optind - 1]) >= 0)
983                           {
984                             _IO_flockfile (stderr);
985
986                             int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
987                             ((_IO_FILE *) stderr)->_flags2
988                               |= _IO_FLAGS2_NOTCANCEL;
989
990                             __fxprintf (NULL, "%s", buf);
991
992                             ((_IO_FILE *) stderr)->_flags2 = old_flags2;
993                             _IO_funlockfile (stderr);
994
995                             free (buf);
996                           }
997 #else
998                         fprintf (stderr,
999                                  _("%s: option `%s' requires an argument\n"),
1000                                  argv[0], argv[d->optind - 1]);
1001 #endif
1002                       }
1003                     d->__nextchar += strlen (d->__nextchar);
1004                     return optstring[0] == ':' ? ':' : '?';
1005                   }
1006               }
1007             d->__nextchar += strlen (d->__nextchar);
1008             if (longind != NULL)
1009               *longind = option_index;
1010             if (pfound->flag)
1011               {
1012                 *(pfound->flag) = pfound->val;
1013                 return 0;
1014               }
1015             return pfound->val;
1016           }
1017           d->__nextchar = NULL;
1018           return 'W';   /* Let the application handle it.   */
1019       }
1020     if (temp[1] == ':')
1021       {
1022         if (temp[2] == ':')
1023           {
1024             /* This is an option that accepts an argument optionally.  */
1025             if (*d->__nextchar != '\0')
1026               {
1027                 d->optarg = d->__nextchar;
1028                 d->optind++;
1029               }
1030             else
1031               d->optarg = NULL;
1032             d->__nextchar = NULL;
1033           }
1034         else
1035           {
1036             /* This is an option that requires an argument.  */
1037             if (*d->__nextchar != '\0')
1038               {
1039                 d->optarg = d->__nextchar;
1040                 /* If we end this ARGV-element by taking the rest as an arg,
1041                    we must advance to the next element now.  */
1042                 d->optind++;
1043               }
1044             else if (d->optind == argc)
1045               {
1046                 if (print_errors)
1047                   {
1048                     /* 1003.2 specifies the format of this message.  */
1049 #if defined _LIBC && defined USE_IN_LIBIO
1050                     char *buf;
1051
1052                     if (__asprintf (&buf, _("\
1053 %s: option requires an argument -- %c\n"),
1054                                     argv[0], c) >= 0)
1055                       {
1056                         _IO_flockfile (stderr);
1057
1058                         int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1059                         ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
1060
1061                         __fxprintf (NULL, "%s", buf);
1062
1063                         ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1064                         _IO_funlockfile (stderr);
1065
1066                         free (buf);
1067                       }
1068 #else
1069                     fprintf (stderr,
1070                              _("%s: option requires an argument -- %c\n"),
1071                              argv[0], c);
1072 #endif
1073                   }
1074                 d->optopt = c;
1075                 if (optstring[0] == ':')
1076                   c = ':';
1077                 else
1078                   c = '?';
1079               }
1080             else
1081               /* We already incremented `optind' once;
1082                  increment it again when taking next ARGV-elt as argument.  */
1083               d->optarg = argv[d->optind++];
1084             d->__nextchar = NULL;
1085           }
1086       }
1087     return c;
1088   }
1089 }
1090
1091 int
1092 _getopt_internal (int argc, char **argv, const char *optstring,
1093                   const struct option *longopts, int *longind,
1094                   int long_only, int posixly_correct)
1095 {
1096   int result;
1097
1098   getopt_data.optind = optind;
1099   getopt_data.opterr = opterr;
1100
1101   result = _getopt_internal_r (argc, argv, optstring, longopts, longind,
1102                                long_only, posixly_correct, &getopt_data);
1103
1104   optind = getopt_data.optind;
1105   optarg = getopt_data.optarg;
1106   optopt = getopt_data.optopt;
1107
1108   return result;
1109 }
1110
1111 /* glibc gets a LSB-compliant getopt.
1112    Standalone applications get a POSIX-compliant getopt.  */
1113 #if _LIBC
1114 enum { POSIXLY_CORRECT = 0 };
1115 #else
1116 enum { POSIXLY_CORRECT = 1 };
1117 #endif
1118
1119 int
1120 getopt (int argc, char *const *argv, const char *optstring)
1121 {
1122   return _getopt_internal (argc, (char **) argv, optstring, NULL, NULL, 0,
1123                            POSIXLY_CORRECT);
1124 }
1125
1126 \f
1127 #ifdef TEST
1128
1129 /* Compile with -DTEST to make an executable for use in testing
1130    the above definition of `getopt'.  */
1131
1132 int
1133 main (int argc, char **argv)
1134 {
1135   int c;
1136   int digit_optind = 0;
1137
1138   while (1)
1139     {
1140       int this_option_optind = optind ? optind : 1;
1141
1142       c = getopt (argc, argv, "abc:d:0123456789");
1143       if (c == -1)
1144         break;
1145
1146       switch (c)
1147         {
1148         case '0':
1149         case '1':
1150         case '2':
1151         case '3':
1152         case '4':
1153         case '5':
1154         case '6':
1155         case '7':
1156         case '8':
1157         case '9':
1158           if (digit_optind != 0 && digit_optind != this_option_optind)
1159             printf ("digits occur in two different argv-elements.\n");
1160           digit_optind = this_option_optind;
1161           printf ("option %c\n", c);
1162           break;
1163
1164         case 'a':
1165           printf ("option a\n");
1166           break;
1167
1168         case 'b':
1169           printf ("option b\n");
1170           break;
1171
1172         case 'c':
1173           printf ("option c with value `%s'\n", optarg);
1174           break;
1175
1176         case '?':
1177           break;
1178
1179         default:
1180           printf ("?? getopt returned character code 0%o ??\n", c);
1181         }
1182     }
1183
1184   if (optind < argc)
1185     {
1186       printf ("non-option ARGV-elements: ");
1187       while (optind < argc)
1188         printf ("%s ", argv[optind++]);
1189       printf ("\n");
1190     }
1191
1192   exit (0);
1193 }
1194
1195 #endif /* TEST */