xref: /netbsd-src/bin/sh/options.c (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1 /*	$NetBSD: options.c,v 1.55 2020/02/05 14:56:25 kre 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.55 2020/02/05 14:56:25 kre 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 #include "syntax.h"
64 #ifndef SMALL
65 #include "myhistedit.h"
66 #endif
67 #include "show.h"
68 
69 char *arg0;			/* value of $0 */
70 struct shparam shellparam;	/* current positional parameters */
71 char **argptr;			/* argument list for builtin commands */
72 char *optionarg;		/* set by nextopt (like getopt) */
73 char *optptr;			/* used by nextopt */
74 
75 char *minusc;			/* argument to -c option */
76 
77 
78 STATIC void options(int);
79 STATIC void minus_o(char *, int);
80 STATIC void setoption(int, int);
81 STATIC int getopts(char *, char *, char **, char ***, char **);
82 
83 
84 /*
85  * Process the shell command line arguments.
86  */
87 
88 void
89 procargs(int argc, char **argv)
90 {
91 	size_t i;
92 	int psx;
93 
94 	argptr = argv;
95 	if (argc > 0)
96 		argptr++;
97 
98 	psx = posix;		/* save what we set it to earlier */
99 	/*
100 	 * option values are mostly boolean 0:off 1:on
101 	 * we use 2 (just in this routine) to mean "unknown yet"
102 	 */
103 	for (i = 0; i < NOPTS; i++)
104 		optlist[i].val = 2;
105 	posix = psx;		/* restore before processing -o ... */
106 
107 	options(1);
108 
109 	if (*argptr == NULL && minusc == NULL)
110 		sflag = 1;
111 	if (iflag == 2 && sflag == 1 && isatty(0) && isatty(2))
112 		iflag = 1;
113 	if (iflag == 1 && sflag == 2)
114 		iflag = 2;
115 	if (mflag == 2)
116 		mflag = iflag;
117 #ifndef DO_SHAREDVFORK
118 	if (usefork == 2)
119 		usefork = 1;
120 #endif
121 #if DEBUG >= 2
122 	if (debug == 2)
123 		debug = 1;
124 #endif
125 	/*
126 	 * Any options not dealt with as special cases just above,
127 	 * and which were not set on the command line, are set to
128 	 * their expected default values (mostly "off")
129 	 *
130 	 * then as each option is initialised, save its setting now
131 	 * as its "default" value for future use ("set -o default").
132 	 */
133 	for (i = 0; i < NOPTS; i++) {
134 		if (optlist[i].val == 2)
135 			optlist[i].val = optlist[i].dflt;
136 		optlist[i].dflt = optlist[i].val;
137 	}
138 
139 	arg0 = argv[0];
140 	if (sflag == 0 && minusc == NULL) {
141 		commandname = argv[0];
142 		arg0 = *argptr++;
143 		setinputfile(arg0, 0);
144 		commandname = arg0;
145 	}
146 	/* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
147 	if (minusc != NULL) {
148 		if (argptr == NULL || *argptr == NULL)
149 			error("Bad -c option");
150 		minusc = *argptr++;
151 		if (*argptr != 0)
152 			arg0 = *argptr++;
153 	}
154 
155 	shellparam.p = argptr;
156 	shellparam.reset = 1;
157 	/* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
158 	while (*argptr) {
159 		shellparam.nparam++;
160 		argptr++;
161 	}
162 	optschanged();
163 }
164 
165 
166 void
167 optschanged(void)
168 {
169 	setinteractive(iflag);
170 #ifndef SMALL
171 	histedit();
172 #endif
173 	setjobctl(mflag);
174 }
175 
176 /*
177  * Process shell options.  The global variable argptr contains a pointer
178  * to the argument list; we advance it past the options.
179  */
180 
181 STATIC void
182 options(int cmdline)
183 {
184 	static char empty[] = "";
185 	char *p;
186 	int val;
187 	int c;
188 
189 	if (cmdline)
190 		minusc = NULL;
191 	while ((p = *argptr) != NULL) {
192 		argptr++;
193 		if ((c = *p++) == '-') {
194 			val = 1;
195                         if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
196                                 if (!cmdline) {
197                                         /* "-" means turn off -x and -v */
198                                         if (p[0] == '\0')
199                                                 xflag = vflag = 0;
200                                         /* "--" means reset params */
201                                         else if (*argptr == NULL)
202 						setparam(argptr);
203                                 }
204 				break;	  /* "-" or  "--" terminates options */
205 			}
206 		} else if (c == '+') {
207 			val = 0;
208 		} else {
209 			argptr--;
210 			break;
211 		}
212 		while ((c = *p++) != '\0') {
213 			if (val == 1 && c == 'c' && cmdline) {
214 				/* command is after shell args*/
215 				minusc = empty;
216 			} else if (c == 'o') {
217 				if (*p != '\0')
218 					minus_o(p, val + (cmdline ? val : 0));
219 				else if (*argptr)
220 					minus_o(*argptr++,
221 					    val + (cmdline ? val : 0));
222 				else if (!cmdline)
223 					minus_o(NULL, val);
224 				else
225 					error("arg for %co missing", "+-"[val]);
226 				break;
227 #ifdef DEBUG
228 			} else if (c == 'D') {
229 				if (*p) {
230 					set_debug(p, val);
231 					break;
232 				} else if (*argptr)
233 					set_debug(*argptr++, val);
234 				else
235 					set_debug("*$", val);
236 #endif
237 			} else {
238 				setoption(c, val);
239 			}
240 		}
241 	}
242 }
243 
244 static void
245 set_opt_val(size_t i, int val)
246 {
247 	size_t j;
248 	int flag;
249 
250 	if (val && (flag = optlist[i].opt_set)) {
251 		/* some options (eg vi/emacs) are mutually exclusive */
252 		for (j = 0; j < NOPTS; j++)
253 		    if (optlist[j].opt_set == flag)
254 			optlist[j].val = 0;
255 	}
256 #ifndef SMALL
257 	if (i == _SH_OPT_Xflag)
258 		xtracefdsetup(val);
259 #endif
260 	optlist[i].val = val;
261 #ifdef DEBUG
262 	if (&optlist[i].val == &debug)
263 		opentrace();	/* different "trace" than the -x one... */
264 #endif
265 }
266 
267 STATIC void
268 minus_o(char *name, int val)
269 {
270 	size_t i;
271 	const char *sep = ": ";
272 
273 	if (name == NULL) {
274 		if (val) {
275 			out1str("Current option settings");
276 			for (i = 0; i < NOPTS; i++) {
277 				if (optlist[i].name == NULL)  {
278 					out1fmt("%s%c%c", sep,
279 					    "+-"[optlist[i].val],
280 					    optlist[i].letter);
281 					sep = ", ";
282 				}
283 			}
284 			out1c('\n');
285 			for (i = 0; i < NOPTS; i++) {
286 				if (optlist[i].name)
287 				    out1fmt("%-19s %s\n", optlist[i].name,
288 					optlist[i].val ? "on" : "off");
289 			}
290 		} else {
291 			out1str("set -o default");
292 			for (i = 0; i < NOPTS; i++) {
293 				if (optlist[i].val == optlist[i].dflt)
294 					continue;
295 				if (optlist[i].name)
296 				    out1fmt(" %co %s",
297 					"+-"[optlist[i].val], optlist[i].name);
298 				else
299 				    out1fmt(" %c%c", "+-"[optlist[i].val],
300 					optlist[i].letter);
301 			}
302 			out1c('\n');
303 		}
304 	} else {
305 		if (val == 1 && equal(name, "default")) { /* special case */
306 			for (i = 0; i < NOPTS; i++)
307 				set_opt_val(i, optlist[i].dflt);
308 			return;
309 		}
310 		if (val)
311 			val = 1;
312 		for (i = 0; i < NOPTS; i++)
313 			if (optlist[i].name && equal(name, optlist[i].name)) {
314 				set_opt_val(i, val);
315 #ifndef SMALL
316 				if (i == _SH_OPT_Xflag)
317 					set_opt_val(_SH_OPT_xflag, val);
318 #endif
319 				return;
320 			}
321 		error("Illegal option %co %s", "+-"[val], name);
322 	}
323 }
324 
325 
326 STATIC void
327 setoption(int flag, int val)
328 {
329 	size_t i;
330 
331 	for (i = 0; i < NOPTS; i++)
332 		if (optlist[i].letter == flag) {
333 			set_opt_val(i, val);
334 #ifndef SMALL
335 			if (i == _SH_OPT_Xflag)
336 				set_opt_val(_SH_OPT_xflag, val);
337 #endif
338 			return;
339 		}
340 	error("Illegal option %c%c", "+-"[val], flag);
341 	/* NOTREACHED */
342 }
343 
344 
345 
346 #ifdef mkinit
347 INCLUDE "options.h"
348 
349 SHELLPROC {
350 	int i;
351 
352 	for (i = 0; optlist[i].name; i++)
353 		optlist[i].val = 0;
354 	optschanged();
355 
356 }
357 #endif
358 
359 
360 /*
361  * Set the shell parameters.
362  */
363 
364 void
365 setparam(char **argv)
366 {
367 	char **newparam;
368 	char **ap;
369 	int nparam;
370 
371 	for (nparam = 0 ; argv[nparam] ; nparam++)
372 		continue;
373 	ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
374 	while (*argv) {
375 		*ap++ = savestr(*argv++);
376 	}
377 	*ap = NULL;
378 	freeparam(&shellparam);
379 	shellparam.malloc = 1;
380 	shellparam.nparam = nparam;
381 	shellparam.p = newparam;
382 	shellparam.optnext = NULL;
383 }
384 
385 
386 /*
387  * Free the list of positional parameters.
388  */
389 
390 void
391 freeparam(volatile struct shparam *param)
392 {
393 	char **ap;
394 
395 	if (param->malloc) {
396 		for (ap = param->p ; *ap ; ap++)
397 			ckfree(*ap);
398 		ckfree(param->p);
399 	}
400 }
401 
402 
403 
404 /*
405  * The shift builtin command.
406  */
407 
408 int
409 shiftcmd(int argc, char **argv)
410 {
411 	int n;
412 	char **ap1, **ap2;
413 
414 	if (argc > 2)
415 		error("Usage: shift [n]");
416 	n = 1;
417 	if (argc > 1)
418 		n = number(argv[1]);
419 	if (n > shellparam.nparam)
420 		error("can't shift that many");
421 	INTOFF;
422 	shellparam.nparam -= n;
423 	for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
424 		if (shellparam.malloc)
425 			ckfree(*ap1);
426 	}
427 	ap2 = shellparam.p;
428 	while ((*ap2++ = *ap1++) != NULL)
429 		continue;
430 	shellparam.optnext = NULL;
431 	INTON;
432 	return 0;
433 }
434 
435 
436 
437 /*
438  * The set command builtin.
439  */
440 
441 int
442 setcmd(int argc, char **argv)
443 {
444 	if (argc == 1)
445 		return showvars(0, 0, 1, 0);
446 	INTOFF;
447 	options(0);
448 	optschanged();
449 	if (*argptr != NULL) {
450 		setparam(argptr);
451 	}
452 	INTON;
453 	return 0;
454 }
455 
456 
457 void
458 getoptsreset(const char *value)
459 {
460 	/*
461 	 * This is just to detect the case where OPTIND=1
462 	 * is executed.   Any other string assigned to OPTIND
463 	 * is OK, but is not a reset.   No errors, so cannot use number()
464 	 */
465 	if (is_digit(*value) && strtol(value, NULL, 10) == 1) {
466 		shellparam.optnext = NULL;
467 		shellparam.reset = 1;
468 	}
469 }
470 
471 /*
472  * The getopts builtin.  Shellparam.optnext points to the next argument
473  * to be processed.  Shellparam.optptr points to the next character to
474  * be processed in the current argument.  If shellparam.optnext is NULL,
475  * then it's the first time getopts has been called.
476  */
477 
478 int
479 getoptscmd(int argc, char **argv)
480 {
481 	char **optbase;
482 
483 	if (argc < 3)
484 		error("usage: getopts optstring var [arg]");
485 	else if (argc == 3)
486 		optbase = shellparam.p;
487 	else
488 		optbase = &argv[3];
489 
490 	if (shellparam.reset == 1) {
491 		shellparam.optnext = optbase;
492 		shellparam.optptr = NULL;
493 		shellparam.reset = 0;
494 	}
495 
496 	return getopts(argv[1], argv[2], optbase, &shellparam.optnext,
497 		       &shellparam.optptr);
498 }
499 
500 STATIC int
501 getopts(char *optstr, char *optvar, char **optfirst, char ***optnext, char **optpptr)
502 {
503 	char *p, *q;
504 	char c = '?';
505 	int done = 0;
506 	int ind = 0;
507 	int err = 0;
508 	char s[12];
509 
510 	if ((p = *optpptr) == NULL || *p == '\0') {
511 		/* Current word is done, advance */
512 		if (*optnext == NULL)
513 			return 1;
514 		p = **optnext;
515 		if (p == NULL || *p != '-' || *++p == '\0') {
516 atend:
517 			ind = *optnext - optfirst + 1;
518 			*optnext = NULL;
519 			p = NULL;
520 			done = 1;
521 			goto out;
522 		}
523 		(*optnext)++;
524 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
525 			goto atend;
526 	}
527 
528 	c = *p++;
529 	for (q = optstr; *q != c; ) {
530 		if (*q == '\0') {
531 			if (optstr[0] == ':') {
532 				s[0] = c;
533 				s[1] = '\0';
534 				err |= setvarsafe("OPTARG", s, 0);
535 			} else {
536 				outfmt(&errout, "Illegal option -%c\n", c);
537 				(void) unsetvar("OPTARG", 0);
538 			}
539 			c = '?';
540 			goto bad;
541 		}
542 		if (*++q == ':')
543 			q++;
544 	}
545 
546 	if (*++q == ':') {
547 		if (*p == '\0' && (p = **optnext) == NULL) {
548 			if (optstr[0] == ':') {
549 				s[0] = c;
550 				s[1] = '\0';
551 				err |= setvarsafe("OPTARG", s, 0);
552 				c = ':';
553 			} else {
554 				outfmt(&errout, "No arg for -%c option\n", c);
555 				(void) unsetvar("OPTARG", 0);
556 				c = '?';
557 			}
558 			goto bad;
559 		}
560 
561 		if (p == **optnext)
562 			(*optnext)++;
563 		err |= setvarsafe("OPTARG", p, 0);
564 		p = NULL;
565 	} else
566 		err |= setvarsafe("OPTARG", "", 0);
567 	ind = *optnext - optfirst + 1;
568 	goto out;
569 
570 bad:
571 	ind = 1;
572 	*optnext = NULL;
573 	p = NULL;
574 out:
575 	*optpptr = p;
576 	fmtstr(s, sizeof(s), "%d", ind);
577 	err |= setvarsafe("OPTIND", s, VNOFUNC);
578 	s[0] = c;
579 	s[1] = '\0';
580 	err |= setvarsafe(optvar, s, 0);
581 	if (err) {
582 		*optnext = NULL;
583 		*optpptr = NULL;
584 		flushall();
585 		exraise(EXERROR);
586 	}
587 	return done;
588 }
589 
590 /*
591  * XXX - should get rid of.  have all builtins use getopt(3).  the
592  * library getopt must have the BSD extension static variable "optreset"
593  * otherwise it can't be used within the shell safely.
594  *
595  * Standard option processing (a la getopt) for builtin routines.  The
596  * only argument that is passed to nextopt is the option string; the
597  * other arguments are unnecessary.  It return the character, or '\0' on
598  * end of input.  If optstring is NULL, then there are no options, and
599  * args are allowed to begin with '-', but a single leading "--" will be
600  * discarded.   This is for some POSIX special builtins that require
601  * -- processing, have no args, and we never did opt processing before
602  * and need to retain backwards compat.
603  */
604 
605 int
606 nextopt(const char *optstring)
607 {
608 	char *p;
609 	const char *q;
610 	char c;
611 
612 	if ((p = optptr) == NULL || *p == '\0') {
613 		p = *argptr;
614 		if (p == NULL || *p != '-' || *++p == '\0')
615 			return '\0';
616 		argptr++;
617 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
618 			return '\0';
619 		if (optstring == NULL)	/* not processing the "option" */
620 			argptr--;	/* so make it be an arg again */
621 	}
622 	if (optstring == NULL)
623 		return '\0';
624 	c = *p++;
625 	for (q = optstring ; *q != c ; ) {
626 		if (*q == '\0')
627 			error("Illegal option -%c", c);
628 		if (*++q == ':')
629 			q++;
630 	}
631 	if (*++q == ':') {
632 		if (*p == '\0' && (p = *argptr++) == NULL)
633 			error("No arg for -%c option", c);
634 		optionarg = p;
635 		p = NULL;
636 	}
637 	optptr = p;
638 	return c;
639 }
640