source: trunk/libs/newlib/src/newlib/libc/sys/linux/getopt.c @ 577

Last change on this file since 577 was 444, checked in by satin@…, 6 years ago

add newlib,libalmos-mkh, restructure shared_syscalls.h and mini-libc

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