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, 1992, 1999 Free Software Foundation, Inc.
7
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
21
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif /* Def: HAVE_CONFIG_H */
25
26 #include "xstd.h"
27 #include "strgicmp.h"
28 #include <stdio.h>
29 #include <stdlib.h>
30
31 /* If GETOPT_COMPAT is defined, `+' as well as `--' can introduce a
32 long-named option. Because this is not POSIX.2 compliant, it is
33 being phased out. */
34 #define GETOPT_COMPAT
35
36 /* This version of `getopt' appears to the caller like standard Unix `getopt'
37 but it behaves differently for the user, since it allows the user
38 to intersperse the options with the other arguments.
39
40 As `getopt' works, it permutes the elements of ARGV so that,
41 when it is done, all the options precede everything else. Thus
42 all application programs are extended to handle flexible argument order.
43
44 Setting the environment variable POSIXLY_CORRECT disables permutation.
45 Then the behavior is completely standard.
46
47 GNU application programs can use a third alternative mode in which
48 they can distinguish the relative order of options and other arguments. */
49
50 #include "getopt.h"
51
52 /* For communication from `getopt' to the caller.
53 When `getopt' finds an option that takes an argument,
54 the argument value is returned here.
55 Also, when `ordering' is RETURN_IN_ORDER,
56 each non-option ARGV-element is returned here. */
57
58 char *optarg = 0;
59
60 /* Index in ARGV of the next element to be scanned.
61 This is used for communication to and from the caller
62 and for communication between successive calls to `getopt'.
63
64 On entry to `getopt', zero means this is the first call; initialize.
65
66 When `getopt' returns EOF, this is the index of the first of the
67 non-option elements that the caller should itself scan.
68
69 Otherwise, `optind' communicates from one call to the next
70 how much of ARGV has been scanned so far. */
71
72 int optind = 0;
73
74 /* The next char to be scanned in the option-element
75 in which the last option character we returned was found.
76 This allows us to pick up the scan where we left off.
77
78 If this is zero, or a null string, it means resume the scan
79 by advancing to the next ARGV-element. */
80
81 static char *nextchar;
82
83 /* Callers store zero here to inhibit the error message
84 for unrecognized options. */
85
86 int opterr = 1;
87
88 /* Describe how to deal with options that follow non-option ARGV-elements.
89
90 If the caller did not specify anything,
91 the default is REQUIRE_ORDER if the environment variable
92 POSIXLY_CORRECT is defined, PERMUTE otherwise.
93
94 REQUIRE_ORDER means don't recognize them as options;
95 stop option processing when the first non-option is seen.
96 This is what Unix does.
97 This mode of operation is selected by either setting the environment
98 variable POSIXLY_CORRECT, or using `+' as the first character
99 of the list of option characters.
100
101 PERMUTE is the default. We permute the contents of ARGV as we scan,
102 so that eventually all the non-options are at the end. This allows options
103 to be given in any order, even with programs that were not written to
104 expect this.
105
106 RETURN_IN_ORDER is an option available to programs that were written
107 to expect options and other ARGV-elements in any order and that care about
108 the ordering of the two. We describe each non-option ARGV-element
109 as if it were the argument of an option with character code 1.
110 Using `-' as the first character of the list of option characters
111 selects this mode of operation.
112
113 The special argument `--' forces an end of option-scanning regardless
114 of the value of `ordering'. In the case of RETURN_IN_ORDER, only
115 `--' can cause `getopt' to return EOF with `optind' != ARGC. */
116
117 static enum
118 {
119 REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
120 } ordering;
121
122 #include <string.h>
123
124 /* Handle permutation of arguments. */
125
126 /* Describe the part of ARGV that contains non-options that have
127 been skipped. `first_nonopt' is the index in ARGV of the first of them;
128 `last_nonopt' is the index after the last of them. */
129
130 static int first_nonopt;
131 static int last_nonopt;
132
133 /* Exchange two adjacent subsequences of ARGV.
134 One subsequence is elements [first_nonopt,last_nonopt)
135 which contains all the non-options that have been skipped so far.
136 The other is elements [last_nonopt,optind), which contains all
137 the options processed since those non-options were skipped.
138
139 `first_nonopt' and `last_nonopt' are relocated so that they describe
140 the new indices of the non-options in ARGV after they are moved. */
141
142 static void
exchange(char ** argv)143 exchange (char **argv)
144 {
145 int nonopts_size = (last_nonopt - first_nonopt) * sizeof (char *);
146 char **temp;
147
148 XMALLOC (temp, nonopts_size);
149
150 /* Interchange the two blocks of data in ARGV. */
151
152 memcpy ((char *) temp, (char *) &argv[first_nonopt], nonopts_size);
153 memcpy ((char *) &argv[first_nonopt], (char *) &argv[last_nonopt],
154 (optind - last_nonopt) * sizeof (char *));
155 memcpy ((char *) &argv[first_nonopt + optind - last_nonopt],
156 (char *) temp, nonopts_size);
157
158 /* Update records for the slots the non-options now occupy. */
159
160 first_nonopt += (optind - last_nonopt);
161 last_nonopt = optind;
162 free (temp);
163 }
164
165
166 /* Scan elements of ARGV (whose length is ARGC) for option characters
167 given in OPTSTRING.
168
169 If an element of ARGV starts with '-', and is not exactly "-" or "--",
170 then it is an option element. The characters of this element
171 (aside from the initial '-') are option characters. If `getopt'
172 is called repeatedly, it returns successively each of the option characters
173 from each of the option elements.
174
175 If `getopt' finds another option character, it returns that character,
176 updating `optind' and `nextchar' so that the next call to `getopt' can
177 resume the scan with the following option character or ARGV-element.
178
179 If there are no more option characters, `getopt' returns `EOF'.
180 Then `optind' is the index in ARGV of the first ARGV-element
181 that is not an option. (The ARGV-elements have been permuted
182 so that those that are not options now come last.)
183
184 OPTSTRING is a string containing the legitimate option characters.
185 If an option character is seen that is not listed in OPTSTRING,
186 return '?' after printing an error message. If you set `opterr' to
187 zero, the error message is suppressed but we still return '?'.
188
189 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
190 so the following text in the same ARGV-element, or the text of the following
191 ARGV-element, is returned in `optarg'. Two colons mean an option that
192 wants an optional arg; if there is text in the current ARGV-element,
193 it is returned in `optarg', otherwise `optarg' is set to zero.
194
195 If OPTSTRING starts with `-' or `+', it requests different methods of
196 handling the non-option ARGV-elements.
197 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
198
199 Long-named options begin with `--' instead of `-'.
200 Their names may be abbreviated as long as the abbreviation is unique
201 or is an exact match for some defined option. If they have an
202 argument, it follows the option name in the same ARGV-element, separated
203 from the option name by a `=', or else the in next ARGV-element.
204 When `getopt' finds a long-named option, it returns 0 if that option's
205 `flag' field is nonzero, the value of the option's `val' field
206 if the `flag' field is zero.
207
208 The elements of ARGV aren't really const, because we permute them.
209 But we pretend they're const in the prototype to be compatible
210 with other systems.
211
212 LONGOPTS is a vector of `struct option' terminated by an
213 element containing a name which is zero.
214
215 LONGIND returns the index in LONGOPT of the long-named option found.
216 It is only valid when a long-named option has been found by the most
217 recent call.
218
219 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
220 long-named options. */
221
222 int
_getopt_internal(int argc,char * const * argv,const char * optstring,const struct option * longopts,int * longind,int long_only)223 _getopt_internal (int argc, char *const *argv, const char *optstring,
224 const struct option *longopts, int *longind, int long_only)
225 {
226 int option_index;
227
228 optarg = 0;
229
230 /* Initialize the internal data when the first call is made.
231 Start processing options with ARGV-element 1 (since ARGV-element 0
232 is the program name); the sequence of previously skipped
233 non-option ARGV-elements is empty. */
234
235 if (optind == 0)
236 {
237 first_nonopt = last_nonopt = optind = 1;
238
239 nextchar = NULL;
240
241 /* Determine how to handle the ordering of options and nonoptions. */
242
243 if (optstring[0] == '-')
244 {
245 ordering = RETURN_IN_ORDER;
246 ++optstring;
247 }
248 else if (optstring[0] == '+')
249 {
250 ordering = REQUIRE_ORDER;
251 ++optstring;
252 }
253 else if (getenv ("POSIXLY_CORRECT") != NULL)
254 ordering = REQUIRE_ORDER;
255 else
256 ordering = PERMUTE;
257 }
258
259 if (nextchar == NULL || *nextchar == '\0')
260 {
261 if (ordering == PERMUTE)
262 {
263 /* If we have just processed some options following some non-options,
264 exchange them so that the options come first. */
265
266 if (first_nonopt != last_nonopt && last_nonopt != optind)
267 exchange ((char **) argv);
268 else if (last_nonopt != optind)
269 first_nonopt = optind;
270
271 /* Now skip any additional non-options
272 and extend the range of non-options previously skipped. */
273
274 while (optind < argc
275 && (argv[optind][0] != '-' || argv[optind][1] == '\0')
276 #ifdef GETOPT_COMPAT
277 && (longopts == NULL
278 || argv[optind][0] != '+' || argv[optind][1] == '\0')
279 #endif /* GETOPT_COMPAT */
280 )
281 optind++;
282 last_nonopt = optind;
283 }
284
285 /* Special ARGV-element `--' means premature end of options.
286 Skip it like a null option,
287 then exchange with previous non-options as if it were an option,
288 then skip everything else like a non-option. */
289
290 if (optind != argc && !strcmp (argv[optind], "--"))
291 {
292 optind++;
293
294 if (first_nonopt != last_nonopt && last_nonopt != optind)
295 exchange ((char **) argv);
296 else if (first_nonopt == last_nonopt)
297 first_nonopt = optind;
298 last_nonopt = argc;
299
300 optind = argc;
301 }
302
303 /* If we have done all the ARGV-elements, stop the scan
304 and back over any non-options that we skipped and permuted. */
305
306 if (optind == argc)
307 {
308 /* Set the next-arg-index to point at the non-options
309 that we previously skipped, so the caller will digest them. */
310 if (first_nonopt != last_nonopt)
311 optind = first_nonopt;
312 return EOF;
313 }
314
315 /* If we have come to a non-option and did not permute it,
316 either stop the scan or describe it to the caller and pass it by. */
317
318 if ((argv[optind][0] != '-' || argv[optind][1] == '\0')
319 #ifdef GETOPT_COMPAT
320 && (longopts == NULL
321 || argv[optind][0] != '+' || argv[optind][1] == '\0')
322 #endif /* GETOPT_COMPAT */
323 )
324 {
325 if (ordering == REQUIRE_ORDER)
326 return EOF;
327 optarg = argv[optind++];
328 return 1;
329 }
330
331 /* We have found another option-ARGV-element.
332 Start decoding its characters. */
333
334 nextchar = (argv[optind] + 1
335 + (longopts != NULL && argv[optind][1] == '-'));
336 }
337
338 if (longopts != NULL
339 && ((argv[optind][0] == '-'
340 && (argv[optind][1] == '-' || long_only))
341 #ifdef GETOPT_COMPAT
342 || argv[optind][0] == '+'
343 #endif /* GETOPT_COMPAT */
344 ))
345 {
346 const struct option *p;
347 char *s = nextchar;
348 int exact = 0;
349 int ambig = 0;
350 const struct option *pfound = NULL;
351 int indfound=0;
352
353 while (*s && *s != '=')
354 s++;
355
356 /* Test all options for either exact match or abbreviated matches. */
357 for (p = longopts, option_index = 0; p->name;
358 p++, option_index++)
359 if (strgnicmp (p->name, nextchar, s - nextchar))
360 {
361 if ((unsigned) (s - nextchar) == strlen (p->name))
362 {
363 /* Exact match found. */
364 pfound = p;
365 indfound = option_index;
366 exact = 1;
367 break;
368 }
369 else if (pfound == NULL)
370 {
371 /* First nonexact match found. */
372 pfound = p;
373 indfound = option_index;
374 }
375 else
376 /* Second nonexact match found. */
377 ambig = 1;
378 }
379
380 if (ambig && !exact)
381 {
382 if (opterr)
383 fprintf (stderr, "%s: option `%s' is ambiguous\n",
384 argv[0], argv[optind]);
385 nextchar += strlen (nextchar);
386 optind++;
387 return '?';
388 }
389
390 if (pfound != NULL)
391 {
392 option_index = indfound;
393 optind++;
394 if (*s)
395 {
396 /* Don't test has_arg with >, because some C compilers don't
397 allow it to be used on enums. */
398 if (pfound->has_arg)
399 optarg = s + 1;
400 else
401 {
402 if (opterr)
403 {
404 if (argv[optind - 1][1] == '-')
405 /* --option */
406 fprintf (stderr,
407 "%s: option `--%s' doesn't allow an argument\n",
408 argv[0], pfound->name);
409 else
410 /* +option or -option */
411 fprintf (stderr,
412 "%s: option `%c%s' doesn't allow an argument\n",
413 argv[0], argv[optind - 1][0], pfound->name);
414 }
415 nextchar += strlen (nextchar);
416 return '?';
417 }
418 }
419 else if (pfound->has_arg == 1)
420 {
421 if (optind < argc)
422 optarg = argv[optind++];
423 else
424 {
425 if (opterr)
426 fprintf (stderr, "%s: option `%s' requires an argument\n",
427 argv[0], argv[optind - 1]);
428 nextchar += strlen (nextchar);
429 return '?';
430 }
431 }
432 nextchar += strlen (nextchar);
433 if (longind != NULL)
434 *longind = option_index;
435 if (pfound->flag)
436 {
437 *(pfound->flag) = pfound->val;
438 return 0;
439 }
440 return pfound->val;
441 }
442 /* Can't find it as a long option. If this is not getopt_long_only,
443 or the option starts with '--' or is not a valid short
444 option, then it's an error.
445 Otherwise interpret it as a short option. */
446 if (!long_only || argv[optind][1] == '-'
447 #ifdef GETOPT_COMPAT
448 || argv[optind][0] == '+'
449 #endif /* GETOPT_COMPAT */
450 || strchr (optstring, *nextchar) == NULL)
451 {
452 if (opterr)
453 {
454 if (argv[optind][1] == '-')
455 /* --option */
456 fprintf (stderr, "%s: unrecognized option `--%s'\n",
457 argv[0], nextchar);
458 else
459 /* +option or -option */
460 fprintf (stderr, "%s: unrecognized option `%c%s'\n",
461 argv[0], argv[optind][0], nextchar);
462 }
463 nextchar = (char *) "";
464 optind++;
465 return '?';
466 }
467 }
468
469 /* Look at and handle the next option-character. */
470
471 {
472 char c = *nextchar++;
473 char *temp = strchr (optstring, c);
474
475 /* Increment `optind' when we start to process its last character. */
476 if (*nextchar == '\0')
477 ++optind;
478
479 if (temp == NULL || c == ':')
480 {
481 if (opterr)
482 {
483 if (c < 040 || c >= 0177)
484 fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
485 argv[0], c);
486 else
487 fprintf (stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
488 }
489 return '?';
490 }
491 if (temp[1] == ':')
492 {
493 if (temp[2] == ':')
494 {
495 /* This is an option that accepts an argument optionally. */
496 if (*nextchar != '\0')
497 {
498 optarg = nextchar;
499 optind++;
500 }
501 else
502 optarg = 0;
503 nextchar = NULL;
504 }
505 else
506 {
507 /* This is an option that requires an argument. */
508 if (*nextchar != '\0')
509 {
510 optarg = nextchar;
511 /* If we end this ARGV-element by taking the rest as an arg,
512 we must advance to the next element now. */
513 optind++;
514 }
515 else if (optind == argc)
516 {
517 if (opterr)
518 fprintf (stderr, "%s: option `-%c' requires an argument\n",
519 argv[0], c);
520 c = '?';
521 }
522 else
523 /* We already incremented `optind' once;
524 increment it again when taking next ARGV-elt as argument. */
525 optarg = argv[optind++];
526 nextchar = NULL;
527 }
528 }
529 return c;
530 }
531 }
532
533 int
getopt(int argc,char * const * argv,const char * optstring)534 getopt (int argc, char *const *argv, const char *optstring)
535 {
536 return _getopt_internal (argc, argv, optstring,
537 (const struct option *) 0,
538 (int *) 0,
539 0);
540 }
541
542