xref: /netbsd-src/bin/sh/options.c (revision 1b9578b8c2c1f848eeb16dabbfd7d1f0d9fdefbd)
1 /*	$NetBSD: options.c,v 1.42 2011/06/18 21:18:46 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Kenneth Almquist.
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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)options.c	8.2 (Berkeley) 5/4/95";
39 #else
40 __RCSID("$NetBSD: options.c,v 1.42 2011/06/18 21:18:46 christos Exp $");
41 #endif
42 #endif /* not lint */
43 
44 #include <signal.h>
45 #include <unistd.h>
46 #include <stdlib.h>
47 
48 #include "shell.h"
49 #define DEFINE_OPTIONS
50 #include "options.h"
51 #undef DEFINE_OPTIONS
52 #include "builtins.h"
53 #include "nodes.h"	/* for other header files */
54 #include "eval.h"
55 #include "jobs.h"
56 #include "input.h"
57 #include "output.h"
58 #include "trap.h"
59 #include "var.h"
60 #include "memalloc.h"
61 #include "error.h"
62 #include "mystring.h"
63 #ifndef SMALL
64 #include "myhistedit.h"
65 #endif
66 #include "show.h"
67 
68 char *arg0;			/* value of $0 */
69 struct shparam shellparam;	/* current positional parameters */
70 char **argptr;			/* argument list for builtin commands */
71 char *optionarg;		/* set by nextopt (like getopt) */
72 char *optptr;			/* used by nextopt */
73 
74 char *minusc;			/* argument to -c option */
75 
76 
77 STATIC void options(int);
78 STATIC void minus_o(char *, int);
79 STATIC void setoption(int, int);
80 STATIC int getopts(char *, char *, char **, char ***, char **);
81 
82 
83 /*
84  * Process the shell command line arguments.
85  */
86 
87 void
88 procargs(int argc, char **argv)
89 {
90 	size_t i;
91 
92 	argptr = argv;
93 	if (argc > 0)
94 		argptr++;
95 	for (i = 0; i < NOPTS; i++)
96 		optlist[i].val = 2;
97 	options(1);
98 	if (*argptr == NULL && minusc == NULL)
99 		sflag = 1;
100 	if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
101 		iflag = 1;
102 	if (iflag == 1 && sflag == 2)
103 		iflag = 2;
104 	if (mflag == 2)
105 		mflag = iflag;
106 	for (i = 0; i < NOPTS; i++)
107 		if (optlist[i].val == 2)
108 			optlist[i].val = 0;
109 #if DEBUG == 2
110 	debug = 1;
111 #endif
112 	arg0 = argv[0];
113 	if (sflag == 0 && minusc == NULL) {
114 		commandname = argv[0];
115 		arg0 = *argptr++;
116 		setinputfile(arg0, 0);
117 		commandname = arg0;
118 	}
119 	/* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
120 	if (minusc != NULL) {
121 		if (argptr == NULL || *argptr == NULL)
122 			error("Bad -c option");
123 		minusc = *argptr++;
124 		if (*argptr != 0)
125 			arg0 = *argptr++;
126 	}
127 
128 	shellparam.p = argptr;
129 	shellparam.reset = 1;
130 	/* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
131 	while (*argptr) {
132 		shellparam.nparam++;
133 		argptr++;
134 	}
135 	optschanged();
136 }
137 
138 
139 void
140 optschanged(void)
141 {
142 	setinteractive(iflag);
143 #ifndef SMALL
144 	histedit();
145 #endif
146 	setjobctl(mflag);
147 }
148 
149 /*
150  * Process shell options.  The global variable argptr contains a pointer
151  * to the argument list; we advance it past the options.
152  */
153 
154 STATIC void
155 options(int cmdline)
156 {
157 	static char empty[] = "";
158 	char *p;
159 	int val;
160 	int c;
161 
162 	if (cmdline)
163 		minusc = NULL;
164 	while ((p = *argptr) != NULL) {
165 		argptr++;
166 		if ((c = *p++) == '-') {
167 			val = 1;
168                         if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
169                                 if (!cmdline) {
170                                         /* "-" means turn off -x and -v */
171                                         if (p[0] == '\0')
172                                                 xflag = vflag = 0;
173                                         /* "--" means reset params */
174                                         else if (*argptr == NULL)
175 						setparam(argptr);
176                                 }
177 				break;	  /* "-" or  "--" terminates options */
178 			}
179 		} else if (c == '+') {
180 			val = 0;
181 		} else {
182 			argptr--;
183 			break;
184 		}
185 		while ((c = *p++) != '\0') {
186 			if (c == 'c' && cmdline) {
187 				/* command is after shell args*/
188 				minusc = empty;
189 			} else if (c == 'o') {
190 				minus_o(*argptr, val);
191 				if (*argptr)
192 					argptr++;
193 			} else {
194 				setoption(c, val);
195 			}
196 		}
197 	}
198 }
199 
200 static void
201 set_opt_val(size_t i, int val)
202 {
203 	size_t j;
204 	int flag;
205 
206 	if (val && (flag = optlist[i].opt_set)) {
207 		/* some options (eg vi/emacs) are mutually exclusive */
208 		for (j = 0; j < NOPTS; j++)
209 		    if (optlist[j].opt_set == flag)
210 			optlist[j].val = 0;
211 	}
212 	optlist[i].val = val;
213 #ifdef DEBUG
214 	if (&optlist[i].val == &debug)
215 		opentrace();
216 #endif
217 }
218 
219 STATIC void
220 minus_o(char *name, int val)
221 {
222 	size_t i;
223 
224 	if (name == NULL) {
225 		if (val) {
226 			out1str("Current option settings\n");
227 			for (i = 0; i < NOPTS; i++) {
228 				out1fmt("%-16s%s\n", optlist[i].name,
229 					optlist[i].val ? "on" : "off");
230 			}
231 		} else {
232 			out1str("set");
233 			for (i = 0; i < NOPTS; i++) {
234 				out1fmt(" %co %s",
235 					"+-"[optlist[i].val], optlist[i].name);
236 			}
237 			out1str("\n");
238 		}
239 	} else {
240 		for (i = 0; i < NOPTS; i++)
241 			if (equal(name, optlist[i].name)) {
242 				set_opt_val(i, val);
243 				return;
244 			}
245 		error("Illegal option -o %s", name);
246 	}
247 }
248 
249 
250 STATIC void
251 setoption(int flag, int val)
252 {
253 	size_t i;
254 
255 	for (i = 0; i < NOPTS; i++)
256 		if (optlist[i].letter == flag) {
257 			set_opt_val( i, val );
258 			return;
259 		}
260 	error("Illegal option -%c", flag);
261 	/* NOTREACHED */
262 }
263 
264 
265 
266 #ifdef mkinit
267 INCLUDE "options.h"
268 
269 SHELLPROC {
270 	int i;
271 
272 	for (i = 0; optlist[i].name; i++)
273 		optlist[i].val = 0;
274 	optschanged();
275 
276 }
277 #endif
278 
279 
280 /*
281  * Set the shell parameters.
282  */
283 
284 void
285 setparam(char **argv)
286 {
287 	char **newparam;
288 	char **ap;
289 	int nparam;
290 
291 	for (nparam = 0 ; argv[nparam] ; nparam++)
292 		continue;
293 	ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
294 	while (*argv) {
295 		*ap++ = savestr(*argv++);
296 	}
297 	*ap = NULL;
298 	freeparam(&shellparam);
299 	shellparam.malloc = 1;
300 	shellparam.nparam = nparam;
301 	shellparam.p = newparam;
302 	shellparam.optnext = NULL;
303 }
304 
305 
306 /*
307  * Free the list of positional parameters.
308  */
309 
310 void
311 freeparam(volatile struct shparam *param)
312 {
313 	char **ap;
314 
315 	if (param->malloc) {
316 		for (ap = param->p ; *ap ; ap++)
317 			ckfree(*ap);
318 		ckfree(param->p);
319 	}
320 }
321 
322 
323 
324 /*
325  * The shift builtin command.
326  */
327 
328 int
329 shiftcmd(int argc, char **argv)
330 {
331 	int n;
332 	char **ap1, **ap2;
333 
334 	n = 1;
335 	if (argc > 1)
336 		n = number(argv[1]);
337 	if (n > shellparam.nparam)
338 		error("can't shift that many");
339 	INTOFF;
340 	shellparam.nparam -= n;
341 	for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
342 		if (shellparam.malloc)
343 			ckfree(*ap1);
344 	}
345 	ap2 = shellparam.p;
346 	while ((*ap2++ = *ap1++) != NULL);
347 	shellparam.optnext = NULL;
348 	INTON;
349 	return 0;
350 }
351 
352 
353 
354 /*
355  * The set command builtin.
356  */
357 
358 int
359 setcmd(int argc, char **argv)
360 {
361 	if (argc == 1)
362 		return showvars(0, 0, 1);
363 	INTOFF;
364 	options(0);
365 	optschanged();
366 	if (*argptr != NULL) {
367 		setparam(argptr);
368 	}
369 	INTON;
370 	return 0;
371 }
372 
373 
374 void
375 getoptsreset(value)
376 	const char *value;
377 {
378 	if (number(value) == 1) {
379 		shellparam.optnext = NULL;
380 		shellparam.reset = 1;
381 	}
382 }
383 
384 /*
385  * The getopts builtin.  Shellparam.optnext points to the next argument
386  * to be processed.  Shellparam.optptr points to the next character to
387  * be processed in the current argument.  If shellparam.optnext is NULL,
388  * then it's the first time getopts has been called.
389  */
390 
391 int
392 getoptscmd(int argc, char **argv)
393 {
394 	char **optbase;
395 
396 	if (argc < 3)
397 		error("usage: getopts optstring var [arg]");
398 	else if (argc == 3)
399 		optbase = shellparam.p;
400 	else
401 		optbase = &argv[3];
402 
403 	if (shellparam.reset == 1) {
404 		shellparam.optnext = optbase;
405 		shellparam.optptr = NULL;
406 		shellparam.reset = 0;
407 	}
408 
409 	return getopts(argv[1], argv[2], optbase, &shellparam.optnext,
410 		       &shellparam.optptr);
411 }
412 
413 STATIC int
414 getopts(char *optstr, char *optvar, char **optfirst, char ***optnext, char **optpptr)
415 {
416 	char *p, *q;
417 	char c = '?';
418 	int done = 0;
419 	int ind = 0;
420 	int err = 0;
421 	char s[12];
422 
423 	if ((p = *optpptr) == NULL || *p == '\0') {
424 		/* Current word is done, advance */
425 		if (*optnext == NULL)
426 			return 1;
427 		p = **optnext;
428 		if (p == NULL || *p != '-' || *++p == '\0') {
429 atend:
430 			ind = *optnext - optfirst + 1;
431 			*optnext = NULL;
432 			p = NULL;
433 			done = 1;
434 			goto out;
435 		}
436 		(*optnext)++;
437 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
438 			goto atend;
439 	}
440 
441 	c = *p++;
442 	for (q = optstr; *q != c; ) {
443 		if (*q == '\0') {
444 			if (optstr[0] == ':') {
445 				s[0] = c;
446 				s[1] = '\0';
447 				err |= setvarsafe("OPTARG", s, 0);
448 			} else {
449 				outfmt(&errout, "Illegal option -%c\n", c);
450 				(void) unsetvar("OPTARG", 0);
451 			}
452 			c = '?';
453 			goto bad;
454 		}
455 		if (*++q == ':')
456 			q++;
457 	}
458 
459 	if (*++q == ':') {
460 		if (*p == '\0' && (p = **optnext) == NULL) {
461 			if (optstr[0] == ':') {
462 				s[0] = c;
463 				s[1] = '\0';
464 				err |= setvarsafe("OPTARG", s, 0);
465 				c = ':';
466 			} else {
467 				outfmt(&errout, "No arg for -%c option\n", c);
468 				(void) unsetvar("OPTARG", 0);
469 				c = '?';
470 			}
471 			goto bad;
472 		}
473 
474 		if (p == **optnext)
475 			(*optnext)++;
476 		err |= setvarsafe("OPTARG", p, 0);
477 		p = NULL;
478 	} else
479 		err |= setvarsafe("OPTARG", "", 0);
480 	ind = *optnext - optfirst + 1;
481 	goto out;
482 
483 bad:
484 	ind = 1;
485 	*optnext = NULL;
486 	p = NULL;
487 out:
488 	*optpptr = p;
489 	fmtstr(s, sizeof(s), "%d", ind);
490 	err |= setvarsafe("OPTIND", s, VNOFUNC);
491 	s[0] = c;
492 	s[1] = '\0';
493 	err |= setvarsafe(optvar, s, 0);
494 	if (err) {
495 		*optnext = NULL;
496 		*optpptr = NULL;
497 		flushall();
498 		exraise(EXERROR);
499 	}
500 	return done;
501 }
502 
503 /*
504  * XXX - should get rid of.  have all builtins use getopt(3).  the
505  * library getopt must have the BSD extension static variable "optreset"
506  * otherwise it can't be used within the shell safely.
507  *
508  * Standard option processing (a la getopt) for builtin routines.  The
509  * only argument that is passed to nextopt is the option string; the
510  * other arguments are unnecessary.  It return the character, or '\0' on
511  * end of input.
512  */
513 
514 int
515 nextopt(const char *optstring)
516 {
517 	char *p;
518 	const char *q;
519 	char c;
520 
521 	if ((p = optptr) == NULL || *p == '\0') {
522 		p = *argptr;
523 		if (p == NULL || *p != '-' || *++p == '\0')
524 			return '\0';
525 		argptr++;
526 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
527 			return '\0';
528 	}
529 	c = *p++;
530 	for (q = optstring ; *q != c ; ) {
531 		if (*q == '\0')
532 			error("Illegal option -%c", c);
533 		if (*++q == ':')
534 			q++;
535 	}
536 	if (*++q == ':') {
537 		if (*p == '\0' && (p = *argptr++) == NULL)
538 			error("No arg for -%c option", c);
539 		optionarg = p;
540 		p = NULL;
541 	}
542 	optptr = p;
543 	return c;
544 }
545