]> git.sesse.net Git - vlc/blob - src/config/getopt.c
Remove Apple getopt_long bug-to-bug
[vlc] / src / config / getopt.c
1 /*****************************************************************************
2  * getopt_long()
3  *****************************************************************************
4  * Copyright (C) 1987-1997 Free Software Foundation, Inc.
5  * Copyright (C) 2005-2010 the VideoLAN team
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU Lesser General Public License as published by
9  * the Free Software Foundation; either version 2.1 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public License
18  * along with this program; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
20  *****************************************************************************/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25 #include <vlc_common.h>
26
27 #include <stdio.h>
28 #include <string.h>
29
30 /* This version of `getopt' appears to the caller like standard Unix `getopt'
31    but it behaves differently for the user, since it allows the user
32    to intersperse the options with the other arguments.
33
34    As `getopt' works, it permutes the elements of ARGV so that,
35    when it is done, all the options precede everything else.  Thus
36    all application programs are extended to handle flexible argument order.
37
38    Setting the environment variable POSIXLY_CORRECT disables permutation.
39    Then the behavior is completely standard.
40
41    GNU application programs can use a third alternative mode in which
42    they can distinguish the relative order of options and other arguments.  */
43
44 #include "vlc_getopt.h"
45
46 /* For communication from `getopt' to the caller.
47    When `getopt' finds an option that takes an argument,
48    the argument value is returned here.
49    Also, when `ordering' is RETURN_IN_ORDER,
50    each non-option ARGV-element is returned here.  */
51
52 char *optarg = NULL;
53
54 /* Index in ARGV of the next element to be scanned.
55    This is used for communication to and from the caller
56    and for communication between successive calls to `getopt'.
57
58    On entry to `getopt', zero means this is the first call; initialize.
59
60    When `getopt' returns -1, this is the index of the first of the
61    non-option elements that the caller should itself scan.
62
63    Otherwise, `optind' communicates from one call to the next
64    how much of ARGV has been scanned so far.  */
65
66 /* 1003.2 says this must be 1 before any call.  */
67 int optind = 1;
68
69 /* Formerly, initialization of getopt depended on optind==0, which
70    causes problems with re-calling getopt as programs generally don't
71    know that. */
72
73 int __getopt_initialized = 0;
74
75 /* The next char to be scanned in the option-element
76    in which the last option character we returned was found.
77    This allows us to pick up the scan where we left off.
78
79    If this is zero, or a null string, it means resume the scan
80    by advancing to the next ARGV-element.  */
81
82 static char *nextchar;
83
84 /* Set to an option character which was unrecognized.
85    This must be initialized on some systems to avoid linking in the
86    system's own getopt implementation.  */
87
88 int optopt = '?';
89
90 /* Describe how to deal with options that follow non-option ARGV-elements.
91
92    If the caller did not specify anything,
93    the default is REQUIRE_ORDER if the environment variable
94    POSIXLY_CORRECT is defined, PERMUTE otherwise.
95
96    REQUIRE_ORDER means don't recognize them as options;
97    stop option processing when the first non-option is seen.
98    This is what Unix does.
99    This mode of operation is selected by either setting the environment
100    variable POSIXLY_CORRECT, or using `+' as the first character
101    of the list of option characters.
102
103    PERMUTE is the default.  We permute the contents of ARGV as we scan,
104    so that eventually all the non-options are at the end.  This allows options
105    to be given in any order, even with programs that were not written to
106    expect this.
107
108    RETURN_IN_ORDER is an option available to programs that were written
109    to expect options and other ARGV-elements in any order and that care about
110    the ordering of the two.  We describe each non-option ARGV-element
111    as if it were the argument of an option with character code 1.
112    Using `-' as the first character of the list of option characters
113    selects this mode of operation.
114
115    The special argument `--' forces an end of option-scanning regardless
116    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
117    `--' can cause `getopt' to return -1 with `optind' != ARGC.  */
118
119 static enum
120 {
121     REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
122 }
123 ordering;
124
125 /* Value of POSIXLY_CORRECT environment variable.  */
126 static char *posixly_correct;
127
128 /* Handle permutation of arguments.  */
129
130 /* Describe the part of ARGV that contains non-options that have
131    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
132    `last_nonopt' is the index after the last of them.  */
133
134 static int first_nonopt;
135 static int last_nonopt;
136
137 /* Exchange two adjacent subsequences of ARGV.
138    One subsequence is elements [first_nonopt,last_nonopt)
139    which contains all the non-options that have been skipped so far.
140    The other is elements [last_nonopt,optind), which contains all
141    the options processed since those non-options were skipped.
142
143    `first_nonopt' and `last_nonopt' are relocated so that they describe
144    the new indices of the non-options in ARGV after they are moved.  */
145
146 static void exchange(char **);
147
148 static void
149      exchange(argv)
150      char **argv;
151 {
152     int bottom = first_nonopt;
153     int middle = last_nonopt;
154     int top = optind;
155     char *tem;
156
157     /* Exchange the shorter segment with the far end of the longer segment.
158        That puts the shorter segment into the right place.
159        It leaves the longer segment in the right place overall,
160        but it consists of two parts that need to be swapped next.  */
161
162     while (top > middle && middle > bottom)
163     {
164         if (top - middle > middle - bottom)
165         {
166             /* Bottom segment is the short one.  */
167             int len = middle - bottom;
168             register int i;
169
170             /* Swap it with the top part of the top segment.  */
171             for (i = 0; i < len; i++)
172             {
173                 tem = argv[bottom + i];
174                 argv[bottom + i] = argv[top - (middle - bottom) + i];
175                 argv[top - (middle - bottom) + i] = tem;
176             }
177             /* Exclude the moved bottom segment from further swapping.  */
178             top -= len;
179         }
180         else
181         {
182             /* Top segment is the short one.  */
183             int len = top - middle;
184             register int i;
185
186             /* Swap it with the bottom part of the bottom segment.  */
187             for (i = 0; i < len; i++)
188             {
189                 tem = argv[bottom + i];
190                 argv[bottom + i] = argv[middle + i];
191                 argv[middle + i] = tem;
192             }
193             /* Exclude the moved top segment from further swapping.  */
194             bottom += len;
195         }
196     }
197
198     /* Update records for the slots the non-options now occupy.  */
199
200     first_nonopt += (optind - last_nonopt);
201     last_nonopt = optind;
202 }
203
204 /* Initialize the internal data when the first call is made.  */
205
206 static const char *_getopt_initialize(int, char *const *, const char *);
207
208 static const char *
209      _getopt_initialize(argc, argv, optstring)
210      int argc;
211      char *const *argv;
212      const char *optstring;
213 {
214     (void)argc;
215     (void)argv;
216     /* Start processing options with ARGV-element 1 (since ARGV-element 0
217        is the program name); the sequence of previously skipped
218        non-option ARGV-elements is empty.  */
219
220     first_nonopt = last_nonopt = optind = 1;
221
222     nextchar = NULL;
223
224     posixly_correct = getenv("POSIXLY_CORRECT");
225
226     /* Determine how to handle the ordering of options and nonoptions.  */
227
228     if (optstring[0] == '-')
229     {
230         ordering = RETURN_IN_ORDER;
231         ++optstring;
232     }
233     else if (optstring[0] == '+')
234     {
235         ordering = REQUIRE_ORDER;
236         ++optstring;
237     }
238     else if (posixly_correct != NULL)
239         ordering = REQUIRE_ORDER;
240     else
241         ordering = PERMUTE;
242
243     return optstring;
244 }
245 \f
246 /* Scan elements of ARGV (whose length is ARGC) for option characters
247    given in OPTSTRING.
248
249    If an element of ARGV starts with '-', and is not exactly "-" or "--",
250    then it is an option element.  The characters of this element
251    (aside from the initial '-') are option characters.  If `getopt'
252    is called repeatedly, it returns successively each of the option characters
253    from each of the option elements.
254
255    If `getopt' finds another option character, it returns that character,
256    updating `optind' and `nextchar' so that the next call to `getopt' can
257    resume the scan with the following option character or ARGV-element.
258
259    If there are no more option characters, `getopt' returns -1.
260    Then `optind' is the index in ARGV of the first ARGV-element
261    that is not an option.  (The ARGV-elements have been permuted
262    so that those that are not options now come last.)
263
264    OPTSTRING is a string containing the legitimate option characters.
265    If an option character is seen that is not listed in OPTSTRING,
266    return '?'.
267
268    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
269    so the following text in the same ARGV-element, or the text of the following
270    ARGV-element, is returned in `optarg'.  Two colons mean an option that
271    wants an optional arg; if there is text in the current ARGV-element,
272    it is returned in `optarg', otherwise `optarg' is set to zero.
273
274    If OPTSTRING starts with `-' or `+', it requests different methods of
275    handling the non-option ARGV-elements.
276    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
277
278    Long-named options begin with `--' instead of `-'.
279    Their names may be abbreviated as long as the abbreviation is unique
280    or is an exact match for some defined option.  If they have an
281    argument, it follows the option name in the same ARGV-element, separated
282    from the option name by a `=', or else the in next ARGV-element.
283    When `getopt' finds a long-named option, it returns 0 if that option's
284    `flag' field is nonzero, the value of the option's `val' field
285    if the `flag' field is zero.
286
287    The elements of ARGV aren't really const, because we permute them.
288    But we pretend they're const in the prototype to be compatible
289    with other systems.
290
291    LONGOPTS is a vector of `struct option' terminated by an
292    element containing a name which is zero.
293
294    LONGIND returns the index in LONGOPT of the long-named option found.
295    It is only valid when a long-named option has been found by the most
296    recent call.  */
297
298 int
299     vlc_getopt_long(argc, argv, optstring, longopts, longind)
300      int argc;
301      char *const *argv;
302      const char *optstring;
303      const struct option *longopts;
304      int *longind;
305 {
306     optarg = NULL;
307
308     if (!__getopt_initialized || optind == 0)
309     {
310         optstring = _getopt_initialize(argc, argv, optstring);
311         optind = 1;    /* Don't scan ARGV[0], the program name.  */
312         __getopt_initialized = 1;
313     }
314
315 #define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
316
317     if (nextchar == NULL || *nextchar == '\0')
318     {
319         /* Advance to the next ARGV-element.  */
320
321         /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
322            moved back by the user (who may also have changed the arguments).  */
323         if (last_nonopt > optind)
324             last_nonopt = optind;
325         if (first_nonopt > optind)
326             first_nonopt = optind;
327
328         if (ordering == PERMUTE)
329         {
330             /* If we have just processed some options following some non-options,
331                exchange them so that the options come first.  */
332
333             if (first_nonopt != last_nonopt && last_nonopt != optind)
334                 exchange((char **) argv);
335             else if (last_nonopt != optind)
336                 first_nonopt = optind;
337
338             /* Skip any additional non-options
339                and extend the range of non-options previously skipped.  */
340
341             while (optind < argc && NONOPTION_P)
342                 optind++;
343             last_nonopt = optind;
344         }
345
346         /* The special ARGV-element `--' means premature end of options.
347            Skip it like a null option,
348            then exchange with previous non-options as if it were an option,
349            then skip everything else like a non-option.  */
350
351         if (optind != argc && !strcmp(argv[optind], "--"))
352         {
353             optind++;
354
355             if (first_nonopt != last_nonopt && last_nonopt != optind)
356                 exchange((char **) argv);
357             else if (first_nonopt == last_nonopt)
358                 first_nonopt = optind;
359             last_nonopt = argc;
360
361             optind = argc;
362         }
363
364         /* If we have done all the ARGV-elements, stop the scan
365            and back over any non-options that we skipped and permuted.  */
366
367         if (optind == argc)
368         {
369             /* Set the next-arg-index to point at the non-options
370                that we previously skipped, so the caller will digest them.  */
371             if (first_nonopt != last_nonopt)
372                 optind = first_nonopt;
373             return -1;
374         }
375
376         /* If we have come to a non-option and did not permute it,
377            either stop the scan or describe it to the caller and pass it by.  */
378
379         if (NONOPTION_P)
380         {
381             if (ordering == REQUIRE_ORDER)
382                 return -1;
383             optarg = argv[optind++];
384             return 1;
385         }
386
387         /* We have found another option-ARGV-element.
388            Skip the initial punctuation.  */
389
390         nextchar = (argv[optind] + 1
391                 + (argv[optind][1] == '-'));
392     }
393
394     /* Decode the current option-ARGV-element.  */
395
396     /* Check whether the ARGV-element is a long option.  */
397
398     if (argv[optind][1] == '-')
399     {
400         char *nameend;
401         const struct option *p;
402         const struct option *pfound = NULL;
403         int exact = 0;
404         int ambig = 0;
405         int indfound = -1;
406         int option_index;
407
408         for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
409             /* Do nothing.  */ ;
410
411         /* Test all long options for either exact match
412            or abbreviated matches.  */
413         for (p = longopts, option_index = 0; p->name; p++, option_index++)
414             if (!strncmp(p->name, nextchar, nameend - nextchar))
415             {
416                 if ((unsigned int) (nameend - nextchar)
417                     == (unsigned int) strlen(p->name))
418                 {
419                     /* Exact match found.  */
420                     pfound = p;
421                     indfound = option_index;
422                     exact = 1;
423                     break;
424                 }
425                 else if (pfound == NULL)
426                 {
427                     /* First nonexact match found.  */
428                     pfound = p;
429                     indfound = option_index;
430                 }
431                 else
432                     /* Second or later nonexact match found.  */
433                     ambig = 1;
434             }
435
436         if (ambig && !exact)
437         {
438             nextchar += strlen(nextchar);
439             optind++;
440             optopt = 0;
441             return '?';
442         }
443
444         if (pfound != NULL)
445         {
446             option_index = indfound;
447             optind++;
448             if (*nameend)
449             {
450                 /* Don't test has_arg with >, because some C compilers don't
451                    allow it to be used on enums.  */
452                 if (pfound->has_arg)
453                     optarg = nameend + 1;
454                 else
455                 {
456                     nextchar += strlen(nextchar);
457
458                     optopt = pfound->val;
459                     return '?';
460                 }
461             }
462             else if (pfound->has_arg == 1)
463             {
464                 if (optind < argc)
465                     optarg = argv[optind++];
466                 else
467                 {
468                     nextchar += strlen(nextchar);
469                     optopt = pfound->val;
470                     return optstring[0] == ':' ? ':' : '?';
471                 }
472             }
473             nextchar += strlen(nextchar);
474             if (longind != NULL)
475                 *longind = option_index;
476             if (pfound->flag)
477             {
478                 *(pfound->flag) = pfound->val;
479                 return 0;
480             }
481             return pfound->val;
482         }
483
484         nextchar = (char *) "";
485         optind++;
486         optopt = 0;
487         return '?';
488     }
489
490     /* Look at and handle the next short option-character.  */
491
492     {
493         char c = *nextchar++;
494         char *temp = strchr(optstring, c);
495
496         /* Increment `optind' when we start to process its last character.  */
497         if (*nextchar == '\0')
498             ++optind;
499
500         if (temp == NULL || c == ':')
501         {
502             optopt = c;
503             return '?';
504         }
505         /* Convenience. Treat POSIX -W foo same as long option --foo */
506         if (temp[0] == 'W' && temp[1] == ';')
507         {
508             char *nameend;
509             const struct option *p;
510             const struct option *pfound = NULL;
511             int exact = 0;
512             int ambig = 0;
513             int indfound = 0;
514             int option_index;
515
516             /* This is an option that requires an argument.  */
517             if (*nextchar != '\0')
518             {
519                 optarg = nextchar;
520                 /* If we end this ARGV-element by taking the rest as an arg,
521                    we must advance to the next element now.  */
522                 optind++;
523             }
524             else if (optind == argc)
525             {
526                 optopt = c;
527                 if (optstring[0] == ':')
528                     c = ':';
529                 else
530                     c = '?';
531                 return c;
532             }
533             else
534                 /* We already incremented `optind' once;
535                    increment it again when taking next ARGV-elt as argument.  */
536                 optarg = argv[optind++];
537
538             /* optarg is now the argument, see if it's in the
539                table of longopts.  */
540
541             for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
542                 /* Do nothing.  */ ;
543
544             /* Test all long options for either exact match
545                or abbreviated matches.  */
546             for (p = longopts, option_index = 0; p->name; p++, option_index++)
547                 if (!strncmp(p->name, nextchar, nameend - nextchar))
548                 {
549                     if ((unsigned int) (nameend - nextchar) == strlen(p->name))
550                     {
551                         /* Exact match found.  */
552                         pfound = p;
553                         indfound = option_index;
554                         exact = 1;
555                         break;
556                     }
557                     else if (pfound == NULL)
558                     {
559                         /* First nonexact match found.  */
560                         pfound = p;
561                         indfound = option_index;
562                     }
563                     else
564                         /* Second or later nonexact match found.  */
565                         ambig = 1;
566                 }
567             if (ambig && !exact)
568             {
569                 nextchar += strlen(nextchar);
570                 optind++;
571                 return '?';
572             }
573             if (pfound != NULL)
574             {
575                 option_index = indfound;
576                 if (*nameend)
577                 {
578                     /* Don't test has_arg with >, because some C compilers don't
579                        allow it to be used on enums.  */
580                     if (pfound->has_arg)
581                         optarg = nameend + 1;
582                     else
583                     {
584                         nextchar += strlen(nextchar);
585                         return '?';
586                     }
587                 }
588                 else if (pfound->has_arg == 1)
589                 {
590                     if (optind < argc)
591                         optarg = argv[optind++];
592                     else
593                     {
594                         nextchar += strlen(nextchar);
595                         return optstring[0] == ':' ? ':' : '?';
596                     }
597                 }
598                 nextchar += strlen(nextchar);
599                 if (longind != NULL)
600                     *longind = option_index;
601                 if (pfound->flag)
602                 {
603                     *(pfound->flag) = pfound->val;
604                     return 0;
605                 }
606                 return pfound->val;
607             }
608             nextchar = NULL;
609             return 'W';    /* Let the application handle it.   */
610         }
611         if (temp[1] == ':')
612         {
613             if (temp[2] == ':')
614             {
615                 /* This is an option that accepts an argument optionally.  */
616                 if (*nextchar != '\0')
617                 {
618                     optarg = nextchar;
619                     optind++;
620                 }
621                 else
622                     optarg = NULL;
623                 nextchar = NULL;
624             }
625             else
626             {
627                 /* This is an option that requires an argument.  */
628                 if (*nextchar != '\0')
629                 {
630                     optarg = nextchar;
631                     /* If we end this ARGV-element by taking the rest as an arg,
632                        we must advance to the next element now.  */
633                     optind++;
634                 }
635                 else if (optind == argc)
636                 {
637                     optopt = c;
638                     if (optstring[0] == ':')
639                         c = ':';
640                     else
641                         c = '?';
642                 }
643                 else
644                     /* We already incremented `optind' once;
645                        increment it again when taking next ARGV-elt as argument.  */
646                     optarg = argv[optind++];
647                 nextchar = NULL;
648             }
649         }
650         return c;
651     }
652 }