Home | History | Annotate | Line # | Download | only in sh
options.c revision 1.61
      1 /*	$NetBSD: options.c,v 1.61 2024/10/14 08:27:53 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.61 2024/10/14 08:27:53 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 	arg0 = argv[0];
    126 	if (loginsh == 2 && arg0 != NULL && arg0[0] == '-')
    127 		loginsh = 1;
    128 
    129 	/*
    130 	 * Any options not dealt with as special cases just above,
    131 	 * and which were not set on the command line, are set to
    132 	 * their expected default values (mostly "off")
    133 	 *
    134 	 * then as each option is initialised, save its setting now
    135 	 * as its "default" value for future use ("set -o default").
    136 	 */
    137 	for (i = 0; i < NOPTS; i++) {
    138 		if (optlist[i].val == 2)
    139 			optlist[i].val = optlist[i].dflt;
    140 		optlist[i].dflt = optlist[i].val;
    141 	}
    142 
    143 	if (sflag == 0 && minusc == NULL) {
    144 		commandname = argv[0];
    145 		arg0 = *argptr++;
    146 		setinputfile(arg0, 0);
    147 		commandname = arg0;
    148 	}
    149 	/* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
    150 	if (minusc != NULL) {
    151 		if (argptr == NULL || *argptr == NULL)
    152 			error("Bad -c option");
    153 		minusc = *argptr++;
    154 		if (*argptr != 0)
    155 			arg0 = *argptr++;
    156 	}
    157 
    158 	shellparam.p = argptr;
    159 	shellparam.reset = 1;
    160 	/* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
    161 	while (*argptr) {
    162 		shellparam.nparam++;
    163 		argptr++;
    164 	}
    165 	optschanged();
    166 }
    167 
    168 
    169 void
    170 optschanged(void)
    171 {
    172 	setinteractive(iflag);
    173 #ifndef SMALL
    174 	histedit();
    175 #endif
    176 	setjobctl(mflag);
    177 
    178 	if (privileged && !pflag) {
    179 		setuid(getuid());
    180 		setgid(getgid());
    181 		privileged = 0;
    182 		setvarsafe("PSc", (getuid() == 0 ? "#" : "$"), 0);
    183 	}
    184 }
    185 
    186 /*
    187  * Process shell options.  The global variable argptr contains a pointer
    188  * to the argument list; we advance it past the options.
    189  */
    190 
    191 STATIC void
    192 options(int cmdline)
    193 {
    194 	static char empty[] = "";
    195 	char *p;
    196 	int val;
    197 	int c;
    198 
    199 	if (cmdline)
    200 		minusc = NULL;
    201 	while ((p = *argptr) != NULL) {
    202 		argptr++;
    203 		if ((c = *p++) == '-') {
    204 			val = 1;
    205                         if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
    206                                 if (!cmdline) {
    207                                         /* "-" means turn off -x and -v */
    208                                         if (p[0] == '\0')
    209                                                 xflag = vflag = 0;
    210                                         /* "--" means reset params */
    211                                         else if (*argptr == NULL)
    212 						setparam(argptr);
    213                                 }
    214 				break;	  /* "-" or  "--" terminates options */
    215 			}
    216 		} else if (c == '+') {
    217 			val = 0;
    218 		} else {
    219 			argptr--;
    220 			break;
    221 		}
    222 		while ((c = *p++) != '\0') {
    223 			if (val == 1 && c == 'c' && cmdline) {
    224 				/* command is after shell args*/
    225 				minusc = empty;
    226 			} else if (c == 'o') {
    227 				if (*p != '\0')
    228 					minus_o(p, val + (cmdline ? val : 0));
    229 				else if (*argptr)
    230 					minus_o(*argptr++,
    231 					    val + (cmdline ? val : 0));
    232 				else if (!cmdline)
    233 					minus_o(NULL, val);
    234 				else
    235 					error("arg for %co missing", "+-"[val]);
    236 				break;
    237 #ifdef DEBUG
    238 			} else if (c == 'D') {
    239 				if (*p) {
    240 					set_debug(p, val);
    241 					break;
    242 				} else if (*argptr)
    243 					set_debug(*argptr++, val);
    244 				else
    245 					set_debug("*$", val);
    246 #endif
    247 			} else if (cmdline && c == 'r') {
    248 				out1fmt("NetBSD shell: %s\n", lookupvar("NETBSD_SHELL"));
    249 				sh_exit(0);
    250 			} else {
    251 				setoption(c, val);
    252 			}
    253 		}
    254 	}
    255 }
    256 
    257 static void
    258 set_opt_val(size_t i, int val)
    259 {
    260 	size_t j;
    261 	int flag;
    262 
    263 	if (val && (flag = optlist[i].opt_set)) {
    264 		/* some options (eg vi/emacs) are mutually exclusive */
    265 		for (j = 0; j < NOPTS; j++)
    266 		    if (optlist[j].opt_set == flag)
    267 			optlist[j].val = 0;
    268 	}
    269 #ifndef SMALL
    270 	if (i == _SH_OPT_Xflag)
    271 		xtracefdsetup(val);
    272 #endif
    273 	optlist[i].val = val;
    274 #ifdef DEBUG
    275 	if (&optlist[i].val == &debug)
    276 		opentrace();	/* different "trace" than the -x one... */
    277 #endif
    278 }
    279 
    280 STATIC void
    281 minus_o(char *name, int val)
    282 {
    283 	size_t i;
    284 	const char *sep = ": ";
    285 
    286 	if (name == NULL) {
    287 		if (val) {
    288 			out1str("Current option settings");
    289 			for (i = 0; i < NOPTS; i++) {
    290 				if (optlist[i].name == NULL)  {
    291 					out1fmt("%s%c%c", sep,
    292 					    "+-"[optlist[i].val],
    293 					    optlist[i].letter);
    294 					sep = ", ";
    295 				}
    296 			}
    297 			out1c('\n');
    298 			for (i = 0; i < NOPTS; i++) {
    299 				if (optlist[i].name)
    300 				    out1fmt("%-19s %s\n", optlist[i].name,
    301 					optlist[i].val ? "on" : "off");
    302 			}
    303 		} else {
    304 			out1str("set -o default");
    305 			for (i = 0; i < NOPTS; i++) {
    306 				if (optlist[i].val == optlist[i].dflt)
    307 					continue;
    308 				if (optlist[i].name)
    309 				    out1fmt(" %co %s",
    310 					"+-"[optlist[i].val], optlist[i].name);
    311 				else
    312 				    out1fmt(" %c%c", "+-"[optlist[i].val],
    313 					optlist[i].letter);
    314 			}
    315 			out1c('\n');
    316 		}
    317 	} else {
    318 		if (val == 1 && equal(name, "default")) { /* special case */
    319 			for (i = 0; i < NOPTS; i++)
    320 				set_opt_val(i, optlist[i].dflt);
    321 			return;
    322 		}
    323 		if (val)
    324 			val = 1;
    325 		for (i = 0; i < NOPTS; i++)
    326 			if (optlist[i].name && equal(name, optlist[i].name)) {
    327 				set_opt_val(i, val);
    328 #ifndef SMALL
    329 				if (i == _SH_OPT_Xflag)
    330 					set_opt_val(_SH_OPT_xflag, val);
    331 #endif
    332 				return;
    333 			}
    334 		error("Unknown option %co %s", "+-"[val], name);
    335 	}
    336 }
    337 
    338 
    339 STATIC void
    340 setoption(int flag, int val)
    341 {
    342 	size_t i;
    343 
    344 	for (i = 0; i < NOPTS; i++)
    345 		if (optlist[i].letter == flag) {
    346 			set_opt_val(i, val);
    347 #ifndef SMALL
    348 			if (i == _SH_OPT_Xflag)
    349 				set_opt_val(_SH_OPT_xflag, val);
    350 #endif
    351 			return;
    352 		}
    353 	error("Unknown option %c%c", "+-"[val], flag);
    354 	/* NOTREACHED */
    355 }
    356 
    357 
    358 
    359 #ifdef mkinit
    360 INCLUDE "options.h"
    361 
    362 SHELLPROC {
    363 	int i;
    364 
    365 	for (i = 0; optlist[i].name; i++)
    366 		optlist[i].val = 0;
    367 	optschanged();
    368 
    369 }
    370 #endif
    371 
    372 
    373 /*
    374  * Set the shell parameters.
    375  */
    376 
    377 void
    378 setparam(char **argv)
    379 {
    380 	char **newparam;
    381 	char **ap;
    382 	int nparam;
    383 
    384 	for (nparam = 0 ; argv[nparam] ; nparam++)
    385 		continue;
    386 	ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
    387 	while (*argv) {
    388 		*ap++ = savestr(*argv++);
    389 	}
    390 	*ap = NULL;
    391 	freeparam(&shellparam);
    392 	shellparam.malloc = 1;
    393 	shellparam.nparam = nparam;
    394 	shellparam.p = newparam;
    395 	shellparam.optnext = NULL;
    396 }
    397 
    398 
    399 /*
    400  * Free the list of positional parameters.
    401  */
    402 
    403 void
    404 freeparam(volatile struct shparam *param)
    405 {
    406 	char **ap;
    407 
    408 	if (param->malloc) {
    409 		for (ap = param->p ; *ap ; ap++)
    410 			ckfree(*ap);
    411 		ckfree(param->p);
    412 	}
    413 }
    414 
    415 
    416 
    417 /*
    418  * The shift builtin command.
    419  */
    420 
    421 #ifndef TINY
    422 /* first the rotate variant */
    423 static inline int
    424 rotatecmd(int argc, char **argv)
    425 {
    426 	int n;
    427 	char **ap1, **ap2, **ss;
    428 
    429 	(void) nextopt(NULL);	/* ignore '--' as leading option */
    430 
    431 	/*
    432 	 * half this is just in case it ever becomes
    433 	 * a separate named command, while it remains
    434 	 * puerly an inline inside shift, the compiler
    435 	 * should optimise most of it to nothingness
    436 	 */
    437 	if (argptr[0] && argptr[1])
    438 		error("Usage: rotate [n]");
    439 	n = 1;
    440 	if (*argptr) {
    441 		if (**argptr == '-')
    442 			n = number(*argptr + 1);
    443 		else		/* anti-clockwise n == clockwise $# - n */
    444 			n = shellparam.nparam - number(*argptr);
    445 	}
    446 
    447 	if (n == 0 || n == shellparam.nparam)		/* nothing to do */
    448 		return 0;
    449 
    450 	if (n < 0 || n > shellparam.nparam)
    451 		error("can't rotate that many");
    452 
    453 	ap2 = ss = (char **)stalloc(n * sizeof(char *));
    454 	INTOFF;
    455 	for (ap1 = shellparam.p + shellparam.nparam - n;
    456 	     ap1 < shellparam.p + shellparam.nparam; )
    457 		*ap2++ = *ap1++;
    458 	for (ap2 = shellparam.p + shellparam.nparam, ap1 = ap2 - n;
    459 	     ap1 > shellparam.p; )
    460 		*--ap2 = *--ap1;
    461 	for (ap1 = ss + n; ap1 > ss; )
    462 		*--ap2 = *--ap1;
    463 	shellparam.optnext = NULL;
    464 	INTON;
    465 	stunalloc(ss);
    466 
    467 	return 0;
    468 }
    469 #endif
    470 
    471 int
    472 shiftcmd(int argc, char **argv)
    473 {
    474 	int n;
    475 	char **ap1, **ap2;
    476 
    477 	(void) nextopt(NULL);	/* ignore '--' as leading option */
    478 
    479 	if (argptr[0] && argptr[1])
    480 		error("Usage: shift [n]");
    481 
    482 #ifndef TINY
    483 	if (*argptr && **argptr == '-') {
    484 		argptr = argv + 1;	/* reinit nextopt() */
    485 		optptr = NULL;
    486 		return rotatecmd(argc, argv);
    487 	}
    488 #endif
    489 
    490 	n = 1;
    491 	if (*argptr)
    492 		n = number(*argptr);
    493 	if (n > shellparam.nparam)
    494 		error("can't shift that many");
    495 	INTOFF;
    496 	shellparam.nparam -= n;
    497 	for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
    498 		if (shellparam.malloc)
    499 			ckfree(*ap1);
    500 	}
    501 	ap2 = shellparam.p;
    502 	while ((*ap2++ = *ap1++) != NULL)
    503 		continue;
    504 	shellparam.optnext = NULL;
    505 	INTON;
    506 	return 0;
    507 }
    508 
    509 
    510 
    511 /*
    512  * The set command builtin.
    513  */
    514 
    515 int
    516 setcmd(int argc, char **argv)
    517 {
    518 	if (argc == 1)
    519 		return showvars(0, 0, 1, 0);
    520 	INTOFF;
    521 	options(0);
    522 	optschanged();
    523 	if (*argptr != NULL) {
    524 		setparam(argptr);
    525 	}
    526 	INTON;
    527 	return 0;
    528 }
    529 
    530 
    531 void
    532 getoptsreset(char *value, int flags __unused)
    533 {
    534 	/*
    535 	 * This is just to detect the case where OPTIND=1
    536 	 * is executed.   Any other string assigned to OPTIND
    537 	 * is OK, but is not a reset.   No errors, so cannot use number()
    538 	 */
    539 	if (is_digit(*value) && strtol(value, NULL, 10) == 1) {
    540 		shellparam.optnext = NULL;
    541 		shellparam.reset = 1;
    542 	}
    543 }
    544 
    545 /*
    546  * The getopts builtin.  Shellparam.optnext points to the next argument
    547  * to be processed.  Shellparam.optptr points to the next character to
    548  * be processed in the current argument.  If shellparam.optnext is NULL,
    549  * then it's the first time getopts has been called.
    550  */
    551 
    552 int
    553 getoptscmd(int argc, char **argv)
    554 {
    555 	char **optbase;
    556 
    557 	if (argc < 3)
    558 		error("usage: getopts optstring var [arg]");
    559 	else if (argc == 3)
    560 		optbase = shellparam.p;
    561 	else
    562 		optbase = &argv[3];
    563 
    564 	if (shellparam.reset == 1) {
    565 		shellparam.optnext = optbase;
    566 		shellparam.optptr = NULL;
    567 		shellparam.reset = 0;
    568 	}
    569 
    570 	return getopts(argv[1], argv[2], optbase, &shellparam.optnext,
    571 		       &shellparam.optptr);
    572 }
    573 
    574 STATIC int
    575 getopts(char *optstr, char *optvar, char **optfirst, char ***optnext, char **optpptr)
    576 {
    577 	char *p, *q;
    578 	char c = '?';
    579 	int done = 0;
    580 	int ind = 0;
    581 	int err = 0;
    582 	char s[12];
    583 
    584 	if ((p = *optpptr) == NULL || *p == '\0') {
    585 		/* Current word is done, advance */
    586 		if (*optnext == NULL)
    587 			return 1;
    588 		p = **optnext;
    589 		if (p == NULL || *p != '-' || *++p == '\0') {
    590 atend:
    591 			ind = *optnext - optfirst + 1;
    592 			*optnext = NULL;
    593 			p = NULL;
    594 			done = 1;
    595 			goto out;
    596 		}
    597 		(*optnext)++;
    598 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
    599 			goto atend;
    600 	}
    601 
    602 	c = *p++;
    603 	for (q = optstr; *q != c; ) {
    604 		if (*q == '\0') {
    605 			if (optstr[0] == ':') {
    606 				s[0] = c;
    607 				s[1] = '\0';
    608 				err |= setvarsafe("OPTARG", s, 0);
    609 			} else {
    610 				outfmt(&errout, "Unknown option -%c\n", c);
    611 				(void) unsetvar("OPTARG", 0);
    612 			}
    613 			c = '?';
    614 			goto bad;
    615 		}
    616 		if (*++q == ':')
    617 			q++;
    618 	}
    619 
    620 	if (*++q == ':') {
    621 		if (*p == '\0' && (p = **optnext) == NULL) {
    622 			if (optstr[0] == ':') {
    623 				s[0] = c;
    624 				s[1] = '\0';
    625 				err |= setvarsafe("OPTARG", s, 0);
    626 				c = ':';
    627 			} else {
    628 				outfmt(&errout, "No arg for -%c option\n", c);
    629 				(void) unsetvar("OPTARG", 0);
    630 				c = '?';
    631 			}
    632 			goto bad;
    633 		}
    634 
    635 		if (p == **optnext)
    636 			(*optnext)++;
    637 		err |= setvarsafe("OPTARG", p, 0);
    638 		p = NULL;
    639 	} else
    640 		err |= setvarsafe("OPTARG", "", 0);
    641 	ind = *optnext - optfirst + 1;
    642 	goto out;
    643 
    644 bad:
    645 	ind = 1;
    646 	*optnext = NULL;
    647 	p = NULL;
    648 out:
    649 	*optpptr = p;
    650 	fmtstr(s, sizeof(s), "%d", ind);
    651 	err |= setvarsafe("OPTIND", s, VNOFUNC);
    652 	s[0] = c;
    653 	s[1] = '\0';
    654 	err |= setvarsafe(optvar, s, 0);
    655 	if (err) {
    656 		*optnext = NULL;
    657 		*optpptr = NULL;
    658 		flushall();
    659 		exraise(EXERROR);
    660 	}
    661 	return done;
    662 }
    663 
    664 /*
    665  * XXX - should get rid of.  have all builtins use getopt(3).  the
    666  * library getopt must have the BSD extension static variable "optreset"
    667  * otherwise it can't be used within the shell safely.
    668  *
    669  * Standard option processing (a la getopt) for builtin routines.  The
    670  * only argument that is passed to nextopt is the option string; the
    671  * other arguments are unnecessary.  It return the character, or '\0' on
    672  * end of input.  If optstring is NULL, then there are no options, and
    673  * args are allowed to begin with '-', but a single leading "--" will be
    674  * discarded.   This is for some POSIX special builtins that require
    675  * -- processing, have no args, and we never did opt processing before
    676  * and need to retain backwards compat.
    677  */
    678 
    679 int
    680 nextopt(const char *optstring)
    681 {
    682 	char *p;
    683 	const char *q;
    684 	char c;
    685 
    686 	if ((p = optptr) == NULL || *p == '\0') {
    687 		p = *argptr;
    688 		if (p == NULL || *p != '-' || *++p == '\0')
    689 			return '\0';
    690 		argptr++;
    691 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
    692 			return '\0';
    693 		if (optstring == NULL)	/* not processing the "option" */
    694 			argptr--;	/* so make it be an arg again */
    695 	}
    696 	if (optstring == NULL)
    697 		return '\0';
    698 	c = *p++;
    699 	for (q = optstring ; *q != c ; ) {
    700 		if (*q == '\0')
    701 			error("Unknown option -%c", c);
    702 		if (*++q == ':')
    703 			q++;
    704 	}
    705 	if (*++q == ':') {
    706 		if (*p == '\0' && (p = *argptr++) == NULL)
    707 			error("No arg for -%c option", c);
    708 		optionarg = p;
    709 		p = NULL;
    710 	}
    711 	optptr = p;
    712 	return c;
    713 }
    714