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