1 /*-
2  * Copyright (c) 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1997-2005
5  *	Herbert Xu <herbert@gondor.apana.org.au>.  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 <zircon/process.h>
36 #include <zircon/status.h>
37 #include <zircon/syscalls.h>
38 #include <stdlib.h>
39 #include <signal.h>
40 #include <unistd.h>
41 #include <sys/types.h>
42 
43 /*
44  * Evaluate a command.
45  */
46 
47 #include "process.h"
48 #include "shell.h"
49 #include "nodes.h"
50 #include "syntax.h"
51 #include "expand.h"
52 #include "parser.h"
53 #include "jobs.h"
54 #include "eval.h"
55 #include "builtins.h"
56 #include "options.h"
57 #include "exec.h"
58 #include "redir.h"
59 #include "input.h"
60 #include "output.h"
61 #include "trap.h"
62 #include "var.h"
63 #include "memalloc.h"
64 #include "error.h"
65 #include "show.h"
66 #include "mystring.h"
67 
68 
69 int evalskip;			/* set if we are skipping commands */
70 STATIC int skipcount;		/* number of levels to skip */
71 MKINIT int loopnest;		/* current loop nesting level */
72 static int funcline;		/* starting line number of current function, or 0 if not in a function */
73 
74 
75 char *commandname;
76 int exitstatus;			/* exit status of last command */
77 int back_exitstatus;		/* exit status of backquoted command */
78 int savestatus = -1;		/* exit status of last command outside traps */
79 
80 
81 STATIC int evalloop(union node *, int);
82 STATIC int evalfor(union node *, int);
83 STATIC int evalcase(union node *, int);
84 STATIC int evalsubshell(union node *, int);
85 STATIC void expredir(union node *);
86 STATIC int evalpipe(union node *, int);
87 #ifdef notyet
88 STATIC int evalcommand(union node *, int, struct backcmd *);
89 #else
90 STATIC int evalcommand(union node *, int);
91 #endif
92 STATIC int evalbltin(const struct builtincmd *, int, char **, int);
93 STATIC int evalfun(struct funcnode *, int, char **, int);
94 STATIC void prehash(union node *);
95 STATIC int eprintlist(struct output *, struct strlist *, int);
96 STATIC int bltincmd(int, char **);
97 
98 
99 STATIC const struct builtincmd bltin = {
100 	name: nullstr,
101 	builtin: bltincmd
102 };
103 
104 
105 /*
106  * Called to reset things after an exception.
107  */
108 
109 #ifdef mkinit
110 INCLUDE "eval.h"
111 
112 RESET {
113 	evalskip = 0;
114 	loopnest = 0;
115 	if (savestatus >= 0) {
116 		exitstatus = savestatus;
117 		savestatus = -1;
118 	}
119 }
120 #endif
121 
122 
123 /*
124  * The eval commmand.
125  */
126 
evalcmd(int argc,char ** argv,int flags)127 static int evalcmd(int argc, char **argv, int flags)
128 {
129         char *p;
130         char *concat;
131         char **ap;
132 
133         if (argc > 1) {
134                 p = argv[1];
135                 if (argc > 2) {
136                         STARTSTACKSTR(concat);
137                         ap = argv + 2;
138                         for (;;) {
139                         	concat = stputs(p, concat);
140                                 if ((p = *ap++) == NULL)
141                                         break;
142                                 STPUTC(' ', concat);
143                         }
144                         STPUTC('\0', concat);
145                         p = grabstackstr(concat);
146                 }
147                 return evalstring(p, flags & EV_TESTED);
148         }
149         return 0;
150 }
151 
152 
153 /*
154  * Execute a command or commands contained in a string.
155  */
156 
157 int
evalstring(char * s,int flags)158 evalstring(char *s, int flags)
159 {
160 	union node *n;
161 	struct stackmark smark;
162 	int status;
163 
164 	s = sstrdup(s);
165 	setinputstring(s);
166 	setstackmark(&smark);
167 
168 	status = 0;
169 	for (; (n = parsecmd(0)) != NEOF; popstackmark(&smark)) {
170 		int i;
171 
172 		i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
173 		if (n)
174 			status = i;
175 
176 		if (evalskip)
177 			break;
178 	}
179 	popstackmark(&smark);
180 	popfile();
181 	stunalloc(s);
182 
183 	return status;
184 }
185 
186 
187 
188 /*
189  * Evaluate a parse tree.  The value is left in the global variable
190  * exitstatus.
191  */
192 
193 int
evaltree(union node * n,int flags)194 evaltree(union node *n, int flags)
195 {
196 	int checkexit = 0;
197 	int (*evalfn)(union node *, int);
198 	unsigned isor;
199 	int status = 0;
200 	if (n == NULL) {
201 		TRACE(("evaltree(NULL) called\n"));
202 		goto out;
203 	}
204 
205 	dotrap();
206 
207 	TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
208 	    getpid(), n, n->type, flags));
209 	switch (n->type) {
210 	default:
211 #ifdef DEBUG
212 		out1fmt("Node type = %d\n", n->type);
213 #ifndef USE_GLIBC_STDIO
214 		flushout(out1);
215 #endif
216 		break;
217 #endif
218 	case NNOT:
219 		status = !evaltree(n->nnot.com, EV_TESTED);
220 		goto setstatus;
221 	case NREDIR:
222 		errlinno = lineno = n->nredir.linno;
223 		if (funcline)
224 			lineno -= funcline - 1;
225 		expredir(n->nredir.redirect);
226 		pushredir(n->nredir.redirect);
227 		status = redirectsafe(n->nredir.redirect, REDIR_PUSH) ?:
228 			 evaltree(n->nredir.n, flags & EV_TESTED);
229 		if (n->nredir.redirect)
230 			popredir(0);
231 		goto setstatus;
232 	case NCMD:
233 #ifdef notyet
234 		if (eflag && !(flags & EV_TESTED))
235 			checkexit = ~0;
236 		status = evalcommand(n, flags, (struct backcmd *)NULL);
237 		goto setstatus;
238 #else
239 		evalfn = evalcommand;
240 checkexit:
241 		if (eflag && !(flags & EV_TESTED))
242 			checkexit = ~0;
243 		goto calleval;
244 #endif
245 	case NFOR:
246 		evalfn = evalfor;
247 		goto calleval;
248 	case NWHILE:
249 	case NUNTIL:
250 		evalfn = evalloop;
251 		goto calleval;
252 	case NSUBSHELL:
253 	case NBACKGND:
254 		evalfn = evalsubshell;
255 		goto checkexit;
256 	case NPIPE:
257 		evalfn = evalpipe;
258 		goto checkexit;
259 	case NCASE:
260 		evalfn = evalcase;
261 		goto calleval;
262 	case NAND:
263 	case NOR:
264 	case NSEMI:
265 #if NAND + 1 != NOR
266 #error NAND + 1 != NOR
267 #endif
268 #if NOR + 1 != NSEMI
269 #error NOR + 1 != NSEMI
270 #endif
271 		isor = n->type - NAND;
272 		status = evaltree(n->nbinary.ch1,
273 				  (flags | ((isor >> 1) - 1)) & EV_TESTED);
274 		if (!status == isor || evalskip)
275 			break;
276 		n = n->nbinary.ch2;
277 evaln:
278 		evalfn = evaltree;
279 calleval:
280 		status = evalfn(n, flags);
281 		goto setstatus;
282 	case NIF:
283 		status = evaltree(n->nif.test, EV_TESTED);
284 		if (evalskip)
285 			break;
286 		if (!status) {
287 			n = n->nif.ifpart;
288 			goto evaln;
289 		} else if (n->nif.elsepart) {
290 			n = n->nif.elsepart;
291 			goto evaln;
292 		}
293 		status = 0;
294 		goto setstatus;
295 	case NDEFUN:
296 		defun(n);
297 setstatus:
298 		exitstatus = status;
299 		break;
300 	}
301 out:
302 	if (checkexit & status)
303 		goto exexit;
304 
305 	dotrap();
306 
307 	if (flags & EV_EXIT) {
308 exexit:
309 		exraise(EXEXIT);
310 	}
311 
312 	return exitstatus;
313 }
314 
315 
316 void evaltreenr(union node *n, int flags)
317 #ifdef HAVE_ATTRIBUTE_ALIAS
318 	__attribute__ ((alias("evaltree")));
319 #else
320 {
321 	evaltree(n, flags);
322 	abort();
323 }
324 #endif
325 
326 
skiploop(void)327 static int skiploop(void)
328 {
329 	int skip = evalskip;
330 
331 	switch (skip) {
332 	case 0:
333 		break;
334 
335 	case SKIPBREAK:
336 	case SKIPCONT:
337 		if (likely(--skipcount <= 0)) {
338 			evalskip = 0;
339 			break;
340 		}
341 
342 		skip = SKIPBREAK;
343 		break;
344 	}
345 
346 	return skip;
347 }
348 
349 
350 STATIC int
evalloop(union node * n,int flags)351 evalloop(union node *n, int flags)
352 {
353 	int skip;
354 	int status;
355 
356 	loopnest++;
357 	status = 0;
358 	flags &= EV_TESTED;
359 	do {
360 		int i;
361 
362 		i = evaltree(n->nbinary.ch1, EV_TESTED);
363 		skip = skiploop();
364 		if (skip == SKIPFUNC)
365 			status = i;
366 		if (skip)
367 			continue;
368 		if (n->type != NWHILE)
369 			i = !i;
370 		if (i != 0)
371 			break;
372 		status = evaltree(n->nbinary.ch2, flags);
373 		if (status == ZX_ERR_CANCELED) {
374 			evalskip = SKIPBREAK;
375 		}
376 		skip = skiploop();
377 	} while (!(skip & ~SKIPCONT));
378 	loopnest--;
379 
380 	return status;
381 }
382 
383 
384 
385 STATIC int
evalfor(union node * n,int flags)386 evalfor(union node *n, int flags)
387 {
388 	struct arglist arglist;
389 	union node *argp;
390 	struct strlist *sp;
391 	struct stackmark smark;
392 	int status;
393 
394 	errlinno = lineno = n->nfor.linno;
395 	if (funcline)
396 		lineno -= funcline - 1;
397 
398 	setstackmark(&smark);
399 	arglist.lastp = &arglist.list;
400 	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
401 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
402 	}
403 	*arglist.lastp = NULL;
404 
405 	status = 0;
406 	loopnest++;
407 	flags &= EV_TESTED;
408 	for (sp = arglist.list ; sp ; sp = sp->next) {
409 		setvar(n->nfor.var, sp->text, 0);
410 		status = evaltree(n->nfor.body, flags);
411 		if (status == ZX_ERR_CANCELED) {
412 			evalskip = SKIPBREAK;
413 		}
414 		if (skiploop() & ~SKIPCONT)
415 			break;
416 	}
417 	loopnest--;
418 	popstackmark(&smark);
419 
420 	return status;
421 }
422 
423 
424 
425 STATIC int
evalcase(union node * n,int flags)426 evalcase(union node *n, int flags)
427 {
428 	union node *cp;
429 	union node *patp;
430 	struct arglist arglist;
431 	struct stackmark smark;
432 	int status = 0;
433 
434 	errlinno = lineno = n->ncase.linno;
435 	if (funcline)
436 		lineno -= funcline - 1;
437 
438 	setstackmark(&smark);
439 	arglist.lastp = &arglist.list;
440 	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
441 	for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
442 		for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
443 			if (casematch(patp, arglist.list->text)) {
444 				/* Ensure body is non-empty as otherwise
445 				 * EV_EXIT may prevent us from setting the
446 				 * exit status.
447 				 */
448 				if (evalskip == 0 && cp->nclist.body) {
449 					status = evaltree(cp->nclist.body,
450 							  flags);
451 				}
452 				goto out;
453 			}
454 		}
455 	}
456 out:
457 	popstackmark(&smark);
458 
459 	return status;
460 }
461 
462 
463 
464 /*
465  * Kick off a subshell to evaluate a tree.
466  */
467 
468 STATIC int
evalsubshell(union node * n,int flags)469 evalsubshell(union node *n, int flags)
470 {
471 	struct job *jp;
472 	int backgnd = (n->type == NBACKGND);
473 	int status;
474 
475 	errlinno = lineno = n->nredir.linno;
476 	if (funcline)
477 		lineno -= funcline - 1;
478 
479 	expredir(n->nredir.redirect);
480 	if (!backgnd && flags & EV_EXIT && !have_traps()) {
481 		redirect(n->nredir.redirect, 0);
482 		evaltreenr(n->nredir.n, flags);
483 		/* never returns */
484 	}
485 	INTOFF;
486 	jp = makejob(n, 1);
487 	zx_handle_t process;
488 	const char* const* envp = (const char* const*)environment();
489 
490 	// Run in the foreground (of the subshell running in the background)
491 	if (backgnd)
492 		n->type = NSUBSHELL;
493 
494 	char err_msg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
495 	zx_status_t exec_result = process_subshell(n, envp, &process, jp->zx_job_hndl, NULL, err_msg);
496         if (exec_result == ZX_OK) {
497 		/* Process-tracking management */
498 		forkparent(jp, n, backgnd, process);
499         } else {
500 		freejob(jp);
501 		sh_error("Failed to create subshell: %d (%s): %s", exec_result, zx_status_get_string(exec_result), err_msg);
502 		return exec_result;
503 	}
504 	status = 0;
505 	if (! backgnd) {
506 		status = process_await_termination(process, jp->zx_job_hndl, true);
507 		zx_handle_close(process);
508 	}
509 	INTON;
510 	freejob(jp);
511 	return status;
512 }
513 
514 
515 /*
516  * Compute the names of the files in a redirection list.
517  */
518 
519 STATIC void
expredir(union node * n)520 expredir(union node *n)
521 {
522 	union node *redir;
523 
524 	for (redir = n ; redir ; redir = redir->nfile.next) {
525 		struct arglist fn;
526 		fn.lastp = &fn.list;
527 		switch (redir->type) {
528 		case NFROMTO:
529 		case NFROM:
530 		case NTO:
531 		case NCLOBBER:
532 		case NAPPEND:
533 			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
534 			redir->nfile.expfname = fn.list->text;
535 			break;
536 		case NFROMFD:
537 		case NTOFD:
538 			if (redir->ndup.vname) {
539 				expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
540 				fixredir(redir, fn.list->text, 1);
541 			}
542 			break;
543 		}
544 	}
545 }
546 
547 
548 
549 /*
550  * Evaluate a pipeline.  All the processes in the pipeline are children
551  * of the process creating the pipeline.  (This differs from some versions
552  * of the shell, which make the last process in a pipeline the parent
553  * of all the rest.)
554  */
555 
556 STATIC int
evalpipe(union node * n,int flags)557 evalpipe(union node *n, int flags)
558 {
559 	struct job *jp;
560 	struct nodelist *lp;
561 	int pipelen;
562 	int fds[3] = { STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO };
563 	int pip[2] = { -1, -1 };
564 	int status = 0;
565 
566 	TRACE(("evalpipe(0x%lx) called\n", (long)n));
567 	pipelen = 0;
568 	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
569 		pipelen++;
570 	flags |= EV_EXIT;
571 	INTOFF;
572 	jp = makejob(n, pipelen);
573 
574 	const size_t processes_size = pipelen * sizeof(zx_handle_t);
575 	zx_handle_t* processes = ckmalloc(processes_size);
576 	memset(processes, 0, processes_size);
577 
578 	size_t idx = 0u;
579 	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next, ++idx) {
580 		prehash(lp->n);
581 		if (pip[0] > 0)
582 			fds[0] = pip[0];
583 		if (lp->next) {
584 			if (pipe(pip) < 0)
585 				sh_error("Pipe call failed");
586 			fds[1] = pip[1];
587 		} else {
588 			fds[1] = STDOUT_FILENO;
589 		}
590 		char err_msg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
591 		const char* const* envp = (const char* const*)environment();
592 		zx_status_t status = process_subshell(lp->n, envp, &processes[idx], jp->zx_job_hndl, fds, err_msg);
593 		if (fds[0] != STDIN_FILENO)
594 			close(fds[0]);
595 		if (fds[1] != STDOUT_FILENO)
596 			close(fds[1]);
597 		if (status == ZX_OK) {
598 			/* Process-tracking management */
599 			forkparent(jp, lp->n, FORK_NOJOB, processes[idx]);
600 		} else {
601 			freejob(jp);
602 			sh_error("Failed to create shell: %d (%s): %s", status, zx_status_get_string(status), err_msg);
603 		}
604 	}
605 
606 	if (n->npipe.backgnd == 0) {
607 		status = waitforjob(jp);
608 		TRACE(("evalpipe:  job done exit status: %d (%s)\n", status, zx_status_get_string(status)));
609 	}
610 	INTON;
611 
612 	zx_handle_close_many(processes, pipelen);
613 	ckfree(processes);
614 
615 	return status;
616 }
617 
618 
619 
620 /*
621  * Execute a command inside back quotes.  If it's a builtin command, we
622  * want to save its output in a block obtained from malloc.  Otherwise
623  * we fork off a subprocess and get the output of the command via a pipe.
624  * Should be called with interrupts off.
625  */
626 
627 void
evalbackcmd(union node * n,struct backcmd * result)628 evalbackcmd(union node *n, struct backcmd *result)
629 {
630 	int pip[2];
631 	struct job *jp;
632 
633 	result->fd = -1;
634 	result->buf = NULL;
635 	result->nleft = 0;
636 	result->jp = NULL;
637 	if (n == NULL) {
638 		goto out;
639 	}
640 
641 	if (pipe(pip) < 0)
642 		sh_error("Pipe call failed");
643 	jp = makejob(n, 1);
644 	zx_handle_t process;
645 	char err_msg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
646 	const char* const* envp = (const char* const*)environment();
647 	int fds[3] = { STDIN_FILENO, pip[1], STDERR_FILENO };
648 	zx_status_t status = process_subshell(n, envp, &process, jp->zx_job_hndl, &fds[0], err_msg);
649         close(pip[1]);
650 	if (status != ZX_OK) {
651 		freejob(jp);
652 		sh_error("Failed to create subshell: %d (%s): %s", status, zx_status_get_string(status), err_msg);
653 	} else {
654                 /* Process-tracking management */
655 		forkparent(jp, n, FORK_NOJOB, process);
656 		result->fd = pip[0];
657 		result->jp = jp;
658 	}
659 
660 out:
661 	TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
662 		result->fd, result->buf, result->nleft, result->jp));
663 }
664 
665 static char **
parse_command_args(char ** argv,const char ** path)666 parse_command_args(char **argv, const char **path)
667 {
668 	char *cp, c;
669 
670 	for (;;) {
671 		cp = *++argv;
672 		if (!cp)
673 			return 0;
674 		if (*cp++ != '-')
675 			break;
676 		if (!(c = *cp++))
677 			break;
678 		if (c == '-' && !*cp) {
679 			if (!*++argv)
680 				return 0;
681 			break;
682 		}
683 		do {
684 			switch (c) {
685 			case 'p':
686 				*path = defpath;
687 				break;
688 			default:
689 				/* run 'typecmd' for other options */
690 				return 0;
691 			}
692 		} while ((c = *cp++));
693 	}
694 	return argv;
695 }
696 
697 
698 
699 /*
700  * Execute a simple command.
701  */
702 
703 STATIC int
704 #ifdef notyet
evalcommand(union node * cmd,int flags,struct backcmd * backcmd)705 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
706 #else
707 evalcommand(union node *cmd, int flags)
708 #endif
709 {
710 	struct localvar_list *localvar_stop;
711 	struct redirtab *redir_stop;
712 	struct stackmark smark;
713 	union node *argp;
714 	struct arglist arglist;
715 	struct arglist varlist;
716 	char **argv;
717 	int argc;
718 	struct strlist *sp;
719 #ifdef notyet
720 	int pip[2];
721 #endif
722 	struct cmdentry cmdentry;
723 	char *lastarg;
724 	const char *path;
725 	int spclbltin;
726 	int execcmd;
727 	int status;
728 	char **nargv;
729 
730 	errlinno = lineno = cmd->ncmd.linno;
731 	if (funcline)
732 		lineno -= funcline - 1;
733 
734 	/* First expand the arguments. */
735 	TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
736 	setstackmark(&smark);
737 	localvar_stop = pushlocalvars();
738 	back_exitstatus = 0;
739 
740 	cmdentry.cmdtype = CMDBUILTIN;
741 	cmdentry.u.cmd = &bltin;
742 	varlist.lastp = &varlist.list;
743 	*varlist.lastp = NULL;
744 	arglist.lastp = &arglist.list;
745 	*arglist.lastp = NULL;
746 
747 	argc = 0;
748 	for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
749 		struct strlist **spp;
750 
751 		spp = arglist.lastp;
752 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
753 		for (sp = *spp; sp; sp = sp->next)
754 			argc++;
755 	}
756 
757 	/* Reserve one extra spot at the front for shellexec. */
758 	nargv = stalloc(sizeof (char *) * (argc + 2));
759 	argv = ++nargv;
760 	for (sp = arglist.list ; sp ; sp = sp->next) {
761 		TRACE(("evalcommand arg: %s\n", sp->text));
762 		*nargv++ = sp->text;
763 	}
764 	*nargv = NULL;
765 
766 	lastarg = NULL;
767 	if (iflag && funcline == 0 && argc > 0)
768 		lastarg = nargv[-1];
769 
770 	preverrout.fd = 2;
771 	expredir(cmd->ncmd.redirect);
772 	redir_stop = pushredir(cmd->ncmd.redirect);
773 	status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH|REDIR_SAVEFD2);
774 
775 	path = vpath.text;
776 	for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
777 		struct strlist **spp;
778 		char *p;
779 
780 		spp = varlist.lastp;
781 		expandarg(argp, &varlist, EXP_VARTILDE);
782 
783 		mklocal((*spp)->text);
784 
785 		/*
786 		 * Modify the command lookup path, if a PATH= assignment
787 		 * is present
788 		 */
789 		p = (*spp)->text;
790 		if (varequal(p, path))
791 			path = p;
792 	}
793 
794 	/* Print the command if xflag is set. */
795 	if (xflag) {
796 		struct output *out;
797 		int sep;
798 
799 		out = &preverrout;
800 		outstr(expandstr(ps4val()), out);
801 		sep = 0;
802 		sep = eprintlist(out, varlist.list, sep);
803 		eprintlist(out, arglist.list, sep);
804 		outcslow('\n', out);
805 #ifdef FLUSHERR
806 		flushout(out);
807 #endif
808 	}
809 
810 	execcmd = 0;
811 	spclbltin = -1;
812 
813 	/* Now locate the command. */
814 	if (argc) {
815 		const char *oldpath;
816 		int cmd_flag = DO_ERR;
817 
818 		path += 5;
819 		oldpath = path;
820 		for (;;) {
821 			find_command(argv[0], &cmdentry, cmd_flag, path);
822 			if (cmdentry.cmdtype == CMDUNKNOWN) {
823 				status = 127;
824 #ifdef FLUSHERR
825 				flushout(&errout);
826 #endif
827 				goto bail;
828 			}
829 
830 			/* implement bltin and command here */
831 			if (cmdentry.cmdtype != CMDBUILTIN)
832 				break;
833 			if (spclbltin < 0)
834 				spclbltin =
835 					cmdentry.u.cmd->flags &
836 					BUILTIN_SPECIAL
837 				;
838 			if (cmdentry.u.cmd == EXECCMD)
839 				execcmd++;
840 			if (cmdentry.u.cmd != COMMANDCMD)
841 				break;
842 
843 			path = oldpath;
844 			nargv = parse_command_args(argv, &path);
845 			if (!nargv)
846 				break;
847 			argc -= nargv - argv;
848 			argv = nargv;
849 			cmd_flag |= DO_NOFUNC;
850 		}
851 	}
852 
853 	if (status) {
854 bail:
855 		exitstatus = status;
856 
857 		/* We have a redirection error. */
858 		if (spclbltin > 0)
859 			exraise(EXERROR);
860 
861 		goto out;
862 	}
863 
864 	/* Execute the command. */
865 	switch (cmdentry.cmdtype) {
866 	default: {
867 		zx_handle_t process = ZX_HANDLE_INVALID;
868 		zx_handle_t zx_job_hndl;
869 		zx_status_t zx_status = zx_job_create(zx_job_default(), 0, &zx_job_hndl);
870 		if (zx_status != ZX_OK) {
871 			sh_error("Cannot create child process: %d (%s)", zx_status, zx_status_get_string(zx_status));
872 			break;
873 		}
874 		char err_msg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
875 		status = process_launch((const char* const*)argv, path, cmdentry.u.index, &process, zx_job_hndl, &zx_status, err_msg);
876 		if (status) {
877 			sh_error("Cannot create child process: %d (%s): %s", zx_status, zx_status_get_string(zx_status), err_msg);
878 			break;
879 		}
880 		settitle(argv[0]);
881 		status = process_await_termination(process, zx_job_hndl, true);
882 		zx_handle_close(process);
883 		zx_handle_close(zx_job_hndl);
884 		settitle("sh");
885 		break;
886 	}
887 	case CMDBUILTIN:
888 		if (spclbltin > 0 || argc == 0) {
889 			poplocalvars(1);
890 			if (execcmd && argc > 1)
891 				listsetvar(varlist.list, VEXPORT);
892 		}
893 		if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
894 			if (exception == EXERROR && spclbltin <= 0) {
895 				FORCEINTON;
896 				goto readstatus;
897 			}
898 raise:
899 			longjmp(handler->loc, 1);
900 		}
901 		goto readstatus;
902 
903 	case CMDFUNCTION:
904 		poplocalvars(1);
905 		if (evalfun(cmdentry.u.func, argc, argv, flags))
906 			goto raise;
907 readstatus:
908 		status = exitstatus;
909 		break;
910 	}
911 
912 out:
913 	if (cmd->ncmd.redirect)
914 		popredir(execcmd);
915 	unwindredir(redir_stop);
916 	unwindlocalvars(localvar_stop);
917 	if (lastarg)
918 		/* dsl: I think this is intended to be used to support
919 		 * '_' in 'vi' command mode during line editing...
920 		 * However I implemented that within libedit itself.
921 		 */
922 		setvar("_", lastarg, 0);
923 	popstackmark(&smark);
924 
925 	return status;
926 }
927 
928 STATIC int
evalbltin(const struct builtincmd * cmd,int argc,char ** argv,int flags)929 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
930 {
931 	char *volatile savecmdname;
932 	struct jmploc *volatile savehandler;
933 	struct jmploc jmploc;
934 	int status;
935 	int i;
936 
937 	savecmdname = commandname;
938 	savehandler = handler;
939 	if ((i = setjmp(jmploc.loc)))
940 		goto cmddone;
941 	handler = &jmploc;
942 	commandname = argv[0];
943 	argptr = argv + 1;
944 	optptr = NULL;			/* initialize nextopt */
945 	if (cmd == EVALCMD)
946 		status = evalcmd(argc, argv, flags);
947 	else
948 		status = (*cmd->builtin)(argc, argv);
949 	flushall();
950 	status |= outerr(out1);
951 	exitstatus = status;
952 cmddone:
953 	freestdout();
954 	commandname = savecmdname;
955 	handler = savehandler;
956 
957 	return i;
958 }
959 
960 STATIC int
evalfun(struct funcnode * func,int argc,char ** argv,int flags)961 evalfun(struct funcnode *func, int argc, char **argv, int flags)
962 {
963 	volatile struct shparam saveparam;
964 	struct jmploc *volatile savehandler;
965 	struct jmploc jmploc;
966 	int e;
967 	int savefuncline;
968 	int saveloopnest;
969 
970 	saveparam = shellparam;
971 	savefuncline = funcline;
972 	saveloopnest = loopnest;
973 	savehandler = handler;
974 	if ((e = setjmp(jmploc.loc))) {
975 		goto funcdone;
976 	}
977 	INTOFF;
978 	handler = &jmploc;
979 	shellparam.malloc = 0;
980 	func->count++;
981 	funcline = func->n.ndefun.linno;
982 	loopnest = 0;
983 	INTON;
984 	shellparam.nparam = argc - 1;
985 	shellparam.p = argv + 1;
986 	shellparam.optind = 1;
987 	shellparam.optoff = -1;
988 	pushlocalvars();
989 	evaltree(func->n.ndefun.body, flags & EV_TESTED);
990 	poplocalvars(0);
991 funcdone:
992 	INTOFF;
993 	loopnest = saveloopnest;
994 	funcline = savefuncline;
995 	freefunc(func);
996 	freeparam(&shellparam);
997 	shellparam = saveparam;
998 	handler = savehandler;
999 	INTON;
1000 	evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
1001 	return e;
1002 }
1003 
1004 
1005 /*
1006  * Search for a command.  This is called before we fork so that the
1007  * location of the command will be available in the parent as well as
1008  * the child.  The check for "goodname" is an overly conservative
1009  * check that the name will not be subject to expansion.
1010  */
1011 
1012 STATIC void
prehash(union node * n)1013 prehash(union node *n)
1014 {
1015 	struct cmdentry entry;
1016 
1017 	if (n->type == NCMD && n->ncmd.args)
1018 		if (goodname(n->ncmd.args->narg.text))
1019 			find_command(n->ncmd.args->narg.text, &entry, 0,
1020 				     pathval());
1021 }
1022 
1023 
1024 
1025 /*
1026  * Builtin commands.  Builtin commands whose functions are closely
1027  * tied to evaluation are implemented here.
1028  */
1029 
1030 /*
1031  * No command given.
1032  */
1033 
1034 STATIC int
bltincmd(int argc,char ** argv)1035 bltincmd(int argc, char **argv)
1036 {
1037 	/*
1038 	 * Preserve exitstatus of a previous possible redirection
1039 	 * as POSIX mandates
1040 	 */
1041 	return back_exitstatus;
1042 }
1043 
1044 
1045 /*
1046  * Handle break and continue commands.  Break, continue, and return are
1047  * all handled by setting the evalskip flag.  The evaluation routines
1048  * above all check this flag, and if it is set they start skipping
1049  * commands rather than executing them.  The variable skipcount is
1050  * the number of loops to break/continue, or the number of function
1051  * levels to return.  (The latter is always 1.)  It should probably
1052  * be an error to break out of more loops than exist, but it isn't
1053  * in the standard shell so we don't make it one here.
1054  */
1055 
1056 int
breakcmd(int argc,char ** argv)1057 breakcmd(int argc, char **argv)
1058 {
1059 	int n = argc > 1 ? number(argv[1]) : 1;
1060 
1061 	if (n <= 0)
1062 		badnum(argv[1]);
1063 	if (n > loopnest)
1064 		n = loopnest;
1065 	if (n > 0) {
1066 		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1067 		skipcount = n;
1068 	}
1069 	return 0;
1070 }
1071 
1072 
1073 /*
1074  * The return command.
1075  */
1076 
1077 int
returncmd(int argc,char ** argv)1078 returncmd(int argc, char **argv)
1079 {
1080 	int skip;
1081 	int status;
1082 
1083 	/*
1084 	 * If called outside a function, do what ksh does;
1085 	 * skip the rest of the file.
1086 	 */
1087 	if (argv[1]) {
1088 		skip = SKIPFUNC;
1089 		status = number(argv[1]);
1090 	} else {
1091 		skip = SKIPFUNCDEF;
1092 		status = exitstatus;
1093 	}
1094 	evalskip = skip;
1095 
1096 	return status;
1097 }
1098 
1099 
1100 int
falsecmd(int argc,char ** argv)1101 falsecmd(int argc, char **argv)
1102 {
1103 	return 1;
1104 }
1105 
1106 
1107 int
truecmd(int argc,char ** argv)1108 truecmd(int argc, char **argv)
1109 {
1110 	return 0;
1111 }
1112 
1113 
1114 int
execcmd(int argc,char ** argv)1115 execcmd(int argc, char **argv)
1116 {
1117 	if (argc > 1) {
1118 		iflag = 0;		/* exit on error */
1119 		mflag = 0;
1120 		optschanged();
1121 		shellexec(argv + 1, pathval(), 0);
1122 	}
1123 	return 0;
1124 }
1125 
1126 
1127 STATIC int
eprintlist(struct output * out,struct strlist * sp,int sep)1128 eprintlist(struct output *out, struct strlist *sp, int sep)
1129 {
1130 	while (sp) {
1131 		const char *p;
1132 
1133 		p = " %s" + (1 - sep);
1134 		sep |= 1;
1135 		outfmt(out, p, sp->text);
1136 		sp = sp->next;
1137 	}
1138 
1139 	return sep;
1140 }
1141