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