xref: /netbsd-src/bin/sh/options.c (revision d909946ca08dceb44d7d0f22ec9488679695d976)
1 /*	$NetBSD: options.c,v 1.46 2016/03/31 16:16:35 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.46 2016/03/31 16:16:35 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 #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 			} else {
198 				setoption(c, val);
199 			}
200 		}
201 	}
202 }
203 
204 static void
205 set_opt_val(size_t i, int val)
206 {
207 	size_t j;
208 	int flag;
209 
210 	if (val && (flag = optlist[i].opt_set)) {
211 		/* some options (eg vi/emacs) are mutually exclusive */
212 		for (j = 0; j < NOPTS; j++)
213 		    if (optlist[j].opt_set == flag)
214 			optlist[j].val = 0;
215 	}
216 	optlist[i].val = val;
217 #ifdef DEBUG
218 	if (&optlist[i].val == &debug)
219 		opentrace();
220 #endif
221 }
222 
223 STATIC void
224 minus_o(char *name, int val)
225 {
226 	size_t i;
227 	const char *sep = ": ";
228 
229 	if (name == NULL) {
230 		if (val) {
231 			out1str("Current option settings");
232 			for (i = 0; i < NOPTS; i++) {
233 				if (optlist[i].name == NULL)  {
234 					out1fmt("%s%c%c", sep,
235 					    "+-"[optlist[i].val],
236 					    optlist[i].letter);
237 					sep = ", ";
238 				}
239 			}
240 			out1c('\n');
241 			for (i = 0; i < NOPTS; i++) {
242 				if (optlist[i].name)
243 				    out1fmt("%-16s%s\n", optlist[i].name,
244 					optlist[i].val ? "on" : "off");
245 			}
246 		} else {
247 			out1str("set");
248 			for (i = 0; i < NOPTS; i++) {
249 				if (optlist[i].name)
250 				    out1fmt(" %co %s",
251 					"+-"[optlist[i].val], optlist[i].name);
252 				else
253 				    out1fmt(" %c%c", "+-"[optlist[i].val],
254 					optlist[i].letter);
255 			}
256 			out1c('\n');
257 		}
258 	} else {
259 		for (i = 0; i < NOPTS; i++)
260 			if (optlist[i].name && equal(name, optlist[i].name)) {
261 				set_opt_val(i, val);
262 				return;
263 			}
264 		error("Illegal option -o %s", name);
265 	}
266 }
267 
268 
269 STATIC void
270 setoption(int flag, int val)
271 {
272 	size_t i;
273 
274 	for (i = 0; i < NOPTS; i++)
275 		if (optlist[i].letter == flag) {
276 			set_opt_val( i, val );
277 			return;
278 		}
279 	error("Illegal option -%c", flag);
280 	/* NOTREACHED */
281 }
282 
283 
284 
285 #ifdef mkinit
286 INCLUDE "options.h"
287 
288 SHELLPROC {
289 	int i;
290 
291 	for (i = 0; optlist[i].name; i++)
292 		optlist[i].val = 0;
293 	optschanged();
294 
295 }
296 #endif
297 
298 
299 /*
300  * Set the shell parameters.
301  */
302 
303 void
304 setparam(char **argv)
305 {
306 	char **newparam;
307 	char **ap;
308 	int nparam;
309 
310 	for (nparam = 0 ; argv[nparam] ; nparam++)
311 		continue;
312 	ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
313 	while (*argv) {
314 		*ap++ = savestr(*argv++);
315 	}
316 	*ap = NULL;
317 	freeparam(&shellparam);
318 	shellparam.malloc = 1;
319 	shellparam.nparam = nparam;
320 	shellparam.p = newparam;
321 	shellparam.optnext = NULL;
322 }
323 
324 
325 /*
326  * Free the list of positional parameters.
327  */
328 
329 void
330 freeparam(volatile struct shparam *param)
331 {
332 	char **ap;
333 
334 	if (param->malloc) {
335 		for (ap = param->p ; *ap ; ap++)
336 			ckfree(*ap);
337 		ckfree(param->p);
338 	}
339 }
340 
341 
342 
343 /*
344  * The shift builtin command.
345  */
346 
347 int
348 shiftcmd(int argc, char **argv)
349 {
350 	int n;
351 	char **ap1, **ap2;
352 
353 	if (argc > 2)
354 		error("Usage: shift [n]");
355 	n = 1;
356 	if (argc > 1)
357 		n = number(argv[1]);
358 	if (n > shellparam.nparam)
359 		error("can't shift that many");
360 	INTOFF;
361 	shellparam.nparam -= n;
362 	for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
363 		if (shellparam.malloc)
364 			ckfree(*ap1);
365 	}
366 	ap2 = shellparam.p;
367 	while ((*ap2++ = *ap1++) != NULL)
368 		continue;
369 	shellparam.optnext = NULL;
370 	INTON;
371 	return 0;
372 }
373 
374 
375 
376 /*
377  * The set command builtin.
378  */
379 
380 int
381 setcmd(int argc, char **argv)
382 {
383 	if (argc == 1)
384 		return showvars(0, 0, 1, 0);
385 	INTOFF;
386 	options(0);
387 	optschanged();
388 	if (*argptr != NULL) {
389 		setparam(argptr);
390 	}
391 	INTON;
392 	return 0;
393 }
394 
395 
396 void
397 getoptsreset(const char *value)
398 {
399 	if (number(value) == 1) {
400 		shellparam.optnext = NULL;
401 		shellparam.reset = 1;
402 	}
403 }
404 
405 /*
406  * The getopts builtin.  Shellparam.optnext points to the next argument
407  * to be processed.  Shellparam.optptr points to the next character to
408  * be processed in the current argument.  If shellparam.optnext is NULL,
409  * then it's the first time getopts has been called.
410  */
411 
412 int
413 getoptscmd(int argc, char **argv)
414 {
415 	char **optbase;
416 
417 	if (argc < 3)
418 		error("usage: getopts optstring var [arg]");
419 	else if (argc == 3)
420 		optbase = shellparam.p;
421 	else
422 		optbase = &argv[3];
423 
424 	if (shellparam.reset == 1) {
425 		shellparam.optnext = optbase;
426 		shellparam.optptr = NULL;
427 		shellparam.reset = 0;
428 	}
429 
430 	return getopts(argv[1], argv[2], optbase, &shellparam.optnext,
431 		       &shellparam.optptr);
432 }
433 
434 STATIC int
435 getopts(char *optstr, char *optvar, char **optfirst, char ***optnext, char **optpptr)
436 {
437 	char *p, *q;
438 	char c = '?';
439 	int done = 0;
440 	int ind = 0;
441 	int err = 0;
442 	char s[12];
443 
444 	if ((p = *optpptr) == NULL || *p == '\0') {
445 		/* Current word is done, advance */
446 		if (*optnext == NULL)
447 			return 1;
448 		p = **optnext;
449 		if (p == NULL || *p != '-' || *++p == '\0') {
450 atend:
451 			ind = *optnext - optfirst + 1;
452 			*optnext = NULL;
453 			p = NULL;
454 			done = 1;
455 			goto out;
456 		}
457 		(*optnext)++;
458 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
459 			goto atend;
460 	}
461 
462 	c = *p++;
463 	for (q = optstr; *q != c; ) {
464 		if (*q == '\0') {
465 			if (optstr[0] == ':') {
466 				s[0] = c;
467 				s[1] = '\0';
468 				err |= setvarsafe("OPTARG", s, 0);
469 			} else {
470 				outfmt(&errout, "Illegal option -%c\n", c);
471 				(void) unsetvar("OPTARG", 0);
472 			}
473 			c = '?';
474 			goto bad;
475 		}
476 		if (*++q == ':')
477 			q++;
478 	}
479 
480 	if (*++q == ':') {
481 		if (*p == '\0' && (p = **optnext) == NULL) {
482 			if (optstr[0] == ':') {
483 				s[0] = c;
484 				s[1] = '\0';
485 				err |= setvarsafe("OPTARG", s, 0);
486 				c = ':';
487 			} else {
488 				outfmt(&errout, "No arg for -%c option\n", c);
489 				(void) unsetvar("OPTARG", 0);
490 				c = '?';
491 			}
492 			goto bad;
493 		}
494 
495 		if (p == **optnext)
496 			(*optnext)++;
497 		err |= setvarsafe("OPTARG", p, 0);
498 		p = NULL;
499 	} else
500 		err |= setvarsafe("OPTARG", "", 0);
501 	ind = *optnext - optfirst + 1;
502 	goto out;
503 
504 bad:
505 	ind = 1;
506 	*optnext = NULL;
507 	p = NULL;
508 out:
509 	*optpptr = p;
510 	fmtstr(s, sizeof(s), "%d", ind);
511 	err |= setvarsafe("OPTIND", s, VNOFUNC);
512 	s[0] = c;
513 	s[1] = '\0';
514 	err |= setvarsafe(optvar, s, 0);
515 	if (err) {
516 		*optnext = NULL;
517 		*optpptr = NULL;
518 		flushall();
519 		exraise(EXERROR);
520 	}
521 	return done;
522 }
523 
524 /*
525  * XXX - should get rid of.  have all builtins use getopt(3).  the
526  * library getopt must have the BSD extension static variable "optreset"
527  * otherwise it can't be used within the shell safely.
528  *
529  * Standard option processing (a la getopt) for builtin routines.  The
530  * only argument that is passed to nextopt is the option string; the
531  * other arguments are unnecessary.  It return the character, or '\0' on
532  * end of input.
533  */
534 
535 int
536 nextopt(const char *optstring)
537 {
538 	char *p;
539 	const char *q;
540 	char c;
541 
542 	if ((p = optptr) == NULL || *p == '\0') {
543 		p = *argptr;
544 		if (p == NULL || *p != '-' || *++p == '\0')
545 			return '\0';
546 		argptr++;
547 		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
548 			return '\0';
549 	}
550 	c = *p++;
551 	for (q = optstring ; *q != c ; ) {
552 		if (*q == '\0')
553 			error("Illegal option -%c", c);
554 		if (*++q == ':')
555 			q++;
556 	}
557 	if (*++q == ':') {
558 		if (*p == '\0' && (p = *argptr++) == NULL)
559 			error("No arg for -%c option", c);
560 		optionarg = p;
561 		p = NULL;
562 	}
563 	optptr = p;
564 	return c;
565 }
566