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