493df4d3b3233ef9a037b18287c0333428297273
[coreboot.git] / payloads / libpayload / libc / getopt_long.c
1 /*      $OpenBSD: getopt_long.c,v 1.23 2007/10/31 12:34:57 chl Exp $    */
2 /*      $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $      */
3
4 /*
5  * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
6  * Copyright (c) 2008 coresystems GmbH
7  *
8  * Permission to use, copy, modify, and distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  *
20  * Sponsored in part by the Defense Advanced Research Projects
21  * Agency (DARPA) and Air Force Research Laboratory, Air Force
22  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
23  */
24 /*-
25  * Copyright (c) 2000 The NetBSD Foundation, Inc.
26  * All rights reserved.
27  *
28  * This code is derived from software contributed to The NetBSD Foundation
29  * by Dieter Baron and Thomas Klausner.
30  *
31  * Redistribution and use in source and binary forms, with or without
32  * modification, are permitted provided that the following conditions
33  * are met:
34  * 1. Redistributions of source code must retain the above copyright
35  *    notice, this list of conditions and the following disclaimer.
36  * 2. Redistributions in binary form must reproduce the above copyright
37  *    notice, this list of conditions and the following disclaimer in the
38  *    documentation and/or other materials provided with the distribution.
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
41  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
42  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
45  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
46  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
47  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
48  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
50  * POSSIBILITY OF SUCH DAMAGE.
51  */
52
53 /*
54 #include <err.h>
55 #include <errno.h>
56 */
57 #include <libpayload.h>
58 #include <getopt.h>
59 #define warnx(x...) printf(x)
60 /*
61 #include <stdlib.h>
62 #include <string.h>
63 */
64 #define REPLACE_GETOPT          /* use this getopt as the system getopt(3) */
65
66 #ifdef REPLACE_GETOPT
67 int     opterr = 1;             /* if error message should be printed */
68 int     optind = 1;             /* index into parent argv vector */
69 int     optopt = '?';           /* character checked for validity */
70 int     optreset;               /* reset getopt */
71 char    *optarg;                /* argument associated with option */
72
73 int posixly_correct = 0;
74 #endif
75
76 #define PRINT_ERROR     ((opterr) && (*options != ':'))
77
78 #define FLAG_PERMUTE    0x01    /* permute non-options to the end of argv */
79 #define FLAG_ALLARGS    0x02    /* treat non-options as args to option "-1" */
80 #define FLAG_LONGONLY   0x04    /* operate as getopt_long_only */
81
82 /* return values */
83 #define BADCH           (int)'?'
84 #define BADARG          ((*options == ':') ? (int)':' : (int)'?')
85 #define INORDER         (int)1
86
87 #define EMSG            ""
88
89 static int getopt_internal(int, char * const *, const char *,
90                            const struct option *, int *, int);
91 static int parse_long_options(char * const *, const char *,
92                               const struct option *, int *, int);
93 static int gcd(int, int);
94 static void permute_args(int, int, int, char * const *);
95
96 static char *place = EMSG; /* option letter processing */
97
98 /* XXX: set optreset to 1 rather than these two */
99 static int nonopt_start = -1; /* first non option argument (for permute) */
100 static int nonopt_end = -1;   /* first option after non options (for permute) */
101
102 /* Error messages */
103 static const char recargchar[] = "option requires an argument -- %c";
104 static const char recargstring[] = "option requires an argument -- %s";
105 static const char ambig[] = "ambiguous option -- %.*s";
106 static const char noarg[] = "option doesn't take an argument -- %.*s";
107 static const char illoptchar[] = "unknown option -- %c";
108 static const char illoptstring[] = "unknown option -- %s";
109
110 /*
111  * Compute the greatest common divisor of a and b.
112  */
113 static int
114 gcd(int a, int b)
115 {
116         int c;
117
118         c = a % b;
119         while (c != 0) {
120                 a = b;
121                 b = c;
122                 c = a % b;
123         }
124
125         return (b);
126 }
127
128 /*
129  * Exchange the block from nonopt_start to nonopt_end with the block
130  * from nonopt_end to opt_end (keeping the same order of arguments
131  * in each block).
132  */
133 static void
134 permute_args(int panonopt_start, int panonopt_end, int opt_end,
135         char * const *nargv)
136 {
137         int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
138         char *swap;
139
140         /*
141          * compute lengths of blocks and number and size of cycles
142          */
143         nnonopts = panonopt_end - panonopt_start;
144         nopts = opt_end - panonopt_end;
145         ncycle = gcd(nnonopts, nopts);
146         cyclelen = (opt_end - panonopt_start) / ncycle;
147
148         for (i = 0; i < ncycle; i++) {
149                 cstart = panonopt_end+i;
150                 pos = cstart;
151                 for (j = 0; j < cyclelen; j++) {
152                         if (pos >= panonopt_end)
153                                 pos -= nnonopts;
154                         else
155                                 pos += nopts;
156                         swap = nargv[pos];
157                         /* LINTED const cast */
158                         ((char **) nargv)[pos] = nargv[cstart];
159                         /* LINTED const cast */
160                         ((char **)nargv)[cstart] = swap;
161                 }
162         }
163 }
164
165 /*
166  * parse_long_options --
167  *      Parse long options in argc/argv argument vector.
168  * Returns -1 if short_too is set and the option does not match long_options.
169  */
170 static int
171 parse_long_options(char * const *nargv, const char *options,
172         const struct option *long_options, int *idx, int short_too)
173 {
174         char *current_argv, *has_equal;
175         size_t current_argv_len;
176         int i, match;
177
178         current_argv = place;
179         match = -1;
180
181         optind++;
182
183         if ((has_equal = strchr(current_argv, '=')) != NULL) {
184                 /* argument found (--option=arg) */
185                 current_argv_len = has_equal - current_argv;
186                 has_equal++;
187         } else
188                 current_argv_len = strlen(current_argv);
189
190         for (i = 0; long_options[i].name; i++) {
191                 /* find matching long option */
192                 if (strncmp(current_argv, long_options[i].name,
193                     current_argv_len))
194                         continue;
195
196                 if (strlen(long_options[i].name) == current_argv_len) {
197                         /* exact match */
198                         match = i;
199                         break;
200                 }
201                 /*
202                  * If this is a known short option, don't allow
203                  * a partial match of a single character.
204                  */
205                 if (short_too && current_argv_len == 1)
206                         continue;
207
208                 if (match == -1)        /* partial match */
209                         match = i;
210                 else {
211                         /* ambiguous abbreviation */
212                         if (PRINT_ERROR)
213                                 warnx(ambig, (int)current_argv_len,
214                                      current_argv);
215                         optopt = 0;
216                         return (BADCH);
217                 }
218         }
219         if (match != -1) {              /* option found */
220                 if (long_options[match].has_arg == no_argument
221                     && has_equal) {
222                         if (PRINT_ERROR)
223                                 warnx(noarg, (int)current_argv_len,
224                                      current_argv);
225                         /*
226                          * XXX: GNU sets optopt to val regardless of flag
227                          */
228                         if (long_options[match].flag == NULL)
229                                 optopt = long_options[match].val;
230                         else
231                                 optopt = 0;
232                         return (BADARG);
233                 }
234                 if (long_options[match].has_arg == required_argument ||
235                     long_options[match].has_arg == optional_argument) {
236                         if (has_equal)
237                                 optarg = has_equal;
238                         else if (long_options[match].has_arg ==
239                             required_argument) {
240                                 /*
241                                  * optional argument doesn't use next nargv
242                                  */
243                                 optarg = nargv[optind++];
244                         }
245                 }
246                 if ((long_options[match].has_arg == required_argument)
247                     && (optarg == NULL)) {
248                         /*
249                          * Missing argument; leading ':' indicates no error
250                          * should be generated.
251                          */
252                         if (PRINT_ERROR)
253                                 warnx(recargstring,
254                                     current_argv);
255                         /*
256                          * XXX: GNU sets optopt to val regardless of flag
257                          */
258                         if (long_options[match].flag == NULL)
259                                 optopt = long_options[match].val;
260                         else
261                                 optopt = 0;
262                         --optind;
263                         return (BADARG);
264                 }
265         } else {                        /* unknown option */
266                 if (short_too) {
267                         --optind;
268                         return (-1);
269                 }
270                 if (PRINT_ERROR)
271                         warnx(illoptstring, current_argv);
272                 optopt = 0;
273                 return (BADCH);
274         }
275         if (idx)
276                 *idx = match;
277         if (long_options[match].flag) {
278                 *long_options[match].flag = long_options[match].val;
279                 return (0);
280         } else
281                 return (long_options[match].val);
282 }
283
284 /*
285  * getopt_internal --
286  *      Parse argc/argv argument vector.  Called by user level routines.
287  */
288 static int
289 getopt_internal(int nargc, char * const *nargv, const char *options,
290         const struct option *long_options, int *idx, int flags)
291 {
292         char *oli;                              /* option letter list index */
293         int optchar, short_too;
294
295         if (options == NULL)
296                 return (-1);
297
298         /*
299          * Disable GNU extensions if posixly_correct is set or options
300          * string begins with a '+'.
301          */
302         if (posixly_correct || *options == '+')
303                 flags &= ~FLAG_PERMUTE;
304         else if (*options == '-')
305                 flags |= FLAG_ALLARGS;
306         if (*options == '+' || *options == '-')
307                 options++;
308
309         /*
310          * XXX Some GNU programs (like cvs) set optind to 0 instead of
311          * XXX using optreset.  Work around this braindamage.
312          */
313         if (optind == 0)
314                 optind = optreset = 1;
315
316         optarg = NULL;
317         if (optreset)
318                 nonopt_start = nonopt_end = -1;
319 start:
320         if (optreset || !*place) {              /* update scanning pointer */
321                 optreset = 0;
322                 if (optind >= nargc) {          /* end of argument vector */
323                         place = EMSG;
324                         if (nonopt_end != -1) {
325                                 /* do permutation, if we have to */
326                                 permute_args(nonopt_start, nonopt_end,
327                                     optind, nargv);
328                                 optind -= nonopt_end - nonopt_start;
329                         }
330                         else if (nonopt_start != -1) {
331                                 /*
332                                  * If we skipped non-options, set optind
333                                  * to the first of them.
334                                  */
335                                 optind = nonopt_start;
336                         }
337                         nonopt_start = nonopt_end = -1;
338                         return (-1);
339                 }
340                 if (*(place = nargv[optind]) != '-' ||
341                     (place[1] == '\0' && strchr(options, '-') == NULL)) {
342                         place = EMSG;           /* found non-option */
343                         if (flags & FLAG_ALLARGS) {
344                                 /*
345                                  * GNU extension:
346                                  * return non-option as argument to option 1
347                                  */
348                                 optarg = nargv[optind++];
349                                 return (INORDER);
350                         }
351                         if (!(flags & FLAG_PERMUTE)) {
352                                 /*
353                                  * If no permutation wanted, stop parsing
354                                  * at first non-option.
355                                  */
356                                 return (-1);
357                         }
358                         /* do permutation */
359                         if (nonopt_start == -1)
360                                 nonopt_start = optind;
361                         else if (nonopt_end != -1) {
362                                 permute_args(nonopt_start, nonopt_end,
363                                     optind, nargv);
364                                 nonopt_start = optind -
365                                     (nonopt_end - nonopt_start);
366                                 nonopt_end = -1;
367                         }
368                         optind++;
369                         /* process next argument */
370                         goto start;
371                 }
372                 if (nonopt_start != -1 && nonopt_end == -1)
373                         nonopt_end = optind;
374
375                 /*
376                  * If we have "-" do nothing, if "--" we are done.
377                  */
378                 if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
379                         optind++;
380                         place = EMSG;
381                         /*
382                          * We found an option (--), so if we skipped
383                          * non-options, we have to permute.
384                          */
385                         if (nonopt_end != -1) {
386                                 permute_args(nonopt_start, nonopt_end,
387                                     optind, nargv);
388                                 optind -= nonopt_end - nonopt_start;
389                         }
390                         nonopt_start = nonopt_end = -1;
391                         return (-1);
392                 }
393         }
394
395         /*
396          * Check long options if:
397          *  1) we were passed some
398          *  2) the arg is not just "-"
399          *  3) either the arg starts with -- we are getopt_long_only()
400          */
401         if (long_options != NULL && place != nargv[optind] &&
402             (*place == '-' || (flags & FLAG_LONGONLY))) {
403                 short_too = 0;
404                 if (*place == '-')
405                         place++;                /* --foo long option */
406                 else if (*place != ':' && strchr(options, *place) != NULL)
407                         short_too = 1;          /* could be short option too */
408
409                 optchar = parse_long_options(nargv, options, long_options,
410                     idx, short_too);
411                 if (optchar != -1) {
412                         place = EMSG;
413                         return (optchar);
414                 }
415         }
416
417         if ((optchar = (int)*place++) == (int)':' ||
418             (optchar == (int)'-' && *place != '\0') ||
419             (oli = strchr(options, optchar)) == NULL) {
420                 /*
421                  * If the user specified "-" and  '-' isn't listed in
422                  * options, return -1 (non-option) as per POSIX.
423                  * Otherwise, it is an unknown option character (or ':').
424                  */
425                 if (optchar == (int)'-' && *place == '\0')
426                         return (-1);
427                 if (!*place)
428                         ++optind;
429                 if (PRINT_ERROR)
430                         warnx(illoptchar, optchar);
431                 optopt = optchar;
432                 return (BADCH);
433         }
434         if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
435                 /* -W long-option */
436                 if (*place)                     /* no space */
437                         /* NOTHING */;
438                 else if (++optind >= nargc) {   /* no arg */
439                         place = EMSG;
440                         if (PRINT_ERROR)
441                                 warnx(recargchar, optchar);
442                         optopt = optchar;
443                         return (BADARG);
444                 } else                          /* white space */
445                         place = nargv[optind];
446                 optchar = parse_long_options(nargv, options, long_options,
447                     idx, 0);
448                 place = EMSG;
449                 return (optchar);
450         }
451         if (*++oli != ':') {                    /* doesn't take argument */
452                 if (!*place)
453                         ++optind;
454         } else {                                /* takes (optional) argument */
455                 optarg = NULL;
456                 if (*place)                     /* no white space */
457                         optarg = place;
458                 else if (oli[1] != ':') {       /* arg not optional */
459                         if (++optind >= nargc) {        /* no arg */
460                                 place = EMSG;
461                                 if (PRINT_ERROR)
462                                         warnx(recargchar, optchar);
463                                 optopt = optchar;
464                                 return (BADARG);
465                         } else
466                                 optarg = nargv[optind];
467                 }
468                 place = EMSG;
469                 ++optind;
470         }
471         /* dump back option letter */
472         return (optchar);
473 }
474
475 #ifdef REPLACE_GETOPT
476 /*
477  * getopt --
478  *      Parse argc/argv argument vector.
479  *
480  * [eventually this will replace the BSD getopt]
481  */
482 int
483 getopt(int nargc, char * const *nargv, const char *options)
484 {
485
486         /*
487          * We don't pass FLAG_PERMUTE to getopt_internal() since
488          * the BSD getopt(3) (unlike GNU) has never done this.
489          *
490          * Furthermore, since many privileged programs call getopt()
491          * before dropping privileges it makes sense to keep things
492          * as simple (and bug-free) as possible.
493          */
494         return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
495 }
496 #endif /* REPLACE_GETOPT */
497
498 /*
499  * getopt_long --
500  *      Parse argc/argv argument vector.
501  */
502 int
503 getopt_long(int nargc, char * const *nargv, const char *options,
504     const struct option *long_options, int *idx)
505 {
506
507         return (getopt_internal(nargc, nargv, options, long_options, idx,
508             FLAG_PERMUTE));
509 }
510
511 /*
512  * getopt_long_only --
513  *      Parse argc/argv argument vector.
514  */
515 int
516 getopt_long_only(int nargc, char * const *nargv, const char *options,
517     const struct option *long_options, int *idx)
518 {
519
520         return (getopt_internal(nargc, nargv, options, long_options, idx,
521             FLAG_PERMUTE|FLAG_LONGONLY));
522 }