"Fossies" - the Fresh Open Source Software Archive

Member "xtermcontrol-3.8/src/getopt.c" (9 Dec 2018, 40994 Bytes) of package /linux/privat/xtermcontrol-3.8.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "getopt.c" see the Fossies "Dox" file reference documentation and the last Fossies "Diffs" side-by-side code changes report: 3.4_vs_3.5.

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