Debian Codegraph @

compat/getopt.c

raw symbols SCIP
1 /* $OpenBSD: getopt_long.c,v 1.26 2013/06/08 22:47:56 millert 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 <[email protected]>
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 *
19 * Sponsored in part by the Defense Advanced Research Projects
20 * Agency (DARPA) and Air Force Research Laboratory, Air Force
21 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
22 */
23 /*-
24 * Copyright (c) 2000 The NetBSD Foundation, Inc.
25 * All rights reserved.
26 *
27 * This code is derived from software contributed to The NetBSD Foundation
28 * by Dieter Baron and Thomas Klausner.
29 *
30 * Redistribution and use in source and binary forms, with or without
31 * modification, are permitted provided that the following conditions
32 * are met:
33 * 1. Redistributions of source code must retain the above copyright
34 * notice, this list of conditions and the following disclaimer.
35 * 2. Redistributions in binary form must reproduce the above copyright
36 * notice, this list of conditions and the following disclaimer in the
37 * documentation and/or other materials provided with the distribution.
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
40 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
41 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
43 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
44 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
45 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
46 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
47 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
49 * POSSIBILITY OF SUCH DAMAGE.
50 */
51
52 #include <err.h>
53 #include <errno.h>
54 #include <getopt.h>
55 #include <stdlib.h>
56 #include <string.h>
57
58 #include "compat.h"
59
60 int opterr = 1; /* if error message should be printed */
61 int optind = 1; /* index into parent argv vector */
62 int optopt = '?'; /* character checked for validity */
63 int optreset; /* reset getopt */
64 char *optarg; /* argument associated with option */
65
66 #define PRINT_ERROR ((opterr) && (*options != ':'))
67
68 #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
69 #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
70 #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
71
72 /* return values */
73 #define BADCH (int)'?'
74 #define BADARG ((*options == ':') ? (int)':' : (int)'?')
75 #define INORDER (int)1
76
77 #define EMSG ""
78
79 static int getopt_internal(int, char * const *, const char *,
80 const struct option *, int *, int);
81 static int parse_long_options(char * const *, const char *,
82 const struct option *, int *, int, int);
83 static int gcd(int, int);
84 static void permute_args(int, int, int, char * const *);
85
86 static char *place = EMSG; /* option letter processing */
87
88 /* XXX: set optreset to 1 rather than these two */
89 static int nonopt_start = -1; /* first non option argument (for permute) */
90 static int nonopt_end = -1; /* first option after non options (for permute) */
91
92 /* Error messages */
93 static const char recargchar[] = "option requires an argument -- %c";
94 static const char recargstring[] = "option requires an argument -- %s";
95 static const char ambig[] = "ambiguous option -- %.*s";
96 static const char noarg[] = "option doesn't take an argument -- %.*s";
97 static const char illoptchar[] = "unknown option -- %c";
98 static const char illoptstring[] = "unknown option -- %s";
99
100 /*
101 * Compute the greatest common divisor of a and b.
102 */
103 static int
104 gcd(int a, int b)
105 {
106 int c;
107
108 c = a % b;
109 while (c != 0) {
110 a = b;
111 b = c;
112 c = a % b;
113 }
114
115 return (b);
116 }
117
118 /*
119 * Exchange the block from nonopt_start to nonopt_end with the block
120 * from nonopt_end to opt_end (keeping the same order of arguments
121 * in each block).
122 */
123 static void
124 permute_args(int panonopt_start, int panonopt_end, int opt_end,
125 char * const *nargv)
126 {
127 int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
128 char *swap;
129
130 /*
131 * compute lengths of blocks and number and size of cycles
132 */
133 nnonopts = panonopt_end - panonopt_start;
134 nopts = opt_end - panonopt_end;
135 ncycle = gcd(nnonopts, nopts);
136 cyclelen = (opt_end - panonopt_start) / ncycle;
137
138 for (i = 0; i < ncycle; i++) {
139 cstart = panonopt_end+i;
140 pos = cstart;
141 for (j = 0; j < cyclelen; j++) {
142 if (pos >= panonopt_end)
143 pos -= nnonopts;
144 else
145 pos += nopts;
146 swap = nargv[pos];
147 /* LINTED const cast */
148 ((char **) nargv)[pos] = nargv[cstart];
149 /* LINTED const cast */
150 ((char **)nargv)[cstart] = swap;
151 }
152 }
153 }
154
155 /*
156 * parse_long_options --
157 * Parse long options in argc/argv argument vector.
158 * Returns -1 if short_too is set and the option does not match long_options.
159 */
160 static int
161 parse_long_options(char * const *nargv, const char *options,
162 const struct option *long_options, int *idx, int short_too, int flags)
163 {
164 char *current_argv, *has_equal;
165 size_t current_argv_len;
166 int i, match, exact_match, second_partial_match;
167
168 current_argv = place;
169 match = -1;
170 exact_match = 0;
171 second_partial_match = 0;
172
173 optind++;
174
175 if ((has_equal = strchr(current_argv, '=')) != NULL) {
176 /* argument found (--option=arg) */
177 current_argv_len = has_equal - current_argv;
178 has_equal++;
179 } else
180 current_argv_len = strlen(current_argv);
181
182 for (i = 0; long_options[i].name; i++) {
183 /* find matching long option */
184 if (strncmp(current_argv, long_options[i].name,
185 current_argv_len))
186 continue;
187
188 if (strlen(long_options[i].name) == current_argv_len) {
189 /* exact match */
190 match = i;
191 exact_match = 1;
192 break;
193 }
194 /*
195 * If this is a known short option, don't allow
196 * a partial match of a single character.
197 */
198 if (short_too && current_argv_len == 1)
199 continue;
200
201 if (match == -1) /* first partial match */
202 match = i;
203 else if ((flags & FLAG_LONGONLY) ||
204 long_options[i].has_arg != long_options[match].has_arg ||
205 long_options[i].flag != long_options[match].flag ||
206 long_options[i].val != long_options[match].val)
207 second_partial_match = 1;
208 }
209 if (!exact_match && second_partial_match) {
210 /* ambiguous abbreviation */
211 if (PRINT_ERROR)
212 warnx(ambig, (int)current_argv_len, current_argv);
213 optopt = 0;
214 return (BADCH);
215 }
216 if (match != -1) { /* option found */
217 if (long_options[match].has_arg == no_argument
218 && has_equal) {
219 if (PRINT_ERROR)
220 warnx(noarg, (int)current_argv_len,
221 current_argv);
222 /*
223 * XXX: GNU sets optopt to val regardless of flag
224 */
225 if (long_options[match].flag == NULL)
226 optopt = long_options[match].val;
227 else
228 optopt = 0;
229 return (BADARG);
230 }
231 if (long_options[match].has_arg == required_argument ||
232 long_options[match].has_arg == optional_argument) {
233 if (has_equal)
234 optarg = has_equal;
235 else if (long_options[match].has_arg ==
236 required_argument) {
237 /*
238 * optional argument doesn't use next nargv
239 */
240 optarg = nargv[optind++];
241 }
242 }
243 if ((long_options[match].has_arg == required_argument)
244 && (optarg == NULL)) {
245 /*
246 * Missing argument; leading ':' indicates no error
247 * should be generated.
248 */
249 if (PRINT_ERROR)
250 warnx(recargstring,
251 current_argv);
252 /*
253 * XXX: GNU sets optopt to val regardless of flag
254 */
255 if (long_options[match].flag == NULL)
256 optopt = long_options[match].val;
257 else
258 optopt = 0;
259 --optind;
260 return (BADARG);
261 }
262 } else { /* unknown option */
263 if (short_too) {
264 --optind;
265 return (-1);
266 }
267 if (PRINT_ERROR)
268 warnx(illoptstring, current_argv);
269 optopt = 0;
270 return (BADCH);
271 }
272 if (idx)
273 *idx = match;
274 if (long_options[match].flag) {
275 *long_options[match].flag = long_options[match].val;
276 return (0);
277 } else
278 return (long_options[match].val);
279 }
280
281 /*
282 * getopt_internal --
283 * Parse argc/argv argument vector. Called by user level routines.
284 */
285 static int
286 getopt_internal(int nargc, char * const *nargv, const char *options,
287 const struct option *long_options, int *idx, int flags)
288 {
289 char *oli; /* option letter list index */
290 int optchar, short_too;
291 static int posixly_correct = -1;
292
293 if (options == NULL)
294 return (-1);
295
296 /*
297 * XXX Some GNU programs (like cvs) set optind to 0 instead of
298 * XXX using optreset. Work around this braindamage.
299 */
300 if (optind == 0)
301 optind = optreset = 1;
302
303 /*
304 * Disable GNU extensions if POSIXLY_CORRECT is set or options
305 * string begins with a '+'.
306 */
307 if (posixly_correct == -1 || optreset)
308 posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
309 if (*options == '-')
310 flags |= FLAG_ALLARGS;
311 else if (posixly_correct || *options == '+')
312 flags &= ~FLAG_PERMUTE;
313 if (*options == '+' || *options == '-')
314 options++;
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, flags);
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, flags);
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 /*
476 * getopt --
477 * Parse argc/argv argument vector.
478 *
479 * [eventually this will replace the BSD getopt]
480 */
481 int
482 getopt(int nargc, char * const *nargv, const char *options)
483 {
484
485 /*
486 * We don't pass FLAG_PERMUTE to getopt_internal() since
487 * the BSD getopt(3) (unlike GNU) has never done this.
488 *
489 * Furthermore, since many privileged programs call getopt()
490 * before dropping privileges it makes sense to keep things
491 * as simple (and bug-free) as possible.
492 */
493 return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
494 }
495
496 /*
497 * getopt_long --
498 * Parse argc/argv argument vector.
499 */
500 int
501 getopt_long(int nargc, char * const *nargv, const char *options,
502 const struct option *long_options, int *idx)
503 {
504
505 return (getopt_internal(nargc, nargv, options, long_options, idx,
506 FLAG_PERMUTE));
507 }
508
509 /*
510 * getopt_long_only --
511 * Parse argc/argv argument vector.
512 */
513 int
514 getopt_long_only(int nargc, char * const *nargv, const char *options,
515 const struct option *long_options, int *idx)
516 {
517
518 return (getopt_internal(nargc, nargv, options, long_options, idx,
519 FLAG_PERMUTE|FLAG_LONGONLY));
520 }