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