Debian Codegraph @

src/compat/getopt.c

raw symbols SCIP
1 /* $NetBSD: getopt_long.c,v 1.27 2015/09/01 19:39:57 kamil Exp $ */
2
3 /*-
4 * Copyright (c) 2000 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Dieter Baron and Thomas Klausner.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 #include "config.h"
33
34 #include <assert.h>
35 #include <errno.h>
36 #include <getopt.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40
41 #define REPLACE_GETOPT
42
43 #define _DIAGASSERT(x) assert(x)
44 #define __UNCONST(x) (char *)(x)
45
46 #ifdef REPLACE_GETOPT
47 #ifdef __weak_alias
48 __weak_alias(getopt,_getopt)
49 #endif
50 int opterr = 1; /* if error message should be printed */
51 int optind = 1; /* index into parent argv vector */
52 int optopt = '?'; /* character checked for validity */
53 int optreset; /* reset getopt */
54 char *optarg; /* argument associated with option */
55 #elif HAVE_NBTOOL_CONFIG_H && !HAVE_DECL_OPTRESET
56 static int optreset;
57 #endif
58
59 #ifdef __weak_alias
60 __weak_alias(getopt_long,_getopt_long)
61 #endif
62
63 #define IGNORE_FIRST (*options == '-' || *options == '+')
64 #define PRINT_ERROR ((opterr) && ((*options != ':') \
65 || (IGNORE_FIRST && options[1] != ':')))
66 #define IS_POSIXLY_CORRECT (getenv("POSIXLY_CORRECT") != NULL)
67 #define PERMUTE (!IS_POSIXLY_CORRECT && !IGNORE_FIRST)
68 /* XXX: GNU ignores PC if *options == '-' */
69 #define IN_ORDER (!IS_POSIXLY_CORRECT && *options == '-')
70
71 /* return values */
72 #define BADCH (int)'?'
73 #define BADARG ((IGNORE_FIRST && options[1] == ':') \
74 || (*options == ':') ? (int)':' : (int)'?')
75 #define INORDER (int)1
76
77 #define EMSG ""
78
79 static int getopt_internal(int, char **, const char *);
80 static int gcd(int, int);
81 static void permute_args(int, int, int, char **);
82
83 static const char *place = EMSG; /* option letter processing */
84
85 /* XXX: set optreset to 1 rather than these two */
86 static int nonopt_start = -1; /* first non option argument (for permute) */
87 static int nonopt_end = -1; /* first option after non options (for permute) */
88
89 /* Error messages */
90 static const char recargchar[] = "option requires an argument -- %c";
91 static const char recargstring[] = "option requires an argument -- %s";
92 static const char ambig[] = "ambiguous option -- %.*s";
93 static const char noarg[] = "option doesn't take an argument -- %.*s";
94 static const char illoptchar[] = "unknown option -- %c";
95 static const char illoptstring[] = "unknown option -- %s";
96
97
98 /*
99 * Compute the greatest common divisor of a and b.
100 */
101 static int
102 gcd(int a, int b)
103 {
104 int c;
105
106 c = a % b;
107 while (c != 0) {
108 a = b;
109 b = c;
110 c = a % b;
111 }
112
113 return b;
114 }
115
116 /*
117 * Exchange the block from nonopt_start to nonopt_end with the block
118 * from nonopt_end to opt_end (keeping the same order of arguments
119 * in each block).
120 */
121 static void
122 permute_args(int panonopt_start, int panonopt_end, int opt_end, char **nargv)
123 {
124 int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
125 char *swap;
126
127 _DIAGASSERT(nargv != NULL);
128
129 /*
130 * compute lengths of blocks and number and size of cycles
131 */
132 nnonopts = panonopt_end - panonopt_start;
133 nopts = opt_end - panonopt_end;
134 ncycle = gcd(nnonopts, nopts);
135 cyclelen = (opt_end - panonopt_start) / ncycle;
136
137 for (i = 0; i < ncycle; i++) {
138 cstart = panonopt_end+i;
139 pos = cstart;
140 for (j = 0; j < cyclelen; j++) {
141 if (pos >= panonopt_end)
142 pos -= nnonopts;
143 else
144 pos += nopts;
145 swap = nargv[pos];
146 nargv[pos] = nargv[cstart];
147 nargv[cstart] = swap;
148 }
149 }
150 }
151
152 /*
153 * getopt_internal --
154 * Parse argc/argv argument vector. Called by user level routines.
155 * Returns -2 if -- is found (can be long option or end of options marker).
156 */
157 static int
158 getopt_internal(int nargc, char **nargv, const char *options)
159 {
160 char *oli; /* option letter list index */
161 int optchar;
162
163 _DIAGASSERT(nargv != NULL);
164 _DIAGASSERT(options != NULL);
165
166 optarg = NULL;
167
168 /*
169 * XXX Some programs (like rsyncd) expect to be able to
170 * XXX re-initialize optind to 0 and have getopt_long(3)
171 * XXX properly function again. Work around this braindamage.
172 */
173 if (optind == 0)
174 optind = 1;
175
176 if (optreset)
177 nonopt_start = nonopt_end = -1;
178 start:
179 if (optreset || !*place) { /* update scanning pointer */
180 optreset = 0;
181 if (optind >= nargc) { /* end of argument vector */
182 place = EMSG;
183 if (nonopt_end != -1) {
184 /* do permutation, if we have to */
185 permute_args(nonopt_start, nonopt_end,
186 optind, nargv);
187 optind -= nonopt_end - nonopt_start;
188 }
189 else if (nonopt_start != -1) {
190 /*
191 * If we skipped non-options, set optind
192 * to the first of them.
193 */
194 optind = nonopt_start;
195 }
196 nonopt_start = nonopt_end = -1;
197 return -1;
198 }
199 if ((*(place = nargv[optind]) != '-')
200 || (place[1] == '\0')) { /* found non-option */
201 place = EMSG;
202 if (IN_ORDER) {
203 /*
204 * GNU extension:
205 * return non-option as argument to option 1
206 */
207 optarg = nargv[optind++];
208 return INORDER;
209 }
210 if (!PERMUTE) {
211 /*
212 * if no permutation wanted, stop parsing
213 * at first non-option
214 */
215 return -1;
216 }
217 /* do permutation */
218 if (nonopt_start == -1)
219 nonopt_start = optind;
220 else if (nonopt_end != -1) {
221 permute_args(nonopt_start, nonopt_end,
222 optind, nargv);
223 nonopt_start = optind -
224 (nonopt_end - nonopt_start);
225 nonopt_end = -1;
226 }
227 optind++;
228 /* process next argument */
229 goto start;
230 }
231 if (nonopt_start != -1 && nonopt_end == -1)
232 nonopt_end = optind;
233 if (place[1] && *++place == '-') { /* found "--" */
234 place++;
235 return -2;
236 }
237 }
238 if ((optchar = (int)*place++) == (int)':' ||
239 (oli = strchr(options + (IGNORE_FIRST ? 1 : 0), optchar)) == NULL) {
240 /* option letter unknown or ':' */
241 if (!*place)
242 ++optind;
243 if (PRINT_ERROR)
244 fprintf(stderr, illoptchar, optchar);
245 optopt = optchar;
246 return BADCH;
247 }
248 if (optchar == 'W' && oli[1] == ';') { /* -W long-option */
249 /* XXX: what if no long options provided (called by getopt)? */
250 if (*place)
251 return -2;
252
253 if (++optind >= nargc) { /* no arg */
254 place = EMSG;
255 if (PRINT_ERROR)
256 fprintf(stderr, recargchar, optchar);
257 optopt = optchar;
258 return BADARG;
259 } else /* white space */
260 place = nargv[optind];
261 /*
262 * Handle -W arg the same as --arg (which causes getopt to
263 * stop parsing).
264 */
265 return -2;
266 }
267 if (*++oli != ':') { /* doesn't take argument */
268 if (!*place)
269 ++optind;
270 } else { /* takes (optional) argument */
271 optarg = NULL;
272 if (*place) /* no white space */
273 optarg = __UNCONST(place);
274 /* XXX: disable test for :: if PC? (GNU doesn't) */
275 else if (oli[1] != ':') { /* arg not optional */
276 if (++optind >= nargc) { /* no arg */
277 place = EMSG;
278 if (PRINT_ERROR)
279 fprintf(stderr, recargchar, optchar);
280 optopt = optchar;
281 return BADARG;
282 } else
283 optarg = nargv[optind];
284 }
285 place = EMSG;
286 ++optind;
287 }
288 /* dump back option letter */
289 return optchar;
290 }
291
292 #ifdef REPLACE_GETOPT
293 /*
294 * getopt --
295 * Parse argc/argv argument vector.
296 *
297 * [eventually this will replace the real getopt]
298 */
299 int
300 getopt(int nargc, char * const *nargv, const char *options)
301 {
302 int retval;
303
304 _DIAGASSERT(nargv != NULL);
305 _DIAGASSERT(options != NULL);
306
307 retval = getopt_internal(nargc, __UNCONST(nargv), options);
308 if (retval == -2) {
309 ++optind;
310 /*
311 * We found an option (--), so if we skipped non-options,
312 * we have to permute.
313 */
314 if (nonopt_end != -1) {
315 permute_args(nonopt_start, nonopt_end, optind,
316 __UNCONST(nargv));
317 optind -= nonopt_end - nonopt_start;
318 }
319 nonopt_start = nonopt_end = -1;
320 retval = -1;
321 }
322 return retval;
323 }
324 #endif
325
326 /*
327 * getopt_long --
328 * Parse argc/argv argument vector.
329 */
330 int
331 getopt_long(int nargc, char * const *nargv, const char *options,
332 const struct option *long_options, int *idx)
333 {
334 int retval;
335
336 #define IDENTICAL_INTERPRETATION(_x, _y) \
337 (long_options[(_x)].has_arg == long_options[(_y)].has_arg && \
338 long_options[(_x)].flag == long_options[(_y)].flag && \
339 long_options[(_x)].val == long_options[(_y)].val)
340
341 _DIAGASSERT(nargv != NULL);
342 _DIAGASSERT(options != NULL);
343 _DIAGASSERT(long_options != NULL);
344 /* idx may be NULL */
345
346 retval = getopt_internal(nargc, __UNCONST(nargv), options);
347 if (retval == -2) {
348 char *current_argv, *has_equal;
349 size_t current_argv_len;
350 int i, ambiguous, match;
351
352 current_argv = __UNCONST(place);
353 match = -1;
354 ambiguous = 0;
355
356 optind++;
357 place = EMSG;
358
359 if (*current_argv == '\0') { /* found "--" */
360 /*
361 * We found an option (--), so if we skipped
362 * non-options, we have to permute.
363 */
364 if (nonopt_end != -1) {
365 permute_args(nonopt_start, nonopt_end,
366 optind, __UNCONST(nargv));
367 optind -= nonopt_end - nonopt_start;
368 }
369 nonopt_start = nonopt_end = -1;
370 return -1;
371 }
372 if ((has_equal = strchr(current_argv, '=')) != NULL) {
373 /* argument found (--option=arg) */
374 current_argv_len = has_equal - current_argv;
375 has_equal++;
376 } else
377 current_argv_len = strlen(current_argv);
378
379 for (i = 0; long_options[i].name; i++) {
380 /* find matching long option */
381 if (strncmp(current_argv, long_options[i].name,
382 current_argv_len))
383 continue;
384
385 if (strlen(long_options[i].name) ==
386 (unsigned)current_argv_len) {
387 /* exact match */
388 match = i;
389 ambiguous = 0;
390 break;
391 }
392 if (match == -1) /* partial match */
393 match = i;
394 else if (!IDENTICAL_INTERPRETATION(i, match))
395 ambiguous = 1;
396 }
397 if (ambiguous) {
398 /* ambiguous abbreviation */
399 if (PRINT_ERROR)
400 fprintf(stderr, ambig, (int)current_argv_len,
401 current_argv);
402 optopt = 0;
403 return BADCH;
404 }
405 if (match != -1) { /* option found */
406 if (long_options[match].has_arg == no_argument
407 && has_equal) {
408 if (PRINT_ERROR)
409 fprintf(stderr, noarg, (int)current_argv_len,
410 current_argv);
411 /*
412 * XXX: GNU sets optopt to val regardless of
413 * flag
414 */
415 if (long_options[match].flag == NULL)
416 optopt = long_options[match].val;
417 else
418 optopt = 0;
419 return BADARG;
420 }
421 if (long_options[match].has_arg == required_argument ||
422 long_options[match].has_arg == optional_argument) {
423 if (has_equal)
424 optarg = has_equal;
425 else if (long_options[match].has_arg ==
426 required_argument) {
427 /*
428 * optional argument doesn't use
429 * next nargv
430 */
431 optarg = nargv[optind++];
432 }
433 }
434 if ((long_options[match].has_arg == required_argument)
435 && (optarg == NULL)) {
436 /*
437 * Missing argument; leading ':'
438 * indicates no error should be generated
439 */
440 if (PRINT_ERROR)
441 fprintf(stderr, recargstring, current_argv);
442 /*
443 * XXX: GNU sets optopt to val regardless
444 * of flag
445 */
446 if (long_options[match].flag == NULL)
447 optopt = long_options[match].val;
448 else
449 optopt = 0;
450 --optind;
451 return BADARG;
452 }
453 } else { /* unknown option */
454 if (PRINT_ERROR)
455 fprintf(stderr, illoptstring, current_argv);
456 optopt = 0;
457 return BADCH;
458 }
459 if (long_options[match].flag) {
460 *long_options[match].flag = long_options[match].val;
461 retval = 0;
462 } else
463 retval = long_options[match].val;
464 if (idx)
465 *idx = match;
466 }
467 return retval;
468 #undef IDENTICAL_INTERPRETATION
469 }
470