Subversion Repositories Kolibri OS

Rev

Rev 6132 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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