xref: /freebsd/bin/sh/eval.c (revision 36daf0495aa68d669ac6abf004940ec1b1e83e42)
1 /*-
2  * Copyright (c) 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)eval.c	8.9 (Berkeley) 6/8/95";
36 #endif
37 #endif /* not lint */
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #include <paths.h>
42 #include <signal.h>
43 #include <stdlib.h>
44 #include <unistd.h>
45 #include <sys/resource.h>
46 #include <sys/wait.h> /* For WIFSIGNALED(status) */
47 #include <errno.h>
48 
49 /*
50  * Evaluate a command.
51  */
52 
53 #include "shell.h"
54 #include "nodes.h"
55 #include "syntax.h"
56 #include "expand.h"
57 #include "parser.h"
58 #include "jobs.h"
59 #include "eval.h"
60 #include "builtins.h"
61 #include "options.h"
62 #include "exec.h"
63 #include "redir.h"
64 #include "input.h"
65 #include "output.h"
66 #include "trap.h"
67 #include "var.h"
68 #include "memalloc.h"
69 #include "error.h"
70 #include "show.h"
71 #include "mystring.h"
72 #ifndef NO_HISTORY
73 #include "myhistedit.h"
74 #endif
75 
76 
77 int evalskip;			/* set if we are skipping commands */
78 static int skipcount;		/* number of levels to skip */
79 MKINIT int loopnest;		/* current loop nesting level */
80 int funcnest;			/* depth of function calls */
81 static int builtin_flags;	/* evalcommand flags for builtins */
82 
83 
84 char *commandname;
85 struct strlist *cmdenviron;
86 int exitstatus;			/* exit status of last command */
87 int oexitstatus;		/* saved exit status */
88 
89 
90 static void evalloop(union node *, int);
91 static void evalfor(union node *, int);
92 static void evalcase(union node *, int);
93 static void evalsubshell(union node *, int);
94 static void evalredir(union node *, int);
95 static void expredir(union node *);
96 static void evalpipe(union node *);
97 static int is_valid_fast_cmdsubst(union node *n);
98 static void evalcommand(union node *, int, struct backcmd *);
99 static void prehash(union node *);
100 
101 
102 /*
103  * Called to reset things after an exception.
104  */
105 
106 #ifdef mkinit
107 INCLUDE "eval.h"
108 
109 RESET {
110 	evalskip = 0;
111 	loopnest = 0;
112 	funcnest = 0;
113 }
114 #endif
115 
116 
117 
118 /*
119  * The eval command.
120  */
121 
122 int
123 evalcmd(int argc, char **argv)
124 {
125         char *p;
126         char *concat;
127         char **ap;
128 
129         if (argc > 1) {
130                 p = argv[1];
131                 if (argc > 2) {
132                         STARTSTACKSTR(concat);
133                         ap = argv + 2;
134                         for (;;) {
135                                 STPUTS(p, concat);
136                                 if ((p = *ap++) == NULL)
137                                         break;
138                                 STPUTC(' ', concat);
139                         }
140                         STPUTC('\0', concat);
141                         p = grabstackstr(concat);
142                 }
143                 evalstring(p, builtin_flags);
144         } else
145                 exitstatus = 0;
146         return exitstatus;
147 }
148 
149 
150 /*
151  * Execute a command or commands contained in a string.
152  */
153 
154 void
155 evalstring(char *s, int flags)
156 {
157 	union node *n;
158 	struct stackmark smark;
159 	int flags_exit;
160 	int any;
161 
162 	flags_exit = flags & EV_EXIT;
163 	flags &= ~EV_EXIT;
164 	any = 0;
165 	setstackmark(&smark);
166 	setinputstring(s, 1);
167 	while ((n = parsecmd(0)) != NEOF) {
168 		if (n != NULL && !nflag) {
169 			if (flags_exit && preadateof())
170 				evaltree(n, flags | EV_EXIT);
171 			else
172 				evaltree(n, flags);
173 			any = 1;
174 		}
175 		popstackmark(&smark);
176 	}
177 	popfile();
178 	popstackmark(&smark);
179 	if (!any)
180 		exitstatus = 0;
181 	if (flags_exit)
182 		exraise(EXEXIT);
183 }
184 
185 
186 /*
187  * Evaluate a parse tree.  The value is left in the global variable
188  * exitstatus.
189  */
190 
191 void
192 evaltree(union node *n, int flags)
193 {
194 	int do_etest;
195 	union node *next;
196 
197 	do_etest = 0;
198 	if (n == NULL) {
199 		TRACE(("evaltree(NULL) called\n"));
200 		exitstatus = 0;
201 		goto out;
202 	}
203 	do {
204 		next = NULL;
205 #ifndef NO_HISTORY
206 		displayhist = 1;	/* show history substitutions done with fc */
207 #endif
208 		TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
209 		switch (n->type) {
210 		case NSEMI:
211 			evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
212 			if (evalskip)
213 				goto out;
214 			next = n->nbinary.ch2;
215 			break;
216 		case NAND:
217 			evaltree(n->nbinary.ch1, EV_TESTED);
218 			if (evalskip || exitstatus != 0) {
219 				goto out;
220 			}
221 			next = n->nbinary.ch2;
222 			break;
223 		case NOR:
224 			evaltree(n->nbinary.ch1, EV_TESTED);
225 			if (evalskip || exitstatus == 0)
226 				goto out;
227 			next = n->nbinary.ch2;
228 			break;
229 		case NREDIR:
230 			evalredir(n, flags);
231 			break;
232 		case NSUBSHELL:
233 			evalsubshell(n, flags);
234 			do_etest = !(flags & EV_TESTED);
235 			break;
236 		case NBACKGND:
237 			evalsubshell(n, flags);
238 			break;
239 		case NIF: {
240 			evaltree(n->nif.test, EV_TESTED);
241 			if (evalskip)
242 				goto out;
243 			if (exitstatus == 0)
244 				next = n->nif.ifpart;
245 			else if (n->nif.elsepart)
246 				next = n->nif.elsepart;
247 			else
248 				exitstatus = 0;
249 			break;
250 		}
251 		case NWHILE:
252 		case NUNTIL:
253 			evalloop(n, flags & ~EV_EXIT);
254 			break;
255 		case NFOR:
256 			evalfor(n, flags & ~EV_EXIT);
257 			break;
258 		case NCASE:
259 			evalcase(n, flags);
260 			break;
261 		case NDEFUN:
262 			defun(n->narg.text, n->narg.next);
263 			exitstatus = 0;
264 			break;
265 		case NNOT:
266 			evaltree(n->nnot.com, EV_TESTED);
267 			exitstatus = !exitstatus;
268 			break;
269 
270 		case NPIPE:
271 			evalpipe(n);
272 			do_etest = !(flags & EV_TESTED);
273 			break;
274 		case NCMD:
275 			evalcommand(n, flags, (struct backcmd *)NULL);
276 			do_etest = !(flags & EV_TESTED);
277 			break;
278 		default:
279 			out1fmt("Node type = %d\n", n->type);
280 			flushout(&output);
281 			break;
282 		}
283 		n = next;
284 	} while (n != NULL);
285 out:
286 	if (pendingsigs)
287 		dotrap();
288 	if (eflag && exitstatus != 0 && do_etest)
289 		exitshell(exitstatus);
290 	if (flags & EV_EXIT)
291 		exraise(EXEXIT);
292 }
293 
294 
295 static void
296 evalloop(union node *n, int flags)
297 {
298 	int status;
299 
300 	loopnest++;
301 	status = 0;
302 	for (;;) {
303 		evaltree(n->nbinary.ch1, EV_TESTED);
304 		if (evalskip) {
305 skipping:	  if (evalskip == SKIPCONT && --skipcount <= 0) {
306 				evalskip = 0;
307 				continue;
308 			}
309 			if (evalskip == SKIPBREAK && --skipcount <= 0)
310 				evalskip = 0;
311 			if (evalskip == SKIPFUNC || evalskip == SKIPFILE)
312 				status = exitstatus;
313 			break;
314 		}
315 		if (n->type == NWHILE) {
316 			if (exitstatus != 0)
317 				break;
318 		} else {
319 			if (exitstatus == 0)
320 				break;
321 		}
322 		evaltree(n->nbinary.ch2, flags);
323 		status = exitstatus;
324 		if (evalskip)
325 			goto skipping;
326 	}
327 	loopnest--;
328 	exitstatus = status;
329 }
330 
331 
332 
333 static void
334 evalfor(union node *n, int flags)
335 {
336 	struct arglist arglist;
337 	union node *argp;
338 	struct strlist *sp;
339 	struct stackmark smark;
340 
341 	setstackmark(&smark);
342 	arglist.lastp = &arglist.list;
343 	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
344 		oexitstatus = exitstatus;
345 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
346 		if (evalskip)
347 			goto out;
348 	}
349 	*arglist.lastp = NULL;
350 
351 	exitstatus = 0;
352 	loopnest++;
353 	for (sp = arglist.list ; sp ; sp = sp->next) {
354 		setvar(n->nfor.var, sp->text, 0);
355 		evaltree(n->nfor.body, flags);
356 		if (evalskip) {
357 			if (evalskip == SKIPCONT && --skipcount <= 0) {
358 				evalskip = 0;
359 				continue;
360 			}
361 			if (evalskip == SKIPBREAK && --skipcount <= 0)
362 				evalskip = 0;
363 			break;
364 		}
365 	}
366 	loopnest--;
367 out:
368 	popstackmark(&smark);
369 }
370 
371 
372 
373 static void
374 evalcase(union node *n, int flags)
375 {
376 	union node *cp;
377 	union node *patp;
378 	struct arglist arglist;
379 	struct stackmark smark;
380 
381 	setstackmark(&smark);
382 	arglist.lastp = &arglist.list;
383 	oexitstatus = exitstatus;
384 	exitstatus = 0;
385 	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
386 	for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
387 		for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
388 			if (casematch(patp, arglist.list->text)) {
389 				while (cp->nclist.next &&
390 				    cp->type == NCLISTFALLTHRU) {
391 					if (evalskip != 0)
392 						break;
393 					evaltree(cp->nclist.body,
394 					    flags & ~EV_EXIT);
395 					cp = cp->nclist.next;
396 				}
397 				if (evalskip == 0) {
398 					evaltree(cp->nclist.body, flags);
399 				}
400 				goto out;
401 			}
402 		}
403 	}
404 out:
405 	popstackmark(&smark);
406 }
407 
408 
409 
410 /*
411  * Kick off a subshell to evaluate a tree.
412  */
413 
414 static void
415 evalsubshell(union node *n, int flags)
416 {
417 	struct job *jp;
418 	int backgnd = (n->type == NBACKGND);
419 
420 	oexitstatus = exitstatus;
421 	expredir(n->nredir.redirect);
422 	if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
423 			forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
424 		if (backgnd)
425 			flags &=~ EV_TESTED;
426 		redirect(n->nredir.redirect, 0);
427 		evaltree(n->nredir.n, flags | EV_EXIT);	/* never returns */
428 	} else if (! backgnd) {
429 		INTOFF;
430 		exitstatus = waitforjob(jp, (int *)NULL);
431 		INTON;
432 	} else
433 		exitstatus = 0;
434 }
435 
436 
437 /*
438  * Evaluate a redirected compound command.
439  */
440 
441 static void
442 evalredir(union node *n, int flags)
443 {
444 	struct jmploc jmploc;
445 	struct jmploc *savehandler;
446 	volatile int in_redirect = 1;
447 
448 	oexitstatus = exitstatus;
449 	expredir(n->nredir.redirect);
450 	savehandler = handler;
451 	if (setjmp(jmploc.loc)) {
452 		int e;
453 
454 		handler = savehandler;
455 		e = exception;
456 		popredir();
457 		if (e == EXERROR || e == EXEXEC) {
458 			if (in_redirect) {
459 				exitstatus = 2;
460 				return;
461 			}
462 		}
463 		longjmp(handler->loc, 1);
464 	} else {
465 		INTOFF;
466 		handler = &jmploc;
467 		redirect(n->nredir.redirect, REDIR_PUSH);
468 		in_redirect = 0;
469 		INTON;
470 		evaltree(n->nredir.n, flags);
471 	}
472 	INTOFF;
473 	handler = savehandler;
474 	popredir();
475 	INTON;
476 }
477 
478 
479 /*
480  * Compute the names of the files in a redirection list.
481  */
482 
483 static void
484 expredir(union node *n)
485 {
486 	union node *redir;
487 
488 	for (redir = n ; redir ; redir = redir->nfile.next) {
489 		struct arglist fn;
490 		fn.lastp = &fn.list;
491 		switch (redir->type) {
492 		case NFROM:
493 		case NTO:
494 		case NFROMTO:
495 		case NAPPEND:
496 		case NCLOBBER:
497 			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
498 			redir->nfile.expfname = fn.list->text;
499 			break;
500 		case NFROMFD:
501 		case NTOFD:
502 			if (redir->ndup.vname) {
503 				expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
504 				fixredir(redir, fn.list->text, 1);
505 			}
506 			break;
507 		}
508 	}
509 }
510 
511 
512 
513 /*
514  * Evaluate a pipeline.  All the processes in the pipeline are children
515  * of the process creating the pipeline.  (This differs from some versions
516  * of the shell, which make the last process in a pipeline the parent
517  * of all the rest.)
518  */
519 
520 static void
521 evalpipe(union node *n)
522 {
523 	struct job *jp;
524 	struct nodelist *lp;
525 	int pipelen;
526 	int prevfd;
527 	int pip[2];
528 
529 	TRACE(("evalpipe(%p) called\n", (void *)n));
530 	pipelen = 0;
531 	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
532 		pipelen++;
533 	INTOFF;
534 	jp = makejob(n, pipelen);
535 	prevfd = -1;
536 	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
537 		prehash(lp->n);
538 		pip[1] = -1;
539 		if (lp->next) {
540 			if (pipe(pip) < 0) {
541 				close(prevfd);
542 				error("Pipe call failed: %s", strerror(errno));
543 			}
544 		}
545 		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
546 			INTON;
547 			if (prevfd > 0) {
548 				dup2(prevfd, 0);
549 				close(prevfd);
550 			}
551 			if (pip[1] >= 0) {
552 				if (!(prevfd >= 0 && pip[0] == 0))
553 					close(pip[0]);
554 				if (pip[1] != 1) {
555 					dup2(pip[1], 1);
556 					close(pip[1]);
557 				}
558 			}
559 			evaltree(lp->n, EV_EXIT);
560 		}
561 		if (prevfd >= 0)
562 			close(prevfd);
563 		prevfd = pip[0];
564 		if (pip[1] != -1)
565 			close(pip[1]);
566 	}
567 	INTON;
568 	if (n->npipe.backgnd == 0) {
569 		INTOFF;
570 		exitstatus = waitforjob(jp, (int *)NULL);
571 		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
572 		INTON;
573 	} else
574 		exitstatus = 0;
575 }
576 
577 
578 
579 static int
580 is_valid_fast_cmdsubst(union node *n)
581 {
582 
583 	return (n->type == NCMD);
584 }
585 
586 /*
587  * Execute a command inside back quotes.  If it's a builtin command, we
588  * want to save its output in a block obtained from malloc.  Otherwise
589  * we fork off a subprocess and get the output of the command via a pipe.
590  * Should be called with interrupts off.
591  */
592 
593 void
594 evalbackcmd(union node *n, struct backcmd *result)
595 {
596 	int pip[2];
597 	struct job *jp;
598 	struct stackmark smark;		/* unnecessary */
599 	struct jmploc jmploc;
600 	struct jmploc *savehandler;
601 	struct localvar *savelocalvars;
602 
603 	setstackmark(&smark);
604 	result->fd = -1;
605 	result->buf = NULL;
606 	result->nleft = 0;
607 	result->jp = NULL;
608 	if (n == NULL) {
609 		exitstatus = 0;
610 		goto out;
611 	}
612 	if (is_valid_fast_cmdsubst(n)) {
613 		exitstatus = oexitstatus;
614 		savelocalvars = localvars;
615 		localvars = NULL;
616 		forcelocal++;
617 		savehandler = handler;
618 		if (setjmp(jmploc.loc)) {
619 			if (exception == EXERROR || exception == EXEXEC)
620 				exitstatus = 2;
621 			else if (exception != 0) {
622 				handler = savehandler;
623 				forcelocal--;
624 				poplocalvars();
625 				localvars = savelocalvars;
626 				longjmp(handler->loc, 1);
627 			}
628 		} else {
629 			handler = &jmploc;
630 			evalcommand(n, EV_BACKCMD, result);
631 		}
632 		handler = savehandler;
633 		forcelocal--;
634 		poplocalvars();
635 		localvars = savelocalvars;
636 	} else {
637 		exitstatus = 0;
638 		if (pipe(pip) < 0)
639 			error("Pipe call failed: %s", strerror(errno));
640 		jp = makejob(n, 1);
641 		if (forkshell(jp, n, FORK_NOJOB) == 0) {
642 			FORCEINTON;
643 			close(pip[0]);
644 			if (pip[1] != 1) {
645 				dup2(pip[1], 1);
646 				close(pip[1]);
647 			}
648 			evaltree(n, EV_EXIT);
649 		}
650 		close(pip[1]);
651 		result->fd = pip[0];
652 		result->jp = jp;
653 	}
654 out:
655 	popstackmark(&smark);
656 	TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
657 		result->fd, result->buf, result->nleft, result->jp));
658 }
659 
660 /*
661  * Check if a builtin can safely be executed in the same process,
662  * even though it should be in a subshell (command substitution).
663  * Note that jobid, jobs, times and trap can show information not
664  * available in a child process; this is deliberate.
665  * The arguments should already have been expanded.
666  */
667 static int
668 safe_builtin(int idx, int argc, char **argv)
669 {
670 	if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD ||
671 	    idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD ||
672 	    idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD ||
673 	    idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD ||
674 	    idx == TYPECMD)
675 		return (1);
676 	if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD ||
677 	    idx == UMASKCMD)
678 		return (argc <= 1 || (argc == 2 && argv[1][0] == '-'));
679 	if (idx == SETCMD)
680 		return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' ||
681 		    argv[1][0] == '+') && argv[1][1] == 'o' &&
682 		    argv[1][2] == '\0'));
683 	return (0);
684 }
685 
686 /*
687  * Execute a simple command.
688  * Note: This may or may not return if (flags & EV_EXIT).
689  */
690 
691 static void
692 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
693 {
694 	struct stackmark smark;
695 	union node *argp;
696 	struct arglist arglist;
697 	struct arglist varlist;
698 	char **argv;
699 	int argc;
700 	char **envp;
701 	int varflag;
702 	struct strlist *sp;
703 	int mode;
704 	int pip[2];
705 	struct cmdentry cmdentry;
706 	struct job *jp;
707 	struct jmploc jmploc;
708 	struct jmploc *savehandler;
709 	char *savecmdname;
710 	struct shparam saveparam;
711 	struct localvar *savelocalvars;
712 	struct parsefile *savetopfile;
713 	volatile int e;
714 	char *lastarg;
715 	int realstatus;
716 	int do_clearcmdentry;
717 	const char *path = pathval();
718 
719 	/* First expand the arguments. */
720 	TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
721 	setstackmark(&smark);
722 	arglist.lastp = &arglist.list;
723 	varlist.lastp = &varlist.list;
724 	varflag = 1;
725 	jp = NULL;
726 	do_clearcmdentry = 0;
727 	oexitstatus = exitstatus;
728 	exitstatus = 0;
729 	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
730 		if (varflag && isassignment(argp->narg.text)) {
731 			expandarg(argp, &varlist, EXP_VARTILDE);
732 			continue;
733 		}
734 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
735 		varflag = 0;
736 	}
737 	*arglist.lastp = NULL;
738 	*varlist.lastp = NULL;
739 	expredir(cmd->ncmd.redirect);
740 	argc = 0;
741 	for (sp = arglist.list ; sp ; sp = sp->next)
742 		argc++;
743 	/* Add one slot at the beginning for tryexec(). */
744 	argv = stalloc(sizeof (char *) * (argc + 2));
745 	argv++;
746 
747 	for (sp = arglist.list ; sp ; sp = sp->next) {
748 		TRACE(("evalcommand arg: %s\n", sp->text));
749 		*argv++ = sp->text;
750 	}
751 	*argv = NULL;
752 	lastarg = NULL;
753 	if (iflag && funcnest == 0 && argc > 0)
754 		lastarg = argv[-1];
755 	argv -= argc;
756 
757 	/* Print the command if xflag is set. */
758 	if (xflag) {
759 		char sep = 0;
760 		const char *p, *ps4;
761 		ps4 = expandstr(ps4val());
762 		out2str(ps4 != NULL ? ps4 : ps4val());
763 		for (sp = varlist.list ; sp ; sp = sp->next) {
764 			if (sep != 0)
765 				out2c(' ');
766 			p = strchr(sp->text, '=');
767 			if (p != NULL) {
768 				p++;
769 				outbin(sp->text, p - sp->text, out2);
770 				out2qstr(p);
771 			} else
772 				out2qstr(sp->text);
773 			sep = ' ';
774 		}
775 		for (sp = arglist.list ; sp ; sp = sp->next) {
776 			if (sep != 0)
777 				out2c(' ');
778 			/* Disambiguate command looking like assignment. */
779 			if (sp == arglist.list &&
780 					strchr(sp->text, '=') != NULL &&
781 					strchr(sp->text, '\'') == NULL) {
782 				out2c('\'');
783 				out2str(sp->text);
784 				out2c('\'');
785 			} else
786 				out2qstr(sp->text);
787 			sep = ' ';
788 		}
789 		out2c('\n');
790 		flushout(&errout);
791 	}
792 
793 	/* Now locate the command. */
794 	if (argc == 0) {
795 		/* Variable assignment(s) without command */
796 		cmdentry.cmdtype = CMDBUILTIN;
797 		cmdentry.u.index = BLTINCMD;
798 		cmdentry.special = 0;
799 	} else {
800 		static const char PATH[] = "PATH=";
801 		int cmd_flags = 0, bltinonly = 0;
802 
803 		/*
804 		 * Modify the command lookup path, if a PATH= assignment
805 		 * is present
806 		 */
807 		for (sp = varlist.list ; sp ; sp = sp->next)
808 			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
809 				path = sp->text + sizeof(PATH) - 1;
810 				/*
811 				 * On `PATH=... command`, we need to make
812 				 * sure that the command isn't using the
813 				 * non-updated hash table of the outer PATH
814 				 * setting and we need to make sure that
815 				 * the hash table isn't filled with items
816 				 * from the temporary setting.
817 				 *
818 				 * It would be better to forbit using and
819 				 * updating the table while this command
820 				 * runs, by the command finding mechanism
821 				 * is heavily integrated with hash handling,
822 				 * so we just delete the hash before and after
823 				 * the command runs. Partly deleting like
824 				 * changepatch() does doesn't seem worth the
825 				 * bookinging effort, since most such runs add
826 				 * directories in front of the new PATH.
827 				 */
828 				clearcmdentry();
829 				do_clearcmdentry = 1;
830 			}
831 
832 		for (;;) {
833 			if (bltinonly) {
834 				cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
835 				if (cmdentry.u.index < 0) {
836 					cmdentry.u.index = BLTINCMD;
837 					argv--;
838 					argc++;
839 					break;
840 				}
841 			} else
842 				find_command(argv[0], &cmdentry, cmd_flags, path);
843 			/* implement the bltin and command builtins here */
844 			if (cmdentry.cmdtype != CMDBUILTIN)
845 				break;
846 			if (cmdentry.u.index == BLTINCMD) {
847 				if (argc == 1)
848 					break;
849 				argv++;
850 				argc--;
851 				bltinonly = 1;
852 			} else if (cmdentry.u.index == COMMANDCMD) {
853 				if (argc == 1)
854 					break;
855 				if (!strcmp(argv[1], "-p")) {
856 					if (argc == 2)
857 						break;
858 					if (argv[2][0] == '-') {
859 						if (strcmp(argv[2], "--"))
860 							break;
861 						if (argc == 3)
862 							break;
863 						argv += 3;
864 						argc -= 3;
865 					} else {
866 						argv += 2;
867 						argc -= 2;
868 					}
869 					path = _PATH_STDPATH;
870 					clearcmdentry();
871 					do_clearcmdentry = 1;
872 				} else if (!strcmp(argv[1], "--")) {
873 					if (argc == 2)
874 						break;
875 					argv += 2;
876 					argc -= 2;
877 				} else if (argv[1][0] == '-')
878 					break;
879 				else {
880 					argv++;
881 					argc--;
882 				}
883 				cmd_flags |= DO_NOFUNC;
884 				bltinonly = 0;
885 			} else
886 				break;
887 		}
888 		/*
889 		 * Special builtins lose their special properties when
890 		 * called via 'command'.
891 		 */
892 		if (cmd_flags & DO_NOFUNC)
893 			cmdentry.special = 0;
894 	}
895 
896 	/* Fork off a child process if necessary. */
897 	if (((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
898 	    && ((flags & EV_EXIT) == 0 || have_traps()))
899 	 || ((flags & EV_BACKCMD) != 0
900 	    && (cmdentry.cmdtype != CMDBUILTIN ||
901 		 !safe_builtin(cmdentry.u.index, argc, argv)))) {
902 		jp = makejob(cmd, 1);
903 		mode = FORK_FG;
904 		if (flags & EV_BACKCMD) {
905 			mode = FORK_NOJOB;
906 			if (pipe(pip) < 0)
907 				error("Pipe call failed: %s", strerror(errno));
908 		}
909 		if (forkshell(jp, cmd, mode) != 0)
910 			goto parent;	/* at end of routine */
911 		if (flags & EV_BACKCMD) {
912 			FORCEINTON;
913 			close(pip[0]);
914 			if (pip[1] != 1) {
915 				dup2(pip[1], 1);
916 				close(pip[1]);
917 			}
918 			flags &= ~EV_BACKCMD;
919 		}
920 		flags |= EV_EXIT;
921 	}
922 
923 	/* This is the child process if a fork occurred. */
924 	/* Execute the command. */
925 	if (cmdentry.cmdtype == CMDFUNCTION) {
926 #ifdef DEBUG
927 		trputs("Shell function:  ");  trargs(argv);
928 #endif
929 		saveparam = shellparam;
930 		shellparam.malloc = 0;
931 		shellparam.reset = 1;
932 		shellparam.nparam = argc - 1;
933 		shellparam.p = argv + 1;
934 		shellparam.optnext = NULL;
935 		INTOFF;
936 		savelocalvars = localvars;
937 		localvars = NULL;
938 		reffunc(cmdentry.u.func);
939 		savehandler = handler;
940 		if (setjmp(jmploc.loc)) {
941 			freeparam(&shellparam);
942 			shellparam = saveparam;
943 			popredir();
944 			unreffunc(cmdentry.u.func);
945 			poplocalvars();
946 			localvars = savelocalvars;
947 			funcnest--;
948 			handler = savehandler;
949 			longjmp(handler->loc, 1);
950 		}
951 		handler = &jmploc;
952 		funcnest++;
953 		redirect(cmd->ncmd.redirect, REDIR_PUSH);
954 		INTON;
955 		for (sp = varlist.list ; sp ; sp = sp->next)
956 			mklocal(sp->text);
957 		exitstatus = oexitstatus;
958 		evaltree(getfuncnode(cmdentry.u.func),
959 		    flags & (EV_TESTED | EV_EXIT));
960 		INTOFF;
961 		unreffunc(cmdentry.u.func);
962 		poplocalvars();
963 		localvars = savelocalvars;
964 		freeparam(&shellparam);
965 		shellparam = saveparam;
966 		handler = savehandler;
967 		funcnest--;
968 		popredir();
969 		INTON;
970 		if (evalskip == SKIPFUNC) {
971 			evalskip = 0;
972 			skipcount = 0;
973 		}
974 		if (jp)
975 			exitshell(exitstatus);
976 	} else if (cmdentry.cmdtype == CMDBUILTIN) {
977 #ifdef DEBUG
978 		trputs("builtin command:  ");  trargs(argv);
979 #endif
980 		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
981 		if (flags == EV_BACKCMD) {
982 			memout.nleft = 0;
983 			memout.nextc = memout.buf;
984 			memout.bufsize = 64;
985 			mode |= REDIR_BACKQ;
986 			cmdentry.special = 0;
987 		}
988 		savecmdname = commandname;
989 		savetopfile = getcurrentfile();
990 		cmdenviron = varlist.list;
991 		e = -1;
992 		savehandler = handler;
993 		if (setjmp(jmploc.loc)) {
994 			e = exception;
995 			if (e == EXINT)
996 				exitstatus = SIGINT+128;
997 			else if (e != EXEXIT)
998 				exitstatus = 2;
999 			goto cmddone;
1000 		}
1001 		handler = &jmploc;
1002 		redirect(cmd->ncmd.redirect, mode);
1003 		/*
1004 		 * If there is no command word, redirection errors should
1005 		 * not be fatal but assignment errors should.
1006 		 */
1007 		if (argc == 0 && !(flags & EV_BACKCMD))
1008 			cmdentry.special = 1;
1009 		listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET);
1010 		if (argc > 0)
1011 			bltinsetlocale();
1012 		commandname = argv[0];
1013 		argptr = argv + 1;
1014 		nextopt_optptr = NULL;		/* initialize nextopt */
1015 		builtin_flags = flags;
1016 		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
1017 		flushall();
1018 cmddone:
1019 		if (argc > 0)
1020 			bltinunsetlocale();
1021 		cmdenviron = NULL;
1022 		out1 = &output;
1023 		out2 = &errout;
1024 		freestdout();
1025 		handler = savehandler;
1026 		commandname = savecmdname;
1027 		if (jp)
1028 			exitshell(exitstatus);
1029 		if (flags == EV_BACKCMD) {
1030 			backcmd->buf = memout.buf;
1031 			backcmd->nleft = memout.nextc - memout.buf;
1032 			memout.buf = NULL;
1033 		}
1034 		if (cmdentry.u.index != EXECCMD)
1035 			popredir();
1036 		if (e != -1) {
1037 			if ((e != EXERROR && e != EXEXEC)
1038 			    || cmdentry.special)
1039 				exraise(e);
1040 			popfilesupto(savetopfile);
1041 			if (flags != EV_BACKCMD)
1042 				FORCEINTON;
1043 		}
1044 	} else {
1045 #ifdef DEBUG
1046 		trputs("normal command:  ");  trargs(argv);
1047 #endif
1048 		redirect(cmd->ncmd.redirect, 0);
1049 		for (sp = varlist.list ; sp ; sp = sp->next)
1050 			setvareq(sp->text, VEXPORT|VSTACK);
1051 		envp = environment();
1052 		shellexec(argv, envp, path, cmdentry.u.index);
1053 		/*NOTREACHED*/
1054 	}
1055 	goto out;
1056 
1057 parent:	/* parent process gets here (if we forked) */
1058 	if (mode == FORK_FG) {	/* argument to fork */
1059 		INTOFF;
1060 		exitstatus = waitforjob(jp, &realstatus);
1061 		INTON;
1062 		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
1063 			evalskip = SKIPBREAK;
1064 			skipcount = loopnest;
1065 		}
1066 	} else if (mode == FORK_NOJOB) {
1067 		backcmd->fd = pip[0];
1068 		close(pip[1]);
1069 		backcmd->jp = jp;
1070 	}
1071 
1072 out:
1073 	if (lastarg)
1074 		setvar("_", lastarg, 0);
1075 	if (do_clearcmdentry)
1076 		clearcmdentry();
1077 	popstackmark(&smark);
1078 }
1079 
1080 
1081 
1082 /*
1083  * Search for a command.  This is called before we fork so that the
1084  * location of the command will be available in the parent as well as
1085  * the child.  The check for "goodname" is an overly conservative
1086  * check that the name will not be subject to expansion.
1087  */
1088 
1089 static void
1090 prehash(union node *n)
1091 {
1092 	struct cmdentry entry;
1093 
1094 	if (n && n->type == NCMD && n->ncmd.args)
1095 		if (goodname(n->ncmd.args->narg.text))
1096 			find_command(n->ncmd.args->narg.text, &entry, 0,
1097 				     pathval());
1098 }
1099 
1100 
1101 
1102 /*
1103  * Builtin commands.  Builtin commands whose functions are closely
1104  * tied to evaluation are implemented here.
1105  */
1106 
1107 /*
1108  * No command given, a bltin command with no arguments, or a bltin command
1109  * with an invalid name.
1110  */
1111 
1112 int
1113 bltincmd(int argc, char **argv)
1114 {
1115 	if (argc > 1) {
1116 		out2fmt_flush("%s: not found\n", argv[1]);
1117 		return 127;
1118 	}
1119 	/*
1120 	 * Preserve exitstatus of a previous possible redirection
1121 	 * as POSIX mandates
1122 	 */
1123 	return exitstatus;
1124 }
1125 
1126 
1127 /*
1128  * Handle break and continue commands.  Break, continue, and return are
1129  * all handled by setting the evalskip flag.  The evaluation routines
1130  * above all check this flag, and if it is set they start skipping
1131  * commands rather than executing them.  The variable skipcount is
1132  * the number of loops to break/continue, or the number of function
1133  * levels to return.  (The latter is always 1.)  It should probably
1134  * be an error to break out of more loops than exist, but it isn't
1135  * in the standard shell so we don't make it one here.
1136  */
1137 
1138 int
1139 breakcmd(int argc, char **argv)
1140 {
1141 	int n = argc > 1 ? number(argv[1]) : 1;
1142 
1143 	if (n > loopnest)
1144 		n = loopnest;
1145 	if (n > 0) {
1146 		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1147 		skipcount = n;
1148 	}
1149 	return 0;
1150 }
1151 
1152 /*
1153  * The `command' command.
1154  */
1155 int
1156 commandcmd(int argc, char **argv)
1157 {
1158 	const char *path;
1159 	int ch;
1160 	int cmd = -1;
1161 
1162 	path = bltinlookup("PATH", 1);
1163 
1164 	optind = optreset = 1;
1165 	opterr = 0;
1166 	while ((ch = getopt(argc, argv, "pvV")) != -1) {
1167 		switch (ch) {
1168 		case 'p':
1169 			path = _PATH_STDPATH;
1170 			break;
1171 		case 'v':
1172 			cmd = TYPECMD_SMALLV;
1173 			break;
1174 		case 'V':
1175 			cmd = TYPECMD_BIGV;
1176 			break;
1177 		case '?':
1178 		default:
1179 			error("unknown option: -%c", optopt);
1180 		}
1181 	}
1182 	argc -= optind;
1183 	argv += optind;
1184 
1185 	if (cmd != -1) {
1186 		if (argc != 1)
1187 			error("wrong number of arguments");
1188 		return typecmd_impl(2, argv - 1, cmd, path);
1189 	}
1190 	if (argc != 0)
1191 		error("commandcmd bad call");
1192 
1193 	/*
1194 	 * Do nothing successfully if no command was specified;
1195 	 * ksh also does this.
1196 	 */
1197 	return 0;
1198 }
1199 
1200 
1201 /*
1202  * The return command.
1203  */
1204 
1205 int
1206 returncmd(int argc, char **argv)
1207 {
1208 	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1209 
1210 	if (funcnest) {
1211 		evalskip = SKIPFUNC;
1212 		skipcount = 1;
1213 	} else {
1214 		/* skip the rest of the file */
1215 		evalskip = SKIPFILE;
1216 		skipcount = 1;
1217 	}
1218 	return ret;
1219 }
1220 
1221 
1222 int
1223 falsecmd(int argc __unused, char **argv __unused)
1224 {
1225 	return 1;
1226 }
1227 
1228 
1229 int
1230 truecmd(int argc __unused, char **argv __unused)
1231 {
1232 	return 0;
1233 }
1234 
1235 
1236 int
1237 execcmd(int argc, char **argv)
1238 {
1239 	/*
1240 	 * Because we have historically not supported any options,
1241 	 * only treat "--" specially.
1242 	 */
1243 	if (argc > 1 && strcmp(argv[1], "--") == 0)
1244 		argc--, argv++;
1245 	if (argc > 1) {
1246 		struct strlist *sp;
1247 
1248 		iflag = 0;		/* exit on error */
1249 		mflag = 0;
1250 		optschanged();
1251 		for (sp = cmdenviron; sp ; sp = sp->next)
1252 			setvareq(sp->text, VEXPORT|VSTACK);
1253 		shellexec(argv + 1, environment(), pathval(), 0);
1254 
1255 	}
1256 	return 0;
1257 }
1258 
1259 
1260 int
1261 timescmd(int argc __unused, char **argv __unused)
1262 {
1263 	struct rusage ru;
1264 	long shumins, shsmins, chumins, chsmins;
1265 	double shusecs, shssecs, chusecs, chssecs;
1266 
1267 	if (getrusage(RUSAGE_SELF, &ru) < 0)
1268 		return 1;
1269 	shumins = ru.ru_utime.tv_sec / 60;
1270 	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1271 	shsmins = ru.ru_stime.tv_sec / 60;
1272 	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1273 	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1274 		return 1;
1275 	chumins = ru.ru_utime.tv_sec / 60;
1276 	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1277 	chsmins = ru.ru_stime.tv_sec / 60;
1278 	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1279 	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1280 	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1281 	return 0;
1282 }
1283