cfengine  3.15.4
About: CFEngine is a configuration management system for configuring and maintaining Unix-like computers (using an own high level policy language). Community version.
  Fossies Dox: cfengine-3.15.4.tar.gz  ("unofficial" and yet experimental doxygen-generated source code documentation)  

getopt.c
Go to the documentation of this file.
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 roland@gnu.ai.mit.edu
4  before changing it!
5 
6  Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94
7  Free Software Foundation, Inc.
8 
9 This file is part of the GNU C Library. Its master source is NOT part of
10 the C library, however. The master source lives in /gd/gnu/lib.
11 
12 The GNU C Library is free software; you can redistribute it and/or
13 modify it under the terms of the GNU Library General Public License as
14 published by the Free Software Foundation; either version 2 of the
15 License, or (at your option) any later version.
16 
17 The GNU C Library 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 GNU
20 Library General Public License for more details.
21 
22 You should have received a copy of the GNU Library General Public
23 License along with the GNU C Library; see the file COPYING.LIB. If
24 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
25 Cambridge, MA 02139, USA. */
26 ␌
27 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
28  Ditto for AIX 3.2 and <stdlib.h>. */
29 #ifndef _NO_PROTO
30 #define _NO_PROTO
31 #endif
32 
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 #if defined (_LIBC) || !defined (__GNU_LIBRARY__)
53 
54 
55 /* This needs to come after some library #include
56  to get __GNU_LIBRARY__ defined. */
57 #ifdef __GNU_LIBRARY__
58 /* Don't include stdlib.h for non-GNU C libraries because some of them
59  contain conflicting prototypes for getopt. */
60 #include <stdlib.h>
61 #endif /* GNU C library. */
62 
63 char *getenv(const char *name);
64 
65 /* This version of `getopt' appears to the caller like standard Unix `getopt'
66  but it behaves differently for the user, since it allows the user
67  to intersperse the options with the other arguments.
68 
69  As `getopt' works, it permutes the elements of ARGV so that,
70  when it is done, all the options precede everything else. Thus
71  all application programs are extended to handle flexible argument order.
72 
73  Setting the environment variable POSIXLY_CORRECT disables permutation.
74  Then the behavior is completely standard.
75 
76  GNU application programs can use a third alternative mode in which
77  they can distinguish the relative order of options and other arguments. */
78 
79 #include <getopt.h>
80 
81 /* For communication from `getopt' to the caller.
82  When `getopt' finds an option that takes an argument,
83  the argument value is returned here.
84  Also, when `ordering' is RETURN_IN_ORDER,
85  each non-option ARGV-element is returned here. */
86 
87 char *optarg = NULL;
88 
89 /* Index in ARGV of the next element to be scanned.
90  This is used for communication to and from the caller
91  and for communication between successive calls to `getopt'.
92 
93  On entry to `getopt', zero means this is the first call; initialize.
94 
95  When `getopt' returns EOF, this is the index of the first of the
96  non-option elements that the caller should itself scan.
97 
98  Otherwise, `optind' communicates from one call to the next
99  how much of ARGV has been scanned so far. */
100 
101 /* XXX 1003.2 says this must be 1 before any call. */
102 int optind = 0;
103 
104 /* The next char to be scanned in the option-element
105  in which the last option character we returned was found.
106  This allows us to pick up the scan where we left off.
107 
108  If this is zero, or a null string, it means resume the scan
109  by advancing to the next ARGV-element. */
110 
111 static char *nextchar;
112 
113 /* Callers store zero here to inhibit the error message
114  for unrecognized options. */
115 
116 int opterr = 1;
117 
118 /* Set to an option character which was unrecognized.
119  This must be initialized on some systems to avoid linking in the
120  system's own getopt implementation. */
121 
122 int optopt = '?';
123 
124 /* Describe how to deal with options that follow non-option ARGV-elements.
125 
126  If the caller did not specify anything,
127  the default is REQUIRE_ORDER if the environment variable
128  POSIXLY_CORRECT is defined, PERMUTE otherwise.
129 
130  REQUIRE_ORDER means don't recognize them as options;
131  stop option processing when the first non-option is seen.
132  This is what Unix does.
133  This mode of operation is selected by either setting the environment
134  variable POSIXLY_CORRECT, or using `+' as the first character
135  of the list of option characters.
136 
137  PERMUTE is the default. We permute the contents of ARGV as we scan,
138  so that eventually all the non-options are at the end. This allows options
139  to be given in any order, even with programs that were not written to
140  expect this.
141 
142  RETURN_IN_ORDER is an option available to programs that were written
143  to expect options and other ARGV-elements in any order and that care about
144  the ordering of the two. We describe each non-option ARGV-element
145  as if it were the argument of an option with character code 1.
146  Using `-' as the first character of the list of option characters
147  selects this mode of operation.
148 
149  The special argument `--' forces an end of option-scanning regardless
150  of the value of `ordering'. In the case of RETURN_IN_ORDER, only
151  `--' can cause `getopt' to return EOF with `optind' != ARGC. */
152 
153 static enum
154 {
157 
158 /* Value of POSIXLY_CORRECT environment variable. */
159 static char *posixly_correct;
160 ␌
161 #include <string.h>
162 #define my_index strchr
163 ␌
164 /* Handle permutation of arguments. */
165 
166 /* Describe the part of ARGV that contains non-options that have
167  been skipped. `first_nonopt' is the index in ARGV of the first of them;
168  `last_nonopt' is the index after the last of them. */
169 
170 static int first_nonopt;
171 static int last_nonopt;
172 
173 /* Exchange two adjacent subsequences of ARGV.
174  One subsequence is elements [first_nonopt,last_nonopt)
175  which contains all the non-options that have been skipped so far.
176  The other is elements [last_nonopt,optind), which contains all
177  the options processed since those non-options were skipped.
178 
179  `first_nonopt' and `last_nonopt' are relocated so that they describe
180  the new indices of the non-options in ARGV after they are moved. */
181 
182 static void
183 exchange (argv)
184  char **argv;
185 {
186  int bottom = first_nonopt;
187  int middle = last_nonopt;
188  int top = optind;
189  char *tem;
190 
191  /* Exchange the shorter segment with the far end of the longer segment.
192  That puts the shorter segment into the right place.
193  It leaves the longer segment in the right place overall,
194  but it consists of two parts that need to be swapped next. */
195 
196  while (top > middle && middle > bottom)
197  {
198  if (top - middle > middle - bottom)
199  {
200  /* Bottom segment is the short one. */
201  int len = middle - bottom;
202  register int i;
203 
204  /* Swap it with the top part of the top segment. */
205  for (i = 0; i < len; i++)
206  {
207  tem = argv[bottom + i];
208  argv[bottom + i] = argv[top - (middle - bottom) + i];
209  argv[top - (middle - bottom) + i] = tem;
210  }
211  /* Exclude the moved bottom segment from further swapping. */
212  top -= len;
213  }
214  else
215  {
216  /* Top segment is the short one. */
217  int len = top - middle;
218  register int i;
219 
220  /* Swap it with the bottom part of the bottom segment. */
221  for (i = 0; i < len; i++)
222  {
223  tem = argv[bottom + i];
224  argv[bottom + i] = argv[middle + i];
225  argv[middle + i] = tem;
226  }
227  /* Exclude the moved top segment from further swapping. */
228  bottom += len;
229  }
230  }
231 
232  /* Update records for the slots the non-options now occupy. */
233 
236 }
237 
238 /* Initialize the internal data when the first call is made. */
239 
240 static const char *
242  const char *optstring;
243 {
244  /* Start processing options with ARGV-element 1 (since ARGV-element 0
245  is the program name); the sequence of previously skipped
246  non-option ARGV-elements is empty. */
247 
249 
250  nextchar = NULL;
251 
252  posixly_correct = getenv ("POSIXLY_CORRECT");
253 
254  /* Determine how to handle the ordering of options and nonoptions. */
255 
256  if (optstring[0] == '-')
257  {
259  ++optstring;
260  }
261  else if (optstring[0] == '+')
262  {
264  ++optstring;
265  }
266  else if (posixly_correct != NULL)
268  else
269  ordering = PERMUTE;
270 
271  return optstring;
272 }
273 ␌
274 /* Scan elements of ARGV (whose length is ARGC) for option characters
275  given in OPTSTRING.
276 
277  If an element of ARGV starts with '-', and is not exactly "-" or "--",
278  then it is an option element. The characters of this element
279  (aside from the initial '-') are option characters. If `getopt'
280  is called repeatedly, it returns successively each of the option characters
281  from each of the option elements.
282 
283  If `getopt' finds another option character, it returns that character,
284  updating `optind' and `nextchar' so that the next call to `getopt' can
285  resume the scan with the following option character or ARGV-element.
286 
287  If there are no more option characters, `getopt' returns `EOF'.
288  Then `optind' is the index in ARGV of the first ARGV-element
289  that is not an option. (The ARGV-elements have been permuted
290  so that those that are not options now come last.)
291 
292  OPTSTRING is a string containing the legitimate option characters.
293  If an option character is seen that is not listed in OPTSTRING,
294  return '?' after printing an error message. If you set `opterr' to
295  zero, the error message is suppressed but we still return '?'.
296 
297  If a char in OPTSTRING is followed by a colon, that means it wants an arg,
298  so the following text in the same ARGV-element, or the text of the following
299  ARGV-element, is returned in `optarg'. Two colons mean an option that
300  wants an optional arg; if there is text in the current ARGV-element,
301  it is returned in `optarg', otherwise `optarg' is set to zero.
302 
303  If OPTSTRING starts with `-' or `+', it requests different methods of
304  handling the non-option ARGV-elements.
305  See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
306 
307  Long-named options begin with `--' instead of `-'.
308  Their names may be abbreviated as long as the abbreviation is unique
309  or is an exact match for some defined option. If they have an
310  argument, it follows the option name in the same ARGV-element, separated
311  from the option name by a `=', or else the in next ARGV-element.
312  When `getopt' finds a long-named option, it returns 0 if that option's
313  `flag' field is nonzero, the value of the option's `val' field
314  if the `flag' field is zero.
315 
316  The elements of ARGV aren't really const, because we permute them.
317  But we pretend they're const in the prototype to be compatible
318  with other systems.
319 
320  LONGOPTS is a vector of `struct option' terminated by an
321  element containing a name which is zero.
322 
323  LONGIND returns the index in LONGOPT of the long-named option found.
324  It is only valid when a long-named option has been found by the most
325  recent call.
326 
327  If LONG_ONLY is nonzero, '-' as well as '--' can introduce
328  long-named options. */
329 
330 int
331 _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
332  int argc;
333  char *const *argv;
334  const char *optstring;
335  const struct option *longopts;
336  int *longind;
337  int long_only;
338 {
339  optarg = NULL;
340 
341  if (optind == 0)
342  optstring = _getopt_initialize (optstring);
343 
344  if (nextchar == NULL || *nextchar == '\0')
345  {
346  /* Advance to the next ARGV-element. */
347 
348  if (ordering == PERMUTE)
349  {
350  /* If we have just processed some options following some non-options,
351  exchange them so that the options come first. */
352 
354  exchange ((char **) argv);
355  else if (last_nonopt != optind)
357 
358  /* Skip any additional non-options
359  and extend the range of non-options previously skipped. */
360 
361  while (optind < argc
362  && (argv[optind][0] != '-' || argv[optind][1] == '\0'))
363  optind++;
365  }
366 
367  /* The special ARGV-element `--' means premature end of options.
368  Skip it like a null option,
369  then exchange with previous non-options as if it were an option,
370  then skip everything else like a non-option. */
371 
372  if (optind != argc && !strcmp (argv[optind], "--"))
373  {
374  optind++;
375 
377  exchange ((char **) argv);
378  else if (first_nonopt == last_nonopt)
380  last_nonopt = argc;
381 
382  optind = argc;
383  }
384 
385  /* If we have done all the ARGV-elements, stop the scan
386  and back over any non-options that we skipped and permuted. */
387 
388  if (optind == argc)
389  {
390  /* Set the next-arg-index to point at the non-options
391  that we previously skipped, so the caller will digest them. */
392  if (first_nonopt != last_nonopt)
394  return EOF;
395  }
396 
397  /* If we have come to a non-option and did not permute it,
398  either stop the scan or describe it to the caller and pass it by. */
399 
400  if ((argv[optind][0] != '-' || argv[optind][1] == '\0'))
401  {
402  if (ordering == REQUIRE_ORDER)
403  return EOF;
404  optarg = argv[optind++];
405  return 1;
406  }
407 
408  /* We have found another option-ARGV-element.
409  Skip the initial punctuation. */
410 
411  nextchar = (argv[optind] + 1
412  + (longopts != NULL && argv[optind][1] == '-'));
413  }
414 
415  /* Decode the current option-ARGV-element. */
416 
417  /* Check whether the ARGV-element is a long option.
418 
419  If long_only and the ARGV-element has the form "-f", where f is
420  a valid short option, don't consider it an abbreviated form of
421  a long option that starts with f. Otherwise there would be no
422  way to give the -f short option.
423 
424  On the other hand, if there's a long option "fubar" and
425  the ARGV-element is "-fu", do consider that an abbreviation of
426  the long option, just like "--fu", and not "-f" with arg "u".
427 
428  This distinction seems to be the most useful approach. */
429 
430  if (longopts != NULL
431  && (argv[optind][1] == '-'
432  || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
433  {
434  char *nameend;
435  const struct option *p;
436  const struct option *pfound = NULL;
437  int exact = 0;
438  int ambig = 0;
439  int indfound = 0;
440  int option_index;
441 
442  for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
443  /* Do nothing. */ ;
444 
445  /* Test all long options for either exact match
446  or abbreviated matches. */
447  for (p = longopts, option_index = 0; p->name; p++, option_index++)
448  if (!strncmp (p->name, nextchar, nameend - nextchar))
449  {
450  if (nameend - nextchar == strlen (p->name))
451  {
452  /* Exact match found. */
453  pfound = p;
454  indfound = option_index;
455  exact = 1;
456  break;
457  }
458  else if (pfound == NULL)
459  {
460  /* First nonexact match found. */
461  pfound = p;
462  indfound = option_index;
463  }
464  else
465  /* Second or later nonexact match found. */
466  ambig = 1;
467  }
468 
469  if (ambig && !exact)
470  {
471  if (opterr)
472  fprintf (stderr, "%s: option `%s' is ambiguous\n",
473  argv[0], argv[optind]);
474  nextchar += strlen (nextchar);
475  optind++;
476  return '?';
477  }
478 
479  if (pfound != NULL)
480  {
481  option_index = indfound;
482  optind++;
483  if (*nameend)
484  {
485  /* Don't test has_arg with >, because some C compilers don't
486  allow it to be used on enums. */
487  if (pfound->has_arg)
488  optarg = nameend + 1;
489  else
490  {
491  if (opterr)
492  {
493  if (argv[optind - 1][1] == '-')
494  /* --option */
495  fprintf (stderr,
496  "%s: option `--%s' doesn't allow an argument\n",
497  argv[0], pfound->name);
498  else
499  /* +option or -option */
500  fprintf (stderr,
501  "%s: option `%c%s' doesn't allow an argument\n",
502  argv[0], argv[optind - 1][0], pfound->name);
503  }
504  nextchar += strlen (nextchar);
505  return '?';
506  }
507  }
508  else if (pfound->has_arg == 1)
509  {
510  if (optind < argc)
511  optarg = argv[optind++];
512  else
513  {
514  if (opterr)
515  fprintf (stderr, "%s: option `%s' requires an argument\n",
516  argv[0], argv[optind - 1]);
517  nextchar += strlen (nextchar);
518  return optstring[0] == ':' ? ':' : '?';
519  }
520  }
521  nextchar += strlen (nextchar);
522  if (longind != NULL)
523  *longind = option_index;
524  if (pfound->flag)
525  {
526  *(pfound->flag) = pfound->val;
527  return 0;
528  }
529  return pfound->val;
530  }
531 
532  /* Can't find it as a long option. If this is not getopt_long_only,
533  or the option starts with '--' or is not a valid short
534  option, then it's an error.
535  Otherwise interpret it as a short option. */
536  if (!long_only || argv[optind][1] == '-'
537  || my_index (optstring, *nextchar) == NULL)
538  {
539  if (opterr)
540  {
541  if (argv[optind][1] == '-')
542  /* --option */
543  fprintf (stderr, "%s: unrecognized option `--%s'\n",
544  argv[0], nextchar);
545  else
546  /* +option or -option */
547  fprintf (stderr, "%s: unrecognized option `%c%s'\n",
548  argv[0], argv[optind][0], nextchar);
549  }
550  nextchar = (char *) "";
551  optind++;
552  return '?';
553  }
554  }
555 
556  /* Look at and handle the next short option-character. */
557 
558  {
559  char c = *nextchar++;
560  char *temp = my_index (optstring, c);
561 
562  /* Increment `optind' when we start to process its last character. */
563  if (*nextchar == '\0')
564  ++optind;
565 
566  if (temp == NULL || c == ':')
567  {
568  if (opterr)
569  {
570  if (posixly_correct)
571  /* 1003.2 specifies the format of this message. */
572  fprintf (stderr, "%s: illegal option -- %c\n", argv[0], c);
573  else
574  fprintf (stderr, "%s: invalid option -- %c\n", argv[0], c);
575  }
576  optopt = c;
577  return '?';
578  }
579  if (temp[1] == ':')
580  {
581  if (temp[2] == ':')
582  {
583  /* This is an option that accepts an argument optionally. */
584  if (*nextchar != '\0')
585  {
586  optarg = nextchar;
587  optind++;
588  }
589  else
590  optarg = NULL;
591  nextchar = NULL;
592  }
593  else
594  {
595  /* This is an option that requires an argument. */
596  if (*nextchar != '\0')
597  {
598  optarg = nextchar;
599  /* If we end this ARGV-element by taking the rest as an arg,
600  we must advance to the next element now. */
601  optind++;
602  }
603  else if (optind == argc)
604  {
605  if (opterr)
606  {
607  /* 1003.2 specifies the format of this message. */
608  fprintf (stderr, "%s: option requires an argument -- %c\n",
609  argv[0], c);
610  }
611  optopt = c;
612  if (optstring[0] == ':')
613  c = ':';
614  else
615  c = '?';
616  }
617  else
618  /* We already incremented `optind' once;
619  increment it again when taking next ARGV-elt as argument. */
620  optarg = argv[optind++];
621  nextchar = NULL;
622  }
623  }
624  return c;
625  }
626 }
627 
628 int
629 getopt (argc, argv, optstring)
630  int argc;
631  char *const *argv;
632  const char *optstring;
633 {
634  return _getopt_internal (argc, argv, optstring,
635  (const struct option *) 0,
636  (int *) 0,
637  0);
638 }
639 
640 #endif /* _LIBC or not __GNU_LIBRARY__. */
641 ␌
642 #ifdef TEST
643 
644 /* Compile with -DTEST to make an executable for use in testing
645  the above definition of `getopt'. */
646 
647 int
648 main (argc, argv)
649  int argc;
650  char **argv;
651 {
652  int c;
653  int digit_optind = 0;
654 
655  while (1)
656  {
657  int this_option_optind = optind ? optind : 1;
658 
659  c = getopt (argc, argv, "abc:d:0123456789");
660  if (c == EOF)
661  break;
662 
663  switch (c)
664  {
665  case '0':
666  case '1':
667  case '2':
668  case '3':
669  case '4':
670  case '5':
671  case '6':
672  case '7':
673  case '8':
674  case '9':
675  if (digit_optind != 0 && digit_optind != this_option_optind)
676  printf ("digits occur in two different argv-elements.\n");
677  digit_optind = this_option_optind;
678  printf ("option %c\n", c);
679  break;
680 
681  case 'a':
682  printf ("option a\n");
683  break;
684 
685  case 'b':
686  printf ("option b\n");
687  break;
688 
689  case 'c':
690  printf ("option c with value `%s'\n", optarg);
691  break;
692 
693  case '?':
694  break;
695 
696  default:
697  printf ("?? getopt returned character code 0%o ??\n", c);
698  }
699  }
700 
701  if (optind < argc)
702  {
703  printf ("non-option ARGV-elements: ");
704  while (optind < argc)
705  printf ("%s ", argv[optind++]);
706  printf ("\n");
707  }
708 
709  exit(EXIT_SUCCESS);
710 }
711 
712 #endif /* TEST */
int main(int argc, char *argv[])
Definition: cf-agent.c:240
#define NULL
Definition: getopt1.c:56
int _getopt_internal(int argc, char **argv, char *optstring, struct option *longopts, int *longind, int long_only)
Definition: getopt.c:331
static enum @2 ordering
static char * _getopt_initialize(char *optstring)
Definition: getopt.c:241
char * getenv(char *name)
static void exchange(char **argv)
Definition: getopt.c:183
int optopt
Definition: getopt.c:122
static char * nextchar
Definition: getopt.c:111
static int last_nonopt
Definition: getopt.c:171
static int first_nonopt
Definition: getopt.c:170
#define my_index
Definition: getopt.c:162
@ REQUIRE_ORDER
Definition: getopt.c:155
@ RETURN_IN_ORDER
Definition: getopt.c:155
@ PERMUTE
Definition: getopt.c:155
int getopt(int argc, char **argv, char *optstring)
Definition: getopt.c:629
static char * posixly_correct
Definition: getopt.c:159
int optind
Definition: getopt.c:102
char * optarg
Definition: getopt.c:87
int opterr
Definition: getopt.c:116
Definition: getopt.h:83
int val
Definition: getopt.h:93
int has_arg
Definition: getopt.h:91
char * name
Definition: getopt.h:87
int * flag
Definition: getopt.h:92