1 /*
2  * exec.c - command execution
3  *
4  * This file is part of zsh, the Z shell.
5  *
6  * Copyright (c) 1992-1997 Paul Falstad
7  * All rights reserved.
8  *
9  * Permission is hereby granted, without written agreement and without
10  * license or royalty fees, to use, copy, modify, and distribute this
11  * software and to distribute modified versions of this software for any
12  * purpose, provided that the above copyright notice and the following
13  * two paragraphs appear in all copies of this software.
14  *
15  * In no event shall Paul Falstad or the Zsh Development Group be liable
16  * to any party for direct, indirect, special, incidental, or consequential
17  * damages arising out of the use of this software and its documentation,
18  * even if Paul Falstad and the Zsh Development Group have been advised of
19  * the possibility of such damage.
20  *
21  * Paul Falstad and the Zsh Development Group specifically disclaim any
22  * warranties, including, but not limited to, the implied warranties of
23  * merchantability and fitness for a particular purpose.  The software
24  * provided hereunder is on an "as is" basis, and Paul Falstad and the
25  * Zsh Development Group have no obligation to provide maintenance,
26  * support, updates, enhancements, or modifications.
27  *
28  */
29 
30 #include "zsh.mdh"
31 #include "exec.pro"
32 
33 /* Flags for last argument of addvars */
34 
35 enum {
36     /* Export the variable for "VAR=val cmd ..." */
37     ADDVAR_EXPORT =   1 << 0,
38     /* Apply restrictions for variable */
39     ADDVAR_RESTRICT = 1 << 1,
40     /* Variable list is being restored later */
41     ADDVAR_RESTORE =  1 << 2
42 };
43 
44 /* Structure in which to save values around shell function call */
45 
46 struct funcsave {
47     char opts[OPT_SIZE];
48     char *argv0;
49     int zoptind, lastval, optcind, numpipestats;
50     int *pipestats;
51     char *scriptname;
52     int breaks, contflag, loops, emulation, noerrexit, oflags, restore_sticky;
53     Emulation_options sticky;
54     struct funcstack fstack;
55 };
56 typedef struct funcsave *Funcsave;
57 
58 /*
59  * used to suppress ERREXIT and trapping of SIGZERR, SIGEXIT.
60  * Bits from noerrexit_bits.
61  */
62 
63 /**/
64 int noerrexit;
65 
66 /* used to suppress ERREXIT or ERRRETURN for one occurrence: 0 or 1 */
67 
68 /**/
69 int this_noerrexit;
70 
71 /*
72  * noerrs = 1: suppress error messages
73  * noerrs = 2: don't set errflag on parse error, either
74  */
75 
76 /**/
77 mod_export int noerrs;
78 
79 /* do not save history on exec and exit */
80 
81 /**/
82 int nohistsave;
83 
84 /* error flag: bits from enum errflag_bits */
85 
86 /**/
87 mod_export int errflag;
88 
89 /*
90  * State of trap return value.  Value is from enum trap_state.
91  */
92 
93 /**/
94 int trap_state;
95 
96 /*
97  * Value associated with return from a trap.
98  * This is only active if we are inside a trap, else its value
99  * is irrelevant.  It is initialised to -1 for a function trap and
100  * -2 for a non-function trap and if negative is decremented as
101  * we go deeper into functions and incremented as we come back up.
102  * The value is used to decide if an explicit "return" should cause
103  * a return from the caller of the trap; it does this by setting
104  * trap_return to a status (i.e. a non-negative value).
105  *
106  * In summary, trap_return is
107  * - zero unless we are in a trap
108  * - negative in a trap unless it has triggered.  Code uses this
109  *   to detect an active trap.
110  * - non-negative in a trap once it was triggered.  It should remain
111  *   non-negative until restored after execution of the trap.
112  */
113 
114 /**/
115 int trap_return;
116 
117 /* != 0 if this is a subshell */
118 
119 /**/
120 int subsh;
121 
122 /* != 0 if we have a return pending */
123 
124 /**/
125 mod_export int retflag;
126 
127 /**/
128 long lastval2;
129 
130 /* The table of file descriptors.  A table element is zero if the  *
131  * corresponding fd is not used by the shell.  It is greater than  *
132  * 1 if the fd is used by a <(...) or >(...) substitution and 1 if *
133  * it is an internal file descriptor which must be closed before   *
134  * executing an external command.  The first ten elements of the   *
135  * table is not used.  A table element is set by movefd and cleard *
136  * by zclose.                                                      */
137 
138 /**/
139 mod_export unsigned char *fdtable;
140 
141 /* The allocated size of fdtable */
142 
143 /**/
144 int fdtable_size;
145 
146 /* The highest fd that marked with nonzero in fdtable */
147 
148 /**/
149 mod_export int max_zsh_fd;
150 
151 /* input fd from the coprocess */
152 
153 /**/
154 mod_export int coprocin;
155 
156 /* output fd from the coprocess */
157 
158 /**/
159 mod_export int coprocout;
160 
161 /* count of file locks recorded in fdtable */
162 
163 /**/
164 int fdtable_flocks;
165 
166 
167 /* != 0 if the line editor is active */
168 
169 /**/
170 mod_export int zleactive;
171 
172 /* pid of process undergoing 'process substitution' */
173 
174 /**/
175 pid_t cmdoutpid;
176 
177 /* pid of last process started by <(...),  >(...) */
178 
179 /**/
180 mod_export pid_t procsubstpid;
181 
182 /* exit status of process undergoing 'process substitution' */
183 
184 /**/
185 int cmdoutval;
186 
187 /*
188  * This is set by an exiting $(...) substitution to indicate we need
189  * to retain the status.  We initialize it to zero if we think we need
190  * to reset the status for a command.
191  */
192 
193 /**/
194 int use_cmdoutval;
195 
196 /* The context in which a shell function is called, see SFC_* in zsh.h. */
197 
198 /**/
199 mod_export int sfcontext;
200 
201 /* Stack to save some variables before executing a signal handler function */
202 
203 /**/
204 struct execstack *exstack;
205 
206 /* Stack with names of function calls, 'source' calls, and 'eval' calls
207  * currently active. */
208 
209 /**/
210 mod_export Funcstack funcstack;
211 
212 #define execerr()				\
213     do {					\
214 	if (!forked) {				\
215 	    redir_err = lastval = 1;		\
216 	    goto done;				\
217 	} else {				\
218 	    _exit(1);				\
219 	}					\
220     } while (0)
221 
222 static int doneps4;
223 static char *STTYval;
224 static char *blank_env[] = { NULL };
225 
226 /* Execution functions. */
227 
228 static int (*execfuncs[WC_COUNT-WC_CURSH]) _((Estate, int)) = {
229     execcursh, exectime, NULL /* execfuncdef handled specially */,
230     execfor, execselect,
231     execwhile, execrepeat, execcase, execif, execcond,
232     execarith, execautofn, exectry
233 };
234 
235 /* structure for command builtin for when it is used with -v or -V */
236 static struct builtin commandbn =
237     BUILTIN("command", 0, bin_whence, 0, -1, BIN_COMMAND, "pvV", NULL);
238 
239 /* parse string into a list */
240 
241 /**/
242 mod_export Eprog
parse_string(char * s,int reset_lineno)243 parse_string(char *s, int reset_lineno)
244 {
245     Eprog p;
246     zlong oldlineno;
247 
248     zcontext_save();
249     inpush(s, INP_LINENO, NULL);
250     strinbeg(0);
251     oldlineno = lineno;
252     if (reset_lineno)
253 	lineno = 1;
254     p = parse_list();
255     lineno = oldlineno;
256     if (tok == LEXERR && !lastval)
257 	lastval = 1;
258     strinend();
259     inpop();
260     zcontext_restore();
261     return p;
262 }
263 
264 /**/
265 #ifdef HAVE_GETRLIMIT
266 
267 /* the resource limits for the shell and its children */
268 
269 /**/
270 mod_export struct rlimit current_limits[RLIM_NLIMITS], limits[RLIM_NLIMITS];
271 
272 /**/
273 mod_export int
zsetlimit(int limnum,char * nam)274 zsetlimit(int limnum, char *nam)
275 {
276     if (limits[limnum].rlim_max != current_limits[limnum].rlim_max ||
277 	limits[limnum].rlim_cur != current_limits[limnum].rlim_cur) {
278 	if (setrlimit(limnum, limits + limnum)) {
279 	    if (nam)
280 		zwarnnam(nam, "setrlimit failed: %e", errno);
281 	    limits[limnum] = current_limits[limnum];
282 	    return -1;
283 	}
284 	current_limits[limnum] = limits[limnum];
285     }
286     return 0;
287 }
288 
289 /**/
290 mod_export int
setlimits(char * nam)291 setlimits(char *nam)
292 {
293     int limnum;
294     int ret = 0;
295 
296     for (limnum = 0; limnum < RLIM_NLIMITS; limnum++)
297 	if (zsetlimit(limnum, nam))
298 	    ret++;
299     return ret;
300 }
301 
302 /**/
303 #endif /* HAVE_GETRLIMIT */
304 
305 /* fork and set limits */
306 
307 /**/
308 static pid_t
zfork(struct timeval * tv)309 zfork(struct timeval *tv)
310 {
311     pid_t pid;
312     struct timezone dummy_tz;
313 
314     /*
315      * Is anybody willing to explain this test?
316      */
317     if (thisjob != -1 && thisjob >= jobtabsize - 1 && !expandjobtab()) {
318 	zerr("job table full");
319 	return -1;
320     }
321     if (tv)
322 	gettimeofday(tv, &dummy_tz);
323     /*
324      * Queueing signals is necessary on Linux because fork()
325      * manipulates mutexes, leading to deadlock in memory
326      * allocation.  We don't expect fork() to be particularly
327      * zippy anyway.
328      */
329     queue_signals();
330     pid = fork();
331     unqueue_signals();
332     if (pid == -1) {
333 	zerr("fork failed: %e", errno);
334 	return -1;
335     }
336 #ifdef HAVE_GETRLIMIT
337     if (!pid)
338 	/* set resource limits for the child process */
339 	setlimits(NULL);
340 #endif
341     return pid;
342 }
343 
344 /*
345  *   Allen Edeln gebiet ich Andacht,
346  *   Hohen und Niedern von Heimdalls Geschlecht;
347  *   Ich will list_pipe's Wirken kuenden
348  *   Die aeltesten Sagen, der ich mich entsinne...
349  *
350  * In most shells, if you do something like:
351  *
352  *   cat foo | while read a; do grep $a bar; done
353  *
354  * the shell forks and executes the loop in the sub-shell thus created.
355  * In zsh this traditionally executes the loop in the current shell, which
356  * is nice to have if the loop does something to change the shell, like
357  * setting parameters or calling builtins.
358  * Putting the loop in a sub-shell makes life easy, because the shell only
359  * has to put it into the job-structure and then treats it as a normal
360  * process. Suspending and interrupting is no problem then.
361  * Some years ago, zsh either couldn't suspend such things at all, or
362  * it got really messed up when users tried to do it. As a solution, we
363  * implemented the list_pipe-stuff, which has since then become a reason
364  * for many nightmares.
365  * Pipelines like the one above are executed by the functions in this file
366  * which call each other (and sometimes recursively). The one above, for
367  * example would lead to a function call stack roughly like:
368  *
369  *  execlist->execpline->execcmd->execwhile->execlist->execpline
370  *
371  * (when waiting for the grep, ignoring execpline2 for now). At this time,
372  * zsh has built two job-table entries for it: one for the cat and one for
373  * the grep. If the user hits ^Z at this point (and jobbing is used), the
374  * shell is notified that the grep was suspended. The list_pipe flag is
375  * used to tell the execpline where it was waiting that it was in a pipeline
376  * with a shell construct at the end (which may also be a shell function or
377  * several other things). When zsh sees the suspended grep, it forks to let
378  * the sub-shell execute the rest of the while loop. The parent shell walks
379  * up in the function call stack to the first execpline. There it has to find
380  * out that it has just forked and then has to add information about the sub-
381  * shell (its pid and the text for it) in the job entry of the cat. The pid
382  * is passed down in the list_pipe_pid variable.
383  * But there is a problem: the suspended grep is a child of the parent shell
384  * and can't be adopted by the sub-shell. So the parent shell also has to
385  * keep the information about this process (more precisely: this pipeline)
386  * by keeping the job table entry it created for it. The fact that there
387  * are two jobs which have to be treated together is remembered by setting
388  * the STAT_SUPERJOB flag in the entry for the cat-job (which now also
389  * contains a process-entry for the whole loop -- the sub-shell) and by
390  * setting STAT_SUBJOB in the job of the grep-job. With that we can keep
391  * sub-jobs from being displayed and we can handle an fg/bg on the super-
392  * job correctly. When the super-job is continued, the shell also wakes up
393  * the sub-job. But then, the grep will exit sometime. Now the parent shell
394  * has to remember not to try to wake it up again (in case of another ^Z).
395  * It also has to wake up the sub-shell (which suspended itself immediately
396  * after creation), so that the rest of the loop is executed by it.
397  * But there is more: when the sub-shell is created, the cat may already
398  * have exited, so we can't put the sub-shell in the process group of it.
399  * In this case, we put the sub-shell in the process group of the parent
400  * shell and in any case, the sub-shell has to put all commands executed
401  * by it into its own process group, because only this way the parent
402  * shell can control them since it only knows the process group of the sub-
403  * shell. Of course, this information is also important when putting a job
404  * in the foreground, where we have to attach its process group to the
405  * controlling tty.
406  * All this is made more difficult because we have to handle return values
407  * correctly. If the grep is signaled, its exit status has to be propagated
408  * back to the parent shell which needs it to set the exit status of the
409  * super-job. And of course, when the grep is signaled (including ^C), the
410  * loop has to be stopped, etc.
411  * The code for all this is distributed over three files (exec.c, jobs.c,
412  * and signals.c) and none of them is a simple one. So, all in all, there
413  * may still be bugs, but considering the complexity (with race conditions,
414  * signal handling, and all that), this should probably be expected.
415  */
416 
417 /**/
418 int list_pipe = 0, simple_pline = 0;
419 
420 static pid_t list_pipe_pid;
421 static struct timeval list_pipe_start;
422 static int nowait, pline_level = 0;
423 static int list_pipe_child = 0, list_pipe_job;
424 static char list_pipe_text[JOBTEXTSIZE];
425 
426 /* execute a current shell command */
427 
428 /**/
429 static int
execcursh(Estate state,int do_exec)430 execcursh(Estate state, int do_exec)
431 {
432     Wordcode end = state->pc + WC_CURSH_SKIP(state->pc[-1]);
433 
434     /* Skip word only used for try/always */
435     state->pc++;
436 
437     /*
438      * The test thisjob != -1 was added because sometimes thisjob
439      * can be invalid at this point.  The case in question was
440      * in a precmd function after operations involving background
441      * jobs.
442      *
443      * This is because sometimes we bypass job control to execute
444      * very simple functions via execssimple().
445      */
446     if (!list_pipe && thisjob != -1 && thisjob != list_pipe_job &&
447 	!hasprocs(thisjob))
448 	deletejob(jobtab + thisjob, 0);
449     cmdpush(CS_CURSH);
450     execlist(state, 1, do_exec);
451     cmdpop();
452 
453     state->pc = end;
454     this_noerrexit = 1;
455 
456     return lastval;
457 }
458 
459 /* execve after handling $_ and #! */
460 
461 #define POUNDBANGLIMIT 128
462 
463 /**/
464 static int
zexecve(char * pth,char ** argv,char ** newenvp)465 zexecve(char *pth, char **argv, char **newenvp)
466 {
467     int eno;
468     static char buf[PATH_MAX * 2+1];
469     char **eep;
470 
471     unmetafy(pth, NULL);
472     for (eep = argv; *eep; eep++)
473 	if (*eep != pth)
474 	    unmetafy(*eep, NULL);
475     buf[0] = '_';
476     buf[1] = '=';
477     if (*pth == '/')
478 	strcpy(buf + 2, pth);
479     else
480 	sprintf(buf + 2, "%s/%s", pwd, pth);
481     zputenv(buf);
482 #ifndef FD_CLOEXEC
483     closedumps();
484 #endif
485 
486     if (newenvp == NULL)
487 	    newenvp = environ;
488     winch_unblock();
489     execve(pth, argv, newenvp);
490 
491     /* If the execve returns (which in general shouldn't happen),   *
492      * then check for an errno equal to ENOEXEC.  This errno is set *
493      * if the process file has the appropriate access permission,   *
494      * but has an invalid magic number in its header.               */
495     if ((eno = errno) == ENOEXEC || eno == ENOENT) {
496 	char execvebuf[POUNDBANGLIMIT + 1], *ptr, *ptr2, *argv0;
497 	int fd, ct, t0;
498 
499 	if ((fd = open(pth, O_RDONLY|O_NOCTTY)) >= 0) {
500 	    argv0 = *argv;
501 	    *argv = pth;
502 	    memset(execvebuf, '\0', POUNDBANGLIMIT + 1);
503 	    ct = read(fd, execvebuf, POUNDBANGLIMIT);
504 	    close(fd);
505 	    if (ct >= 0) {
506 		if (ct >= 2 && execvebuf[0] == '#' && execvebuf[1] == '!') {
507 		    for (t0 = 0; t0 != ct; t0++)
508 			if (execvebuf[t0] == '\n')
509 			    break;
510 		    if (t0 == ct)
511 			zerr("%s: bad interpreter: %s: %e", pth,
512 			     execvebuf + 2, eno);
513 		    else {
514 			while (inblank(execvebuf[t0]))
515 			    execvebuf[t0--] = '\0';
516 			for (ptr = execvebuf + 2; *ptr && *ptr == ' '; ptr++);
517 			for (ptr2 = ptr; *ptr && *ptr != ' '; ptr++);
518 			if (eno == ENOENT) {
519 			    char *pprog;
520 			    if (*ptr)
521 				*ptr = '\0';
522 			    if (*ptr2 != '/' &&
523 				(pprog = pathprog(ptr2, NULL))) {
524 				if (ptr == execvebuf + t0 + 1) {
525 				    argv[-1] = ptr2;
526 				    winch_unblock();
527 				    execve(pprog, argv - 1, newenvp);
528 				} else {
529 				    argv[-2] = ptr2;
530 				    argv[-1] = ptr + 1;
531 				    winch_unblock();
532 				    execve(pprog, argv - 2, newenvp);
533 				}
534 			    }
535 			    zerr("%s: bad interpreter: %s: %e", pth, ptr2,
536 				 eno);
537 			} else if (*ptr) {
538 			    *ptr = '\0';
539 			    argv[-2] = ptr2;
540 			    argv[-1] = ptr + 1;
541 			    winch_unblock();
542 			    execve(ptr2, argv - 2, newenvp);
543 			} else {
544 			    argv[-1] = ptr2;
545 			    winch_unblock();
546 			    execve(ptr2, argv - 1, newenvp);
547 			}
548 		    }
549 		} else if (eno == ENOEXEC) {
550 		    for (t0 = 0; t0 != ct; t0++)
551 			if (!execvebuf[t0])
552 			    break;
553 		    if (t0 == ct) {
554 			argv[-1] = "sh";
555 			winch_unblock();
556 			execve("/bin/sh", argv - 1, newenvp);
557 		    }
558 		}
559 	    } else
560 		eno = errno;
561 	    *argv = argv0;
562 	} else
563 	    eno = errno;
564     }
565     /* restore the original arguments and path but do not bother with *
566      * null characters as these cannot be passed to external commands *
567      * anyway.  So the result is truncated at the first null char.    */
568     pth = metafy(pth, -1, META_NOALLOC);
569     for (eep = argv; *eep; eep++)
570 	if (*eep != pth)
571 	    (void) metafy(*eep, -1, META_NOALLOC);
572     return eno;
573 }
574 
575 #define MAXCMDLEN (PATH_MAX*4)
576 
577 /* test whether we really want to believe the error number */
578 
579 /**/
580 static int
isgooderr(int e,char * dir)581 isgooderr(int e, char *dir)
582 {
583     /*
584      * Maybe the directory was unreadable, or maybe it wasn't
585      * even a directory.
586      */
587     return ((e != EACCES || !access(dir, X_OK)) &&
588 	    e != ENOENT && e != ENOTDIR);
589 }
590 
591 /*
592  * Attempt to handle command not found.
593  * Return 0 if the condition was handled, non-zero otherwise.
594  */
595 
596 /**/
597 static int
commandnotfound(char * arg0,LinkList args)598 commandnotfound(char *arg0, LinkList args)
599 {
600     Shfunc shf = (Shfunc)
601 	shfunctab->getnode(shfunctab, "command_not_found_handler");
602 
603     if (!shf) {
604 	lastval = 127;
605 	return 1;
606     }
607 
608     pushnode(args, arg0);
609     lastval = doshfunc(shf, args, 1);
610     return 0;
611 }
612 
613 /*
614  * Search the default path for cmd.
615  * pbuf of length plen is the buffer to use.
616  * Return NULL if not found.
617  */
618 
619 static char *
search_defpath(char * cmd,char * pbuf,int plen)620 search_defpath(char *cmd, char *pbuf, int plen)
621 {
622     char *ps = DEFAULT_PATH, *pe = NULL, *s;
623 
624     for (ps = DEFAULT_PATH; ps; ps = pe ? pe+1 : NULL) {
625 	pe = strchr(ps, ':');
626 	if (*ps == '/') {
627 	    s = pbuf;
628 	    if (pe) {
629 		if (pe - ps >= plen)
630 		    continue;
631 		struncpy(&s, ps, pe-ps);
632 	    } else {
633 		if (strlen(ps) >= plen)
634 		    continue;
635 		strucpy(&s, ps);
636 	    }
637 	    *s++ = '/';
638 	    if ((s - pbuf) + strlen(cmd) >= plen)
639 		continue;
640 	    strucpy(&s, cmd);
641 	    if (iscom(pbuf))
642 		return pbuf;
643 	}
644     }
645     return NULL;
646 }
647 
648 /* execute an external command */
649 
650 /**/
651 static void
execute(LinkList args,int flags,int defpath)652 execute(LinkList args, int flags, int defpath)
653 {
654     Cmdnam cn;
655     char buf[MAXCMDLEN+1], buf2[MAXCMDLEN+1];
656     char *s, *z, *arg0;
657     char **argv, **pp, **newenvp = NULL;
658     int eno = 0, ee;
659 
660     arg0 = (char *) peekfirst(args);
661     if (isset(RESTRICTED) && (strchr(arg0, '/') || defpath)) {
662 	zerr("%s: restricted", arg0);
663 	_exit(1);
664     }
665 
666     /* If the parameter STTY is set in the command's environment, *
667      * we first run the stty command with the value of this       *
668      * parameter as it arguments.                                 */
669     if ((s = STTYval) && isatty(0) && (GETPGRP() == getpid())) {
670 	char *t = tricat("stty", " ", s);
671 
672 	STTYval = 0;	/* this prevents infinite recursion */
673 	zsfree(s);
674 	execstring(t, 1, 0, "stty");
675 	zsfree(t);
676     } else if (s) {
677 	STTYval = 0;
678 	zsfree(s);
679     }
680 
681     /* If ARGV0 is in the commands environment, we use *
682      * that as argv[0] for this external command       */
683     if (unset(RESTRICTED) && (z = zgetenv("ARGV0"))) {
684 	setdata(firstnode(args), (void *) ztrdup(z));
685 	/*
686 	 * Note we don't do anything with the parameter structure
687 	 * for ARGV0: that's OK since we're about to exec or exit
688 	 * on failure.
689 	 */
690 #ifdef USE_SET_UNSET_ENV
691 	unsetenv("ARGV0");
692 #else
693 	delenvvalue(z - 6);
694 #endif
695     } else if (flags & BINF_DASH) {
696     /* Else if the pre-command `-' was given, we add `-' *
697      * to the front of argv[0] for this command.         */
698 	sprintf(buf2, "-%s", arg0);
699 	setdata(firstnode(args), (void *) ztrdup(buf2));
700     }
701 
702     argv = makecline(args);
703     if (flags & BINF_CLEARENV)
704 	newenvp = blank_env;
705 
706     /*
707      * Note that we don't close fd's attached to process substitution
708      * here, which should be visible to external processes.
709      */
710     closem(FDT_XTRACE, 0);
711 #ifndef FD_CLOEXEC
712     if (SHTTY != -1) {
713 	close(SHTTY);
714 	SHTTY = -1;
715     }
716 #endif
717     child_unblock();
718     if ((int) strlen(arg0) >= PATH_MAX) {
719 	zerr("command too long: %s", arg0);
720 	_exit(1);
721     }
722     for (s = arg0; *s; s++)
723 	if (*s == '/') {
724 	    int lerrno = zexecve(arg0, argv, newenvp);
725 	    if (arg0 == s || unset(PATHDIRS) ||
726 		(arg0[0] == '.' && (arg0 + 1 == s ||
727 				    (arg0[1] == '.' && arg0 + 2 == s)))) {
728 		zerr("%e: %s", lerrno, arg0);
729 		_exit((lerrno == EACCES || lerrno == ENOEXEC) ? 126 : 127);
730 	    }
731 	    break;
732 	}
733 
734     /* for command -p, search the default path */
735     if (defpath) {
736 	char pbuf[PATH_MAX+1];
737 	char *dptr;
738 
739 	if (!search_defpath(arg0, pbuf, PATH_MAX)) {
740 	    if (commandnotfound(arg0, args) == 0)
741 		_realexit();
742 	    zerr("command not found: %s", arg0);
743 	    _exit(127);
744 	}
745 
746 	ee = zexecve(pbuf, argv, newenvp);
747 
748 	if ((dptr = strrchr(pbuf, '/')))
749 	    *dptr = '\0';
750 	if (isgooderr(ee, *pbuf ? pbuf : "/"))
751 	    eno = ee;
752 
753     } else {
754 
755 	if ((cn = (Cmdnam) cmdnamtab->getnode(cmdnamtab, arg0))) {
756 	    char nn[PATH_MAX+1], *dptr;
757 
758 	    if (cn->node.flags & HASHED)
759 		strcpy(nn, cn->u.cmd);
760 	    else {
761 		for (pp = path; pp < cn->u.name; pp++)
762 		    if (!**pp || (**pp == '.' && (*pp)[1] == '\0')) {
763 			ee = zexecve(arg0, argv, newenvp);
764 			if (isgooderr(ee, *pp))
765 			    eno = ee;
766 		    } else if (**pp != '/') {
767 			z = buf;
768 			strucpy(&z, *pp);
769 			*z++ = '/';
770 			strcpy(z, arg0);
771 			ee = zexecve(buf, argv, newenvp);
772 			if (isgooderr(ee, *pp))
773 			    eno = ee;
774 		    }
775 		strcpy(nn, cn->u.name ? *(cn->u.name) : "");
776 		strcat(nn, "/");
777 		strcat(nn, cn->node.nam);
778 	    }
779 	    ee = zexecve(nn, argv, newenvp);
780 
781 	    if ((dptr = strrchr(nn, '/')))
782 		*dptr = '\0';
783 	    if (isgooderr(ee, *nn ? nn : "/"))
784 		eno = ee;
785 	}
786 	for (pp = path; *pp; pp++)
787 	    if (!(*pp)[0] || ((*pp)[0] == '.' && !(*pp)[1])) {
788 		ee = zexecve(arg0, argv, newenvp);
789 		if (isgooderr(ee, *pp))
790 		    eno = ee;
791 	    } else {
792 		z = buf;
793 		strucpy(&z, *pp);
794 		*z++ = '/';
795 		strcpy(z, arg0);
796 		ee = zexecve(buf, argv, newenvp);
797 		if (isgooderr(ee, *pp))
798 		    eno = ee;
799 	    }
800     }
801 
802     if (eno)
803 	zerr("%e: %s", eno, arg0);
804     else if (commandnotfound(arg0, args) == 0)
805 	_realexit();
806     else
807 	zerr("command not found: %s", arg0);
808     _exit((eno == EACCES || eno == ENOEXEC) ? 126 : 127);
809 }
810 
811 #define RET_IF_COM(X) { if (iscom(X)) return docopy ? dupstring(X) : arg0; }
812 
813 /*
814  * Get the full pathname of an external command.
815  * If the second argument is zero, return the first argument if found;
816  * if non-zero, return the path using heap memory.  (RET_IF_COM(X),
817  * above).
818  * If the third argument is non-zero, use the system default path
819  * instead of the current path.
820  */
821 
822 /**/
823 mod_export char *
findcmd(char * arg0,int docopy,int default_path)824 findcmd(char *arg0, int docopy, int default_path)
825 {
826     char **pp;
827     char *z, *s, buf[MAXCMDLEN];
828     Cmdnam cn;
829 
830     if (default_path)
831     {
832 	if (search_defpath(arg0, buf, MAXCMDLEN))
833 	    return docopy ? dupstring(buf) : arg0;
834 	return NULL;
835     }
836     cn = (Cmdnam) cmdnamtab->getnode(cmdnamtab, arg0);
837     if (!cn && isset(HASHCMDS) && !isrelative(arg0))
838 	cn = hashcmd(arg0, path);
839     if ((int) strlen(arg0) > PATH_MAX)
840 	return NULL;
841     if ((s = strchr(arg0, '/'))) {
842 	RET_IF_COM(arg0);
843 	if (arg0 == s || unset(PATHDIRS) || !strncmp(arg0, "./", 2) ||
844 	    !strncmp(arg0, "../", 3)) {
845 	    return NULL;
846 	}
847     }
848     if (cn) {
849 	char nn[PATH_MAX+1];
850 
851 	if (cn->node.flags & HASHED)
852 	    strcpy(nn, cn->u.cmd);
853 	else {
854 	    for (pp = path; pp < cn->u.name; pp++)
855 		if (**pp != '/') {
856 		    z = buf;
857 		    if (**pp) {
858 			strucpy(&z, *pp);
859 			*z++ = '/';
860 		    }
861 		    strcpy(z, arg0);
862 		    RET_IF_COM(buf);
863 		}
864 	    strcpy(nn, cn->u.name ? *(cn->u.name) : "");
865 	    strcat(nn, "/");
866 	    strcat(nn, cn->node.nam);
867 	}
868 	RET_IF_COM(nn);
869     }
870     for (pp = path; *pp; pp++) {
871 	z = buf;
872 	if (**pp) {
873 	    strucpy(&z, *pp);
874 	    *z++ = '/';
875 	}
876 	strcpy(z, arg0);
877 	RET_IF_COM(buf);
878     }
879     return NULL;
880 }
881 
882 /*
883  * Return TRUE if the given path denotes an executable regular file, or a
884  * symlink to one.
885  */
886 
887 /**/
888 int
iscom(char * s)889 iscom(char *s)
890 {
891     struct stat statbuf;
892     char *us = unmeta(s);
893 
894     return (access(us, X_OK) == 0 && stat(us, &statbuf) >= 0 &&
895 	    S_ISREG(statbuf.st_mode));
896 }
897 
898 /**/
899 int
isreallycom(Cmdnam cn)900 isreallycom(Cmdnam cn)
901 {
902     char fullnam[MAXCMDLEN];
903 
904     if (cn->node.flags & HASHED)
905 	strcpy(fullnam, cn->u.cmd);
906     else if (!cn->u.name)
907 	return 0;
908     else {
909 	strcpy(fullnam, *(cn->u.name));
910 	strcat(fullnam, "/");
911 	strcat(fullnam, cn->node.nam);
912     }
913     return iscom(fullnam);
914 }
915 
916 /*
917  * Return TRUE if the given path contains a dot or dot-dot component
918  * and does not start with a slash.
919  */
920 
921 /**/
922 int
isrelative(char * s)923 isrelative(char *s)
924 {
925     if (*s != '/')
926 	return 1;
927     for (; *s; s++)
928 	if (*s == '.' && s[-1] == '/' &&
929 	    (s[1] == '/' || s[1] == '\0' ||
930 	     (s[1] == '.' && (s[2] == '/' || s[2] == '\0'))))
931 	    return 1;
932     return 0;
933 }
934 
935 /**/
936 mod_export Cmdnam
hashcmd(char * arg0,char ** pp)937 hashcmd(char *arg0, char **pp)
938 {
939     Cmdnam cn;
940     char *s, buf[PATH_MAX+1];
941     char **pq;
942 
943     if (*arg0 == '/')
944         return NULL;
945     for (; *pp; pp++)
946 	if (**pp == '/') {
947 	    s = buf;
948 	    struncpy(&s, *pp, PATH_MAX);
949 	    *s++ = '/';
950 	    if ((s - buf) + strlen(arg0) >= PATH_MAX)
951 		continue;
952 	    strcpy(s, arg0);
953 	    if (iscom(buf))
954 		break;
955 	}
956 
957     if (!*pp)
958 	return NULL;
959 
960     cn = (Cmdnam) zshcalloc(sizeof *cn);
961     cn->node.flags = 0;
962     cn->u.name = pp;
963     cmdnamtab->addnode(cmdnamtab, ztrdup(arg0), cn);
964 
965     if (isset(HASHDIRS)) {
966 	for (pq = pathchecked; pq <= pp; pq++)
967 	    hashdir(pq);
968 	pathchecked = pp + 1;
969     }
970 
971     return cn;
972 }
973 
974 /* The value that 'locallevel' had when we forked. When we get back to this
975  * level, the current process (which is a subshell) will terminate.
976  */
977 
978 /**/
979 int
980 forklevel;
981 
982 /* Arguments to entersubsh() */
983 enum {
984     /* Subshell is to be run asynchronously (else synchronously) */
985     ESUB_ASYNC = 0x01,
986     /*
987      * Perform process group and tty handling and clear the
988      * (real) job table, since it won't be any longer valid
989      */
990     ESUB_PGRP = 0x02,
991     /* Don't unset traps */
992     ESUB_KEEPTRAP = 0x04,
993     /* This is only a fake entry to a subshell */
994     ESUB_FAKE = 0x08,
995     /* Release the process group if pid is the shell's process group */
996     ESUB_REVERTPGRP = 0x10,
997     /* Don't handle the MONITOR option even if previously set */
998     ESUB_NOMONITOR = 0x20,
999     /* This is a subshell where job control is allowed */
1000     ESUB_JOB_CONTROL = 0x40
1001 };
1002 
1003 /*
1004  * gleaderp may be NULL.  Otherwise, *gleaderp is set to point to the
1005  * group leader of the job of the new process if this is assigned.  Else
1006  * it is left alone: it is initialised to -1.
1007  */
1008 
1009 /**/
1010 static void
entersubsh(int flags,struct entersubsh_ret * retp)1011 entersubsh(int flags, struct entersubsh_ret *retp)
1012 {
1013     int i, sig, monitor, job_control_ok;
1014 
1015     if (!(flags & ESUB_KEEPTRAP))
1016 	for (sig = 0; sig < SIGCOUNT; sig++)
1017 	    if (!(sigtrapped[sig] & ZSIG_FUNC))
1018 		unsettrap(sig);
1019     monitor = isset(MONITOR);
1020     job_control_ok = monitor && (flags & ESUB_JOB_CONTROL) && isset(POSIXJOBS);
1021     exit_val = 0; 		/* parent exit status is irrelevant */
1022     if (flags & ESUB_NOMONITOR)
1023 	opts[MONITOR] = 0;
1024     if (!isset(MONITOR)) {
1025 	if (flags & ESUB_ASYNC) {
1026 	    settrap(SIGINT, NULL, 0);
1027 	    settrap(SIGQUIT, NULL, 0);
1028 	    if (isatty(0)) {
1029 		close(0);
1030 		if (open("/dev/null", O_RDWR | O_NOCTTY)) {
1031 		    zerr("can't open /dev/null: %e", errno);
1032 		    _exit(1);
1033 		}
1034 	    }
1035 	}
1036     } else if (thisjob != -1 && (flags & ESUB_PGRP)) {
1037 	if (jobtab[list_pipe_job].gleader && (list_pipe || list_pipe_child)) {
1038 	    if (setpgrp(0L, jobtab[list_pipe_job].gleader) == -1 ||
1039 		killpg(jobtab[list_pipe_job].gleader, 0) == -1) {
1040 		jobtab[list_pipe_job].gleader =
1041 		    jobtab[thisjob].gleader = (list_pipe_child ? mypgrp : getpid());
1042 		setpgrp(0L, jobtab[list_pipe_job].gleader);
1043 		if (!(flags & ESUB_ASYNC))
1044 		    attachtty(jobtab[thisjob].gleader);
1045 	    }
1046 	    if (retp && !(flags & ESUB_ASYNC)) {
1047 		retp->gleader = jobtab[list_pipe_job].gleader;
1048 		retp->list_pipe_job = list_pipe_job;
1049 	    }
1050 	}
1051 	else if (!jobtab[thisjob].gleader ||
1052 		 setpgrp(0L, jobtab[thisjob].gleader) == -1) {
1053 	    /*
1054 	     * This is the standard point at which a newly started
1055 	     * process gets put into the foreground by taking over
1056 	     * the terminal.  Note that in normal circumstances we do
1057 	     * this only from the process itself.  This only works if
1058 	     * we are still ignoring SIGTTOU at this point; in this
1059 	     * case ignoring the signal has the special effect that
1060 	     * the operation is allowed to work (in addition to not
1061 	     * causing the shell to be suspended).
1062 	     */
1063 	    jobtab[thisjob].gleader = getpid();
1064 	    if (list_pipe_job != thisjob &&
1065 		!jobtab[list_pipe_job].gleader)
1066 		jobtab[list_pipe_job].gleader = jobtab[thisjob].gleader;
1067 	    setpgrp(0L, jobtab[thisjob].gleader);
1068 	    if (!(flags & ESUB_ASYNC)) {
1069 		attachtty(jobtab[thisjob].gleader);
1070 		if (retp) {
1071 		    retp->gleader = jobtab[thisjob].gleader;
1072 		    if (list_pipe_job != thisjob)
1073 			retp->list_pipe_job = list_pipe_job;
1074 		}
1075 	    }
1076 	}
1077     }
1078     if (!(flags & ESUB_FAKE))
1079 	subsh = 1;
1080     /*
1081      * Increment the visible parameter ZSH_SUBSHELL even if this
1082      * is a fake subshell because we are exec'ing at the end.
1083      * Logically this should be equivalent to a real subshell so
1084      * we don't hang out the dirty washing.
1085      */
1086     zsh_subshell++;
1087     if ((flags & ESUB_REVERTPGRP) && getpid() == mypgrp)
1088 	release_pgrp();
1089     shout = NULL;
1090     if (flags & ESUB_NOMONITOR) {
1091 	/*
1092 	 * Allowing any form of interactive signalling here is
1093 	 * actively harmful as we are in a context where there is no
1094 	 * control over the process.
1095 	 */
1096 	signal_ignore(SIGTTOU);
1097 	signal_ignore(SIGTTIN);
1098 	signal_ignore(SIGTSTP);
1099     } else if (!job_control_ok) {
1100 	/*
1101 	 * If this process is not going to be doing job control,
1102 	 * we don't want to do special things with the corresponding
1103 	 * signals.  If it is, we need to keep the special behaviour:
1104 	 * see note about attachtty() above.
1105 	 */
1106 	signal_default(SIGTTOU);
1107 	signal_default(SIGTTIN);
1108 	signal_default(SIGTSTP);
1109     }
1110     if (interact) {
1111 	signal_default(SIGTERM);
1112 	if (!(sigtrapped[SIGINT] & ZSIG_IGNORED))
1113 	    signal_default(SIGINT);
1114 	if (!(sigtrapped[SIGPIPE]))
1115 	    signal_default(SIGPIPE);
1116     }
1117     if (!(sigtrapped[SIGQUIT] & ZSIG_IGNORED))
1118 	signal_default(SIGQUIT);
1119     /*
1120      * sigtrapped[sig] == ZSIG_IGNORED for signals that remain ignored,
1121      * but other trapped signals are temporarily blocked when intrap,
1122      * and must be unblocked before continuing into the subshell.  This
1123      * is orthogonal to what the default handler for the signal may be.
1124      *
1125      * Start loop at 1 because 0 is SIGEXIT
1126      */
1127     if (intrap)
1128 	for (sig = 1; sig < SIGCOUNT; sig++)
1129 	    if (sigtrapped[sig] && sigtrapped[sig] != ZSIG_IGNORED)
1130 		signal_unblock(signal_mask(sig));
1131     if (!job_control_ok)
1132 	opts[MONITOR] = 0;
1133     opts[USEZLE] = 0;
1134     zleactive = 0;
1135     /*
1136      * If we've saved fd's for later restoring, we're never going
1137      * to restore them now, so just close them.
1138      */
1139     for (i = 10; i <= max_zsh_fd; i++) {
1140 	if (fdtable[i] & FDT_SAVED_MASK)
1141 	    zclose(i);
1142     }
1143     if (flags & ESUB_PGRP)
1144 	clearjobtab(monitor);
1145     get_usage();
1146     forklevel = locallevel;
1147 }
1148 
1149 /* execute a string */
1150 
1151 /**/
1152 mod_export void
execstring(char * s,int dont_change_job,int exiting,char * context)1153 execstring(char *s, int dont_change_job, int exiting, char *context)
1154 {
1155     Eprog prog;
1156 
1157     pushheap();
1158     if (isset(VERBOSE)) {
1159 	zputs(s, stderr);
1160 	fputc('\n', stderr);
1161 	fflush(stderr);
1162     }
1163     if ((prog = parse_string(s, 0)))
1164 	execode(prog, dont_change_job, exiting, context);
1165     popheap();
1166 }
1167 
1168 /**/
1169 mod_export void
execode(Eprog p,int dont_change_job,int exiting,char * context)1170 execode(Eprog p, int dont_change_job, int exiting, char *context)
1171 {
1172     struct estate s;
1173     static int zsh_eval_context_len;
1174     int alen;
1175 
1176     if (!zsh_eval_context_len) {
1177 	zsh_eval_context_len = 16;
1178 	alen = 0;
1179 	zsh_eval_context = (char **)zalloc(zsh_eval_context_len *
1180 					   sizeof(*zsh_eval_context));
1181     } else {
1182 	alen = arrlen(zsh_eval_context);
1183 	if (zsh_eval_context_len == alen + 1) {
1184 	    zsh_eval_context_len *= 2;
1185 	    zsh_eval_context = zrealloc(zsh_eval_context,
1186 					zsh_eval_context_len *
1187 					sizeof(*zsh_eval_context));
1188 	}
1189     }
1190     zsh_eval_context[alen] = context;
1191     zsh_eval_context[alen+1] = NULL;
1192 
1193     s.prog = p;
1194     s.pc = p->prog;
1195     s.strs = p->strs;
1196     useeprog(p);		/* Mark as in use */
1197 
1198     execlist(&s, dont_change_job, exiting);
1199 
1200     freeeprog(p);		/* Free if now unused */
1201 
1202     /*
1203      * zsh_eval_context may have been altered by a recursive
1204      * call, but that's OK since we're using the global value.
1205      */
1206     zsh_eval_context[alen] = NULL;
1207 }
1208 
1209 /* Execute a simplified command. This is used to execute things that
1210  * will run completely in the shell, so that we can by-pass all that
1211  * nasty job-handling and redirection stuff in execpline and execcmd. */
1212 
1213 /**/
1214 static int
execsimple(Estate state)1215 execsimple(Estate state)
1216 {
1217     wordcode code = *state->pc++;
1218     int lv, otj;
1219 
1220     if (errflag)
1221 	return (lastval = 1);
1222 
1223     if (!isset(EXECOPT))
1224 	return lastval = 0;
1225 
1226     /* In evaluated traps, don't modify the line number. */
1227     if (!IN_EVAL_TRAP() && !ineval && code)
1228 	lineno = code - 1;
1229 
1230     code = wc_code(*state->pc++);
1231 
1232     /*
1233      * Because we're bypassing job control, ensure the called
1234      * code doesn't see the current job.
1235      */
1236     otj = thisjob;
1237     thisjob = -1;
1238 
1239     if (code == WC_ASSIGN) {
1240 	cmdoutval = 0;
1241 	addvars(state, state->pc - 1, 0);
1242 	setunderscore("");
1243 	if (isset(XTRACE)) {
1244 	    fputc('\n', xtrerr);
1245 	    fflush(xtrerr);
1246 	}
1247 	lv = (errflag ? errflag : cmdoutval);
1248     } else {
1249 	int q = queue_signal_level();
1250 	dont_queue_signals();
1251 	if (code == WC_FUNCDEF)
1252 	    lv = execfuncdef(state, NULL);
1253 	else
1254 	    lv = (execfuncs[code - WC_CURSH])(state, 0);
1255 	restore_queue_signals(q);
1256     }
1257 
1258     thisjob = otj;
1259 
1260     return lastval = lv;
1261 }
1262 
1263 /* Main routine for executing a list.                                *
1264  * exiting means that the (sub)shell we are in is a definite goner   *
1265  * after the current list is finished, so we may be able to exec the *
1266  * last command directly instead of forking.  If dont_change_job is  *
1267  * nonzero, then restore the current job number after executing the  *
1268  * list.                                                             */
1269 
1270 /**/
1271 void
execlist(Estate state,int dont_change_job,int exiting)1272 execlist(Estate state, int dont_change_job, int exiting)
1273 {
1274     static int donetrap;
1275     Wordcode next;
1276     wordcode code;
1277     int ret, cj, csp, ltype;
1278     int old_pline_level, old_list_pipe, old_list_pipe_job;
1279     char *old_list_pipe_text;
1280     zlong oldlineno;
1281     /*
1282      * ERREXIT only forces the shell to exit if the last command in a &&
1283      * or || fails.  This is the case even if an earlier command is a
1284      * shell function or other current shell structure, so we have to set
1285      * noerrexit here if the sublist is not of type END.
1286      */
1287     int oldnoerrexit = noerrexit;
1288 
1289     queue_signals();
1290 
1291     cj = thisjob;
1292     old_pline_level = pline_level;
1293     old_list_pipe = list_pipe;
1294     old_list_pipe_job = list_pipe_job;
1295     if (*list_pipe_text)
1296 	old_list_pipe_text = ztrdup(list_pipe_text);
1297     else
1298 	old_list_pipe_text = NULL;
1299     oldlineno = lineno;
1300 
1301     if (sourcelevel && unset(SHINSTDIN)) {
1302 	pline_level = list_pipe = list_pipe_job = 0;
1303 	*list_pipe_text = '\0';
1304     }
1305 
1306     /* Loop over all sets of comands separated by newline, *
1307      * semi-colon or ampersand (`sublists').               */
1308     code = *state->pc++;
1309     if (wc_code(code) != WC_LIST) {
1310 	/* Empty list; this returns status zero. */
1311 	lastval = 0;
1312     }
1313     while (wc_code(code) == WC_LIST && !breaks && !retflag && !errflag) {
1314 	int donedebug;
1315 	int this_donetrap = 0;
1316 	this_noerrexit = 0;
1317 
1318 	ltype = WC_LIST_TYPE(code);
1319 	csp = cmdsp;
1320 
1321 	if (!IN_EVAL_TRAP() && !ineval) {
1322 	    /*
1323 	     * Ensure we have a valid line number for debugging,
1324 	     * unless we are in an evaluated trap in which case
1325 	     * we retain the line number from the context.
1326 	     * This was added for DEBUGBEFORECMD but I've made
1327 	     * it unconditional to keep dependencies to a minimum.
1328 	     *
1329 	     * The line number is updated for individual pipelines.
1330 	     * This isn't necessary for debug traps since they only
1331 	     * run once per sublist.
1332 	     */
1333 	    wordcode code2 = *state->pc, lnp1 = 0;
1334 	    if (ltype & Z_SIMPLE) {
1335 		lnp1 = code2;
1336 	    } else if (wc_code(code2) == WC_SUBLIST) {
1337 		if (WC_SUBLIST_FLAGS(code2) == WC_SUBLIST_SIMPLE)
1338 		    lnp1 = state->pc[1];
1339 		else
1340 		    lnp1 = WC_PIPE_LINENO(state->pc[1]);
1341 	    }
1342 	    if (lnp1)
1343 		lineno = lnp1 - 1;
1344 	}
1345 
1346 	if (sigtrapped[SIGDEBUG] && isset(DEBUGBEFORECMD) && !intrap) {
1347 	    Wordcode pc2 = state->pc;
1348 	    int oerrexit_opt = opts[ERREXIT];
1349 	    Param pm;
1350 	    opts[ERREXIT] = 0;
1351 	    noerrexit = NOERREXIT_EXIT | NOERREXIT_RETURN;
1352 	    if (ltype & Z_SIMPLE) /* skip the line number */
1353 		pc2++;
1354 	    pm = assignsparam("ZSH_DEBUG_CMD",
1355 			      getpermtext(state->prog, pc2, 0),
1356 			      0);
1357 
1358 	    exiting = donetrap;
1359 	    ret = lastval;
1360 	    dotrap(SIGDEBUG);
1361 	    if (!retflag)
1362 		lastval = ret;
1363 	    donetrap = exiting;
1364 	    noerrexit = oldnoerrexit;
1365 	    /*
1366 	     * Only execute the trap once per sublist, even
1367 	     * if the DEBUGBEFORECMD option changes.
1368 	     */
1369 	    donedebug = isset(ERREXIT) ? 2 : 1;
1370 	    opts[ERREXIT] = oerrexit_opt;
1371 	    if (pm)
1372 		unsetparam_pm(pm, 0, 1);
1373 	} else
1374 	    donedebug = intrap ? 1 : 0;
1375 
1376 	/* Reset donetrap:  this ensures that a trap is only *
1377 	 * called once for each sublist that fails.          */
1378 	donetrap = 0;
1379 	if (ltype & Z_SIMPLE) {
1380 	    next = state->pc + WC_LIST_SKIP(code);
1381 	    if (donedebug != 2)
1382 		execsimple(state);
1383 	    state->pc = next;
1384 	    goto sublist_done;
1385 	}
1386 
1387 	/* Loop through code followed by &&, ||, or end of sublist. */
1388 	code = *state->pc++;
1389 	if (donedebug == 2) {
1390 	    /* Skip sublist. */
1391 	    while (wc_code(code) == WC_SUBLIST) {
1392 		state->pc = state->pc + WC_SUBLIST_SKIP(code);
1393 		if (WC_SUBLIST_TYPE(code) == WC_SUBLIST_END)
1394 		    break;
1395 		code = *state->pc++;
1396 	    }
1397 	    donetrap = 1;
1398 	    /* yucky but consistent... */
1399 	    goto sublist_done;
1400 	}
1401 	while (wc_code(code) == WC_SUBLIST) {
1402 	    int isend = (WC_SUBLIST_TYPE(code) == WC_SUBLIST_END);
1403 	    next = state->pc + WC_SUBLIST_SKIP(code);
1404 	    if (!oldnoerrexit)
1405 		noerrexit = isend ? 0 : NOERREXIT_EXIT | NOERREXIT_RETURN;
1406 	    if (WC_SUBLIST_FLAGS(code) & WC_SUBLIST_NOT) {
1407 		/* suppress errexit for "! this_command" */
1408 		if (isend)
1409 		    this_noerrexit = 1;
1410 		/* suppress errexit for ! <list-of-shell-commands> */
1411 		noerrexit = NOERREXIT_EXIT | NOERREXIT_RETURN;
1412 	    }
1413 	    switch (WC_SUBLIST_TYPE(code)) {
1414 	    case WC_SUBLIST_END:
1415 		/* End of sublist; just execute, ignoring status. */
1416 		if (WC_SUBLIST_FLAGS(code) & WC_SUBLIST_SIMPLE)
1417 		    execsimple(state);
1418 		else
1419 		    execpline(state, code, ltype, (ltype & Z_END) && exiting);
1420 		state->pc = next;
1421 		goto sublist_done;
1422 		break;
1423 	    case WC_SUBLIST_AND:
1424 		/* If the return code is non-zero, we skip pipelines until *
1425 		 * we find a sublist followed by ORNEXT.                   */
1426 		if ((ret = ((WC_SUBLIST_FLAGS(code) & WC_SUBLIST_SIMPLE) ?
1427 			    execsimple(state) :
1428 			    execpline(state, code, Z_SYNC, 0)))) {
1429 		    state->pc = next;
1430 		    code = *state->pc++;
1431 		    next = state->pc + WC_SUBLIST_SKIP(code);
1432 		    while (wc_code(code) == WC_SUBLIST &&
1433 			   WC_SUBLIST_TYPE(code) == WC_SUBLIST_AND) {
1434 			state->pc = next;
1435 			code = *state->pc++;
1436 			next = state->pc + WC_SUBLIST_SKIP(code);
1437 		    }
1438 		    if (wc_code(code) != WC_SUBLIST) {
1439 			/* We've skipped to the end of the list, not executing *
1440 			 * the final pipeline, so don't perform error handling *
1441 			 * for this sublist.                                   */
1442 			this_donetrap = 1;
1443 			goto sublist_done;
1444 		    } else if (WC_SUBLIST_TYPE(code) == WC_SUBLIST_END) {
1445 			this_donetrap = 1;
1446 			/*
1447 			 * Treat this in the same way as if we reached
1448 			 * the end of the sublist normally.
1449 			 */
1450 			state->pc = next;
1451 			goto sublist_done;
1452 		    }
1453 		}
1454 		cmdpush(CS_CMDAND);
1455 		break;
1456 	    case WC_SUBLIST_OR:
1457 		/* If the return code is zero, we skip pipelines until *
1458 		 * we find a sublist followed by ANDNEXT.              */
1459 		if (!(ret = ((WC_SUBLIST_FLAGS(code) & WC_SUBLIST_SIMPLE) ?
1460 			     execsimple(state) :
1461 			     execpline(state, code, Z_SYNC, 0)))) {
1462 		    state->pc = next;
1463 		    code = *state->pc++;
1464 		    next = state->pc + WC_SUBLIST_SKIP(code);
1465 		    while (wc_code(code) == WC_SUBLIST &&
1466 			   WC_SUBLIST_TYPE(code) == WC_SUBLIST_OR) {
1467 			state->pc = next;
1468 			code = *state->pc++;
1469 			next = state->pc + WC_SUBLIST_SKIP(code);
1470 		    }
1471 		    if (wc_code(code) != WC_SUBLIST) {
1472 			/* We've skipped to the end of the list, not executing *
1473 			 * the final pipeline, so don't perform error handling *
1474 			 * for this sublist.                                   */
1475 			this_donetrap = 1;
1476 			goto sublist_done;
1477 		    } else if (WC_SUBLIST_TYPE(code) == WC_SUBLIST_END) {
1478 			this_donetrap = 1;
1479 			/*
1480 			 * Treat this in the same way as if we reached
1481 			 * the end of the sublist normally.
1482 			 */
1483 			state->pc = next;
1484 			goto sublist_done;
1485 		    }
1486 		}
1487 		cmdpush(CS_CMDOR);
1488 		break;
1489 	    }
1490 	    state->pc = next;
1491 	    code = *state->pc++;
1492 	}
1493 	state->pc--;
1494 sublist_done:
1495 
1496 	/*
1497 	 * See hairy code near the end of execif() for the
1498 	 * following.  "noerrexit " only applies until
1499 	 * we hit execcmd on the way down.  We're now
1500 	 * on the way back up, so don't restore it.
1501 	 */
1502 	if (!(oldnoerrexit & NOERREXIT_UNTIL_EXEC))
1503 	    noerrexit = oldnoerrexit;
1504 
1505 	if (sigtrapped[SIGDEBUG] && !isset(DEBUGBEFORECMD) && !donedebug) {
1506 	    /*
1507 	     * Save and restore ERREXIT for consistency with
1508 	     * DEBUGBEFORECMD, even though it's not used.
1509 	     */
1510 	    int oerrexit_opt = opts[ERREXIT];
1511 	    opts[ERREXIT] = 0;
1512 	    noerrexit = NOERREXIT_EXIT | NOERREXIT_RETURN;
1513 	    exiting = donetrap;
1514 	    ret = lastval;
1515 	    dotrap(SIGDEBUG);
1516 	    if (!retflag)
1517 		lastval = ret;
1518 	    donetrap = exiting;
1519 	    noerrexit = oldnoerrexit;
1520 	    opts[ERREXIT] = oerrexit_opt;
1521 	}
1522 
1523 	cmdsp = csp;
1524 
1525 	/* Check whether we are suppressing traps/errexit *
1526 	 * (typically in init scripts) and if we haven't  *
1527 	 * already performed them for this sublist.       */
1528 	if (!this_noerrexit && !donetrap && !this_donetrap) {
1529 	    if (sigtrapped[SIGZERR] && lastval &&
1530 		!(noerrexit & NOERREXIT_EXIT)) {
1531 		dotrap(SIGZERR);
1532 		donetrap = 1;
1533 	    }
1534 	    if (lastval) {
1535 		int errreturn = isset(ERRRETURN) &&
1536 		    (isset(INTERACTIVE) || locallevel || sourcelevel) &&
1537 		    !(noerrexit & NOERREXIT_RETURN);
1538 		int errexit = (isset(ERREXIT) ||
1539 			       (isset(ERRRETURN) && !errreturn)) &&
1540 		    !(noerrexit & NOERREXIT_EXIT);
1541 		if (errexit) {
1542 		    if (sigtrapped[SIGEXIT])
1543 			dotrap(SIGEXIT);
1544 		    if (mypid != getpid())
1545 			_realexit();
1546 		    else
1547 			realexit();
1548 		}
1549 		if (errreturn) {
1550 		    retflag = 1;
1551 		    breaks = loops;
1552 		}
1553 	    }
1554 	}
1555 	if (ltype & Z_END)
1556 	    break;
1557 	code = *state->pc++;
1558     }
1559     pline_level = old_pline_level;
1560     list_pipe = old_list_pipe;
1561     list_pipe_job = old_list_pipe_job;
1562     if (old_list_pipe_text) {
1563 	strcpy(list_pipe_text, old_list_pipe_text);
1564 	zsfree(old_list_pipe_text);
1565     } else {
1566 	*list_pipe_text = '\0';
1567     }
1568     lineno = oldlineno;
1569     if (dont_change_job)
1570 	thisjob = cj;
1571 
1572     if (exiting && sigtrapped[SIGEXIT]) {
1573 	dotrap(SIGEXIT);
1574 	/* Make sure this doesn't get executed again. */
1575 	sigtrapped[SIGEXIT] = 0;
1576     }
1577 
1578     unqueue_signals();
1579 }
1580 
1581 /* Execute a pipeline.                                                *
1582  * last1 is a flag that this command is the last command in a shell   *
1583  * that is about to exit, so we can exec instead of forking.  It gets *
1584  * passed all the way down to execcmd() which actually makes the      *
1585  * decision.  A 0 is always passed if the command is not the last in  *
1586  * the pipeline.  This function assumes that the sublist is not NULL. *
1587  * If last1 is zero but the command is at the end of a pipeline, we   *
1588  * pass 2 down to execcmd().                                          *
1589  */
1590 
1591 /**/
1592 static int
execpline(Estate state,wordcode slcode,int how,int last1)1593 execpline(Estate state, wordcode slcode, int how, int last1)
1594 {
1595     int ipipe[2], opipe[2];
1596     int pj, newjob;
1597     int old_simple_pline = simple_pline;
1598     int slflags = WC_SUBLIST_FLAGS(slcode);
1599     wordcode code = *state->pc++;
1600     static int lastwj, lpforked;
1601 
1602     if (wc_code(code) != WC_PIPE)
1603 	return lastval = (slflags & WC_SUBLIST_NOT) != 0;
1604     else if (slflags & WC_SUBLIST_NOT)
1605 	last1 = 0;
1606 
1607     /* If trap handlers are allowed to run here, they may start another
1608      * external job in the middle of us starting this one, which can
1609      * result in jobs being reaped before their job table entries have
1610      * been initialized, which in turn leads to waiting forever for
1611      * jobs that no longer exist.  So don't do that.
1612      */
1613     queue_signals();
1614 
1615     pj = thisjob;
1616     ipipe[0] = ipipe[1] = opipe[0] = opipe[1] = 0;
1617     child_block();
1618 
1619     /*
1620      * Get free entry in job table and initialize it.  This is currently
1621      * the only call to initjob() (apart from a minor exception in
1622      * clearjobtab()), so this is also the only place where we can
1623      * expand the job table under us.
1624      */
1625     if ((thisjob = newjob = initjob()) == -1) {
1626 	child_unblock();
1627 	unqueue_signals();
1628 	return 1;
1629     }
1630     if (how & Z_TIMED)
1631 	jobtab[thisjob].stat |= STAT_TIMED;
1632 
1633     if (slflags & WC_SUBLIST_COPROC) {
1634 	how = Z_ASYNC;
1635 	if (coprocin >= 0) {
1636 	    zclose(coprocin);
1637 	    zclose(coprocout);
1638 	}
1639 	if (mpipe(ipipe) < 0) {
1640 	    coprocin = coprocout = -1;
1641 	    slflags &= ~WC_SUBLIST_COPROC;
1642 	} else if (mpipe(opipe) < 0) {
1643 	    close(ipipe[0]);
1644 	    close(ipipe[1]);
1645 	    coprocin = coprocout = -1;
1646 	    slflags &= ~WC_SUBLIST_COPROC;
1647 	} else {
1648 	    coprocin = ipipe[0];
1649 	    coprocout = opipe[1];
1650 	    fdtable[coprocin] = fdtable[coprocout] = FDT_UNUSED;
1651 	}
1652     }
1653     /* This used to set list_pipe_pid=0 unconditionally, but in things
1654      * like `ls|if true; then sleep 20; cat; fi' where the sleep was
1655      * stopped, the top-level execpline() didn't get the pid for the
1656      * sub-shell because it was overwritten. */
1657     if (!pline_level++) {
1658         list_pipe_pid = 0;
1659 	nowait = 0;
1660 	simple_pline = (WC_PIPE_TYPE(code) == WC_PIPE_END);
1661 	list_pipe_job = newjob;
1662     }
1663     lastwj = lpforked = 0;
1664     execpline2(state, code, how, opipe[0], ipipe[1], last1);
1665     pline_level--;
1666     if (how & Z_ASYNC) {
1667 	lastwj = newjob;
1668 
1669         if (thisjob == list_pipe_job)
1670             list_pipe_job = 0;
1671 	jobtab[thisjob].stat |= STAT_NOSTTY;
1672 	if (slflags & WC_SUBLIST_COPROC) {
1673 	    zclose(ipipe[1]);
1674 	    zclose(opipe[0]);
1675 	}
1676 	if (how & Z_DISOWN) {
1677 	    pipecleanfilelist(jobtab[thisjob].filelist, 0);
1678 	    deletejob(jobtab + thisjob, 1);
1679 	    thisjob = -1;
1680 	}
1681 	else
1682 	    spawnjob();
1683 	child_unblock();
1684 	unqueue_signals();
1685 	/* Executing background code resets shell status */
1686 	return lastval = 0;
1687     } else {
1688 	if (newjob != lastwj) {
1689 	    Job jn = jobtab + newjob;
1690 	    int updated;
1691 
1692 	    if (newjob == list_pipe_job && list_pipe_child)
1693 		_exit(0);
1694 
1695 	    lastwj = thisjob = newjob;
1696 
1697 	    if (list_pipe || (pline_level && !(how & Z_TIMED) &&
1698 			      !(jn->stat & STAT_NOSTTY)))
1699 		jn->stat |= STAT_NOPRINT;
1700 
1701 	    if (nowait) {
1702 		if(!pline_level) {
1703 		    int jobsub;
1704 		    struct process *pn, *qn;
1705 
1706 		    curjob = newjob;
1707 		    DPUTS(!list_pipe_pid, "invalid list_pipe_pid");
1708 		    addproc(list_pipe_pid, list_pipe_text, 0,
1709 			    &list_pipe_start, -1, -1);
1710 
1711 		    /* If the super-job contains only the sub-shell, the
1712 		       sub-shell is the group leader. */
1713 		    if (!jn->procs->next || lpforked == 2) {
1714 			jn->gleader = list_pipe_pid;
1715 			jn->stat |= STAT_SUBLEADER;
1716 			/*
1717 			 * Pick up any subjob that's still lying around
1718 			 * as it's now our responsibility.
1719 			 * If we find it we're a SUPERJOB.
1720 			 */
1721 			for (jobsub = 1; jobsub <= maxjob; jobsub++) {
1722 			    Job jnsub = jobtab + jobsub;
1723 			    if (jnsub->stat & STAT_SUBJOB_ORPHANED) {
1724 				jn->other = jobsub;
1725 				jn->stat |= STAT_SUPERJOB;
1726 				jnsub->stat &= ~STAT_SUBJOB_ORPHANED;
1727 				jnsub->other = list_pipe_pid;
1728 			    }
1729 			}
1730 		    }
1731 		    for (pn = jobtab[jn->other].procs; pn; pn = pn->next)
1732 			if (WIFSTOPPED(pn->status))
1733 			    break;
1734 
1735 		    if (pn) {
1736 			for (qn = jn->procs; qn->next; qn = qn->next);
1737 			qn->status = pn->status;
1738 		    }
1739 
1740 		    jn->stat &= ~(STAT_DONE | STAT_NOPRINT);
1741 		    jn->stat |= STAT_STOPPED | STAT_CHANGED | STAT_LOCKED |
1742 			STAT_INUSE;
1743 		    printjob(jn, !!isset(LONGLISTJOBS), 1);
1744 		}
1745 		else if (newjob != list_pipe_job)
1746 		    deletejob(jn, 0);
1747 		else
1748 		    lastwj = -1;
1749 	    }
1750 
1751 	    errbrk_saved = 0;
1752 	    for (; !nowait;) {
1753 		if (list_pipe_child) {
1754 		    jn->stat |= STAT_NOPRINT;
1755 		    makerunning(jn);
1756 		}
1757 		if (!(jn->stat & STAT_LOCKED)) {
1758 		    updated = hasprocs(thisjob);
1759 		    waitjobs();		/* deals with signal queue */
1760 		    child_block();
1761 		} else
1762 		    updated = 0;
1763 		if (!updated &&
1764 		    list_pipe_job && hasprocs(list_pipe_job) &&
1765 		    !(jobtab[list_pipe_job].stat & STAT_STOPPED)) {
1766 		    int q = queue_signal_level();
1767 		    child_unblock();
1768 		    child_block();
1769 		    dont_queue_signals();
1770 		    restore_queue_signals(q);
1771 		}
1772 		if (list_pipe_child &&
1773 		    jn->stat & STAT_DONE &&
1774 		    lastval2 & 0200)
1775 		    killpg(mypgrp, lastval2 & ~0200);
1776 		if (!list_pipe_child && !lpforked && !subsh && jobbing &&
1777 		    (list_pipe || last1 || pline_level) &&
1778 		    ((jn->stat & STAT_STOPPED) ||
1779 		     (list_pipe_job && pline_level &&
1780 		      (jobtab[list_pipe_job].stat & STAT_STOPPED)))) {
1781 		    pid_t pid = 0;
1782 		    int synch[2];
1783 		    struct timeval bgtime;
1784 
1785 		    /*
1786 		     * A pipeline with the shell handling the right
1787 		     * hand side was stopped.  We'll fork to allow
1788 		     * it to continue.
1789 		     */
1790 		    if (pipe(synch) < 0 || (pid = zfork(&bgtime)) == -1) {
1791 			/* Failure */
1792 			if (pid < 0) {
1793 			    close(synch[0]);
1794 			    close(synch[1]);
1795 			} else
1796 			    zerr("pipe failed: %e", errno);
1797 			zleentry(ZLE_CMD_TRASH);
1798 			fprintf(stderr, "zsh: job can't be suspended\n");
1799 			fflush(stderr);
1800 			makerunning(jn);
1801 			killjb(jn, SIGCONT);
1802 			thisjob = newjob;
1803 		    }
1804 		    else if (pid) {
1805 			/*
1806 			 * Parent: job control is here.  If the job
1807 			 * started for the RHS of the pipeline is still
1808 			 * around, then its a SUBJOB and the job for
1809 			 * earlier parts of the pipeeline is its SUPERJOB.
1810 			 * The newly forked shell isn't recorded as a
1811 			 * separate job here, just as list_pipe_pid.
1812 			 * If the superjob exits (it may already have
1813 			 * done so, see child branch below), we'll use
1814 			 * list_pipe_pid to form the basis of a
1815 			 * replacement job --- see SUBLEADER code above.
1816 			 */
1817 			char dummy;
1818 
1819 			lpforked =
1820 			    (killpg(jobtab[list_pipe_job].gleader, 0) == -1 ? 2 : 1);
1821 			list_pipe_pid = pid;
1822 			list_pipe_start = bgtime;
1823 			nowait = 1;
1824 			errflag |= ERRFLAG_ERROR;
1825 			breaks = loops;
1826 			close(synch[1]);
1827 			read_loop(synch[0], &dummy, 1);
1828 			close(synch[0]);
1829 			/* If this job has finished, we leave it as a
1830 			 * normal (non-super-) job. */
1831 			if (!(jn->stat & STAT_DONE)) {
1832 			    jobtab[list_pipe_job].other = newjob;
1833 			    jobtab[list_pipe_job].stat |= STAT_SUPERJOB;
1834 			    jn->stat |= STAT_SUBJOB | STAT_NOPRINT;
1835 			    jn->other = list_pipe_pid;	/* see zsh.h */
1836 			    if (hasprocs(list_pipe_job))
1837 				jn->gleader = jobtab[list_pipe_job].gleader;
1838 			}
1839 			if ((list_pipe || last1) && hasprocs(list_pipe_job))
1840 			    killpg(jobtab[list_pipe_job].gleader, SIGSTOP);
1841 			break;
1842 		    }
1843 		    else {
1844 			close(synch[0]);
1845 			entersubsh(ESUB_ASYNC, NULL);
1846 			/*
1847 			 * At this point, we used to attach this process
1848 			 * to the process group of list_pipe_job (the
1849 			 * new superjob) any time that was still available.
1850 			 * That caused problems in at least two
1851 			 * cases because this forked shell was then
1852 			 * suspended with the right hand side of the
1853 			 * pipeline, and the SIGSTOP below suspended
1854 			 * it a second time when it was continued.
1855 			 *
1856 			 * It's therefore not clear entirely why you'd ever
1857 			 * do anything other than the following, but no
1858 			 * doubt we'll find out...
1859 			 */
1860 			setpgrp(0L, mypgrp = getpid());
1861 			close(synch[1]);
1862 			kill(getpid(), SIGSTOP);
1863 			list_pipe = 0;
1864 			list_pipe_child = 1;
1865 			opts[INTERACTIVE] = 0;
1866 			if (errbrk_saved) {
1867 			    /*
1868 			     * Keep any user interrupt bit in errflag.
1869 			     */
1870 			    errflag = prev_errflag | (errflag & ERRFLAG_INT);
1871 			    breaks = prev_breaks;
1872 			}
1873 			break;
1874 		    }
1875 		}
1876 		else if (subsh && jn->stat & STAT_STOPPED)
1877 		    thisjob = newjob;
1878 		else
1879 		    break;
1880 	    }
1881 	    child_unblock();
1882 	    unqueue_signals();
1883 
1884 	    if (list_pipe && (lastval & 0200) && pj >= 0 &&
1885 		(!(jn->stat & STAT_INUSE) || (jn->stat & STAT_DONE))) {
1886 		deletejob(jn, 0);
1887 		jn = jobtab + pj;
1888 		if (jn->gleader)
1889 		    killjb(jn, lastval & ~0200);
1890 	    }
1891 	    if (list_pipe_child ||
1892 		((jn->stat & STAT_DONE) &&
1893 		 (list_pipe || (pline_level && !(jn->stat & STAT_SUBJOB)))))
1894 		deletejob(jn, 0);
1895 	    thisjob = pj;
1896 	}
1897 	else
1898 	    unqueue_signals();
1899 	if ((slflags & WC_SUBLIST_NOT) && !errflag)
1900 	    lastval = !lastval;
1901     }
1902     if (!pline_level)
1903 	simple_pline = old_simple_pline;
1904     return lastval;
1905 }
1906 
1907 /* execute pipeline.  This function assumes the `pline' is not NULL. */
1908 
1909 /**/
1910 static void
execpline2(Estate state,wordcode pcode,int how,int input,int output,int last1)1911 execpline2(Estate state, wordcode pcode,
1912 	   int how, int input, int output, int last1)
1913 {
1914     struct execcmd_params eparams;
1915 
1916     if (breaks || retflag)
1917 	return;
1918 
1919     /* In evaluated traps, don't modify the line number. */
1920     if (!IN_EVAL_TRAP() && !ineval && WC_PIPE_LINENO(pcode))
1921 	lineno = WC_PIPE_LINENO(pcode) - 1;
1922 
1923     if (pline_level == 1) {
1924 	if ((how & Z_ASYNC) || !sfcontext)
1925 	    strcpy(list_pipe_text,
1926 		   getjobtext(state->prog,
1927 			      state->pc + (WC_PIPE_TYPE(pcode) == WC_PIPE_END ?
1928 					   0 : 1)));
1929 	else
1930 	    list_pipe_text[0] = '\0';
1931     }
1932     if (WC_PIPE_TYPE(pcode) == WC_PIPE_END) {
1933 	execcmd_analyse(state, &eparams);
1934 	execcmd_exec(state, &eparams, input, output, how, last1 ? 1 : 2, -1);
1935     } else {
1936 	int pipes[2];
1937 	int old_list_pipe = list_pipe;
1938 	Wordcode next = state->pc + (*state->pc);
1939 
1940 	++state->pc;
1941 	execcmd_analyse(state, &eparams);
1942 
1943 	if (mpipe(pipes) < 0) {
1944 	    /* FIXME */
1945 	}
1946 
1947 	addfilelist(NULL, pipes[0]);
1948 	execcmd_exec(state, &eparams, input, pipes[1], how, 0, pipes[0]);
1949 	zclose(pipes[1]);
1950 	state->pc = next;
1951 
1952 	/* if another execpline() is invoked because the command is *
1953 	 * a list it must know that we're already in a pipeline     */
1954 	cmdpush(CS_PIPE);
1955 	list_pipe = 1;
1956 	execpline2(state, *state->pc++, how, pipes[0], output, last1);
1957 	list_pipe = old_list_pipe;
1958 	cmdpop();
1959     }
1960 }
1961 
1962 /* make the argv array */
1963 
1964 /**/
1965 static char **
makecline(LinkList list)1966 makecline(LinkList list)
1967 {
1968     LinkNode node;
1969     char **argv, **ptr;
1970 
1971     /* A bigger argv is necessary for executing scripts */
1972     ptr = argv = 2 + (char **) hcalloc((countlinknodes(list) + 4) *
1973 				       sizeof(char *));
1974 
1975     if (isset(XTRACE)) {
1976 	if (!doneps4)
1977 	    printprompt4();
1978 
1979 	for (node = firstnode(list); node; incnode(node)) {
1980 	    *ptr++ = (char *)getdata(node);
1981 	    quotedzputs(getdata(node), xtrerr);
1982 	    if (nextnode(node))
1983 		fputc(' ', xtrerr);
1984 	}
1985 	fputc('\n', xtrerr);
1986 	fflush(xtrerr);
1987     } else {
1988 	for (node = firstnode(list); node; incnode(node))
1989 	    *ptr++ = (char *)getdata(node);
1990     }
1991     *ptr = NULL;
1992     return (argv);
1993 }
1994 
1995 /**/
1996 mod_export void
untokenize(char * s)1997 untokenize(char *s)
1998 {
1999     if (*s) {
2000 	int c;
2001 
2002 	while ((c = *s++))
2003 	    if (itok(c)) {
2004 		char *p = s - 1;
2005 
2006 		if (c != Nularg)
2007 		    *p++ = ztokens[c - Pound];
2008 
2009 		while ((c = *s++)) {
2010 		    if (itok(c)) {
2011 			if (c != Nularg)
2012 			    *p++ = ztokens[c - Pound];
2013 		    } else
2014 			*p++ = c;
2015 		}
2016 		*p = '\0';
2017 		break;
2018 	    }
2019     }
2020 }
2021 
2022 
2023 /*
2024  * Given a tokenized string, output it to standard output in
2025  * such a way that it's clear which tokens are active.
2026  * Hence Star becomes an unquoted "*", while a "*" becomes "\*".
2027  *
2028  * The code here is a kind of amalgamation of the tests in
2029  * zshtokenize() and untokenize() with some outputting.
2030  */
2031 
2032 /**/
2033 void
quote_tokenized_output(char * str,FILE * file)2034 quote_tokenized_output(char *str, FILE *file)
2035 {
2036     char *s = str;
2037 
2038     for (; *s; s++) {
2039 	switch (*s) {
2040 	case Meta:
2041 	    putc(*++s ^ 32, file);
2042 	    continue;
2043 
2044 	case Nularg:
2045 	    /* Do nothing.  I think. */
2046 	    continue;
2047 
2048 	case '\\':
2049 	case '<':
2050 	case '>':
2051 	case '(':
2052 	case '|':
2053 	case ')':
2054 	case '^':
2055 	case '#':
2056 	case '~':
2057 	case '[':
2058 	case ']':
2059 	case '*':
2060 	case '?':
2061 	case '$':
2062 	case ' ':
2063 	    putc('\\', file);
2064 	    break;
2065 
2066 	case '\t':
2067 	    fputs("$'\\t'", file);
2068 	    continue;
2069 
2070 	case '\n':
2071 	    fputs("$'\\n'", file);
2072 	    continue;
2073 
2074 	case '\r':
2075 	    fputs("$'\\r'", file);
2076 	    continue;
2077 
2078 	case '=':
2079 	    if (s == str)
2080 		putc('\\', file);
2081 	    break;
2082 
2083 	default:
2084 	    if (itok(*s)) {
2085 		putc(ztokens[*s - Pound], file);
2086 		continue;
2087 	    }
2088 	    break;
2089 	}
2090 
2091 	putc(*s, file);
2092     }
2093 }
2094 
2095 /* Check that we can use a parameter for allocating a file descriptor. */
2096 
2097 static int
checkclobberparam(struct redir * f)2098 checkclobberparam(struct redir *f)
2099 {
2100     struct value vbuf;
2101     Value v;
2102     char *s = f->varid;
2103     int fd;
2104 
2105     if (!s)
2106 	return 1;
2107 
2108     if (!(v = getvalue(&vbuf, &s, 0)))
2109 	return 1;
2110 
2111     if (v->pm->node.flags & PM_READONLY) {
2112 	zwarn("can't allocate file descriptor to readonly parameter %s",
2113 	      f->varid);
2114 	/* don't flag a system error for this */
2115 	errno = 0;
2116 	return 0;
2117     }
2118 
2119     /*
2120      * We can't clobber the value in the parameter if it's
2121      * already an opened file descriptor --- that means it's a decimal
2122      * integer corresponding to an opened file descriptor,
2123      * not merely an expression that evaluates to a file descriptor.
2124      */
2125     if (!isset(CLOBBER) && (s = getstrvalue(v)) &&
2126 	(fd = (int)zstrtol(s, &s, 10)) >= 0 && !*s &&
2127 	fd <= max_zsh_fd && fdtable[fd] == FDT_EXTERNAL) {
2128 	zwarn("can't clobber parameter %s containing file descriptor %d",
2129 	     f->varid, fd);
2130 	/* don't flag a system error for this */
2131 	errno = 0;
2132 	return 0;
2133     }
2134     return 1;
2135 }
2136 
2137 /* Open a file for writing redirection */
2138 
2139 /**/
2140 static int
clobber_open(struct redir * f)2141 clobber_open(struct redir *f)
2142 {
2143     struct stat buf;
2144     int fd, oerrno;
2145 
2146     /* If clobbering, just open. */
2147     if (isset(CLOBBER) || IS_CLOBBER_REDIR(f->type))
2148 	return open(unmeta(f->name),
2149 		O_WRONLY | O_CREAT | O_TRUNC | O_NOCTTY, 0666);
2150 
2151     /* If not clobbering, attempt to create file exclusively. */
2152     if ((fd = open(unmeta(f->name),
2153 		   O_WRONLY | O_CREAT | O_EXCL | O_NOCTTY, 0666)) >= 0)
2154 	return fd;
2155 
2156     /* If that fails, we are still allowed to open non-regular files. *
2157      * Try opening, and if it's a regular file then close it again    *
2158      * because we weren't supposed to open it.                        */
2159     oerrno = errno;
2160     if ((fd = open(unmeta(f->name), O_WRONLY | O_NOCTTY)) != -1) {
2161 	if(!fstat(fd, &buf) && !S_ISREG(buf.st_mode))
2162 	    return fd;
2163 	close(fd);
2164     }
2165     errno = oerrno;
2166     return -1;
2167 }
2168 
2169 /* size of buffer for tee and cat processes */
2170 #define TCBUFSIZE 4092
2171 
2172 /* close an multio (success) */
2173 
2174 /**/
2175 static void
closemn(struct multio ** mfds,int fd,int type)2176 closemn(struct multio **mfds, int fd, int type)
2177 {
2178     if (fd >= 0 && mfds[fd] && mfds[fd]->ct >= 2) {
2179 	struct multio *mn = mfds[fd];
2180 	char buf[TCBUFSIZE];
2181 	int len, i;
2182 	pid_t pid;
2183 	struct timeval bgtime;
2184 
2185 	/*
2186 	 * We need to block SIGCHLD in case the process
2187 	 * we are spawning terminates before the job table
2188 	 * is set up to handle it.
2189 	 */
2190 	child_block();
2191 	if ((pid = zfork(&bgtime))) {
2192 	    for (i = 0; i < mn->ct; i++)
2193 		zclose(mn->fds[i]);
2194 	    zclose(mn->pipe);
2195 	    if (pid == -1) {
2196 		mfds[fd] = NULL;
2197 		child_unblock();
2198 		return;
2199 	    }
2200 	    mn->ct = 1;
2201 	    mn->fds[0] = fd;
2202 	    addproc(pid, NULL, 1, &bgtime, -1, -1);
2203 	    child_unblock();
2204 	    return;
2205 	}
2206 	/* pid == 0 */
2207 	child_unblock();
2208 	closeallelse(mn);
2209 	if (mn->rflag) {
2210 	    /* tee process */
2211 	    while ((len = read(mn->pipe, buf, TCBUFSIZE)) != 0) {
2212 		if (len < 0) {
2213 		    if (errno == EINTR)
2214 			continue;
2215 		    else
2216 			break;
2217 		}
2218 		for (i = 0; i < mn->ct; i++)
2219 		    write_loop(mn->fds[i], buf, len);
2220 	    }
2221 	} else {
2222 	    /* cat process */
2223 	    for (i = 0; i < mn->ct; i++)
2224 		while ((len = read(mn->fds[i], buf, TCBUFSIZE)) != 0) {
2225 		    if (len < 0) {
2226 			if (errno == EINTR)
2227 			    continue;
2228 			else
2229 			    break;
2230 		    }
2231 		    write_loop(mn->pipe, buf, len);
2232 		}
2233 	}
2234 	_exit(0);
2235     } else if (fd >= 0 && type == REDIR_CLOSE)
2236 	mfds[fd] = NULL;
2237 }
2238 
2239 /* close all the mnodes (failure) */
2240 
2241 /**/
2242 static void
closemnodes(struct multio ** mfds)2243 closemnodes(struct multio **mfds)
2244 {
2245     int i, j;
2246 
2247     for (i = 0; i < 10; i++)
2248 	if (mfds[i]) {
2249 	    for (j = 0; j < mfds[i]->ct; j++)
2250 		zclose(mfds[i]->fds[j]);
2251 	    mfds[i] = NULL;
2252 	}
2253 }
2254 
2255 /**/
2256 static void
closeallelse(struct multio * mn)2257 closeallelse(struct multio *mn)
2258 {
2259     int i, j;
2260     long openmax;
2261 
2262     openmax = fdtable_size;
2263 
2264     for (i = 0; i < openmax; i++)
2265 	if (mn->pipe != i) {
2266 	    for (j = 0; j < mn->ct; j++)
2267 		if (mn->fds[j] == i)
2268 		    break;
2269 	    if (j == mn->ct)
2270 		zclose(i);
2271 	}
2272 }
2273 
2274 /*
2275  * A multio is a list of fds associated with a certain fd.
2276  * Thus if you do "foo >bar >ble", the multio for fd 1 will have
2277  * two fds, the result of open("bar",...), and the result of
2278  * open("ble",....).
2279  */
2280 
2281 /*
2282  * Add a fd to an multio.  fd1 must be < 10, and may be in any state.
2283  * fd2 must be open, and is `consumed' by this function.  Note that
2284  * fd1 == fd2 is possible, and indicates that fd1 was really closed.
2285  * We effectively do `fd2 = movefd(fd2)' at the beginning of this
2286  * function, but in most cases we can avoid an extra dup by delaying
2287  * the movefd: we only >need< to move it if we're actually doing a
2288  * multiple redirection.
2289  *
2290  * If varid is not NULL, we open an fd above 10 and set the parameter
2291  * named varid to that value.  fd1 is not used.
2292  */
2293 
2294 /**/
2295 static void
addfd(int forked,int * save,struct multio ** mfds,int fd1,int fd2,int rflag,char * varid)2296 addfd(int forked, int *save, struct multio **mfds, int fd1, int fd2, int rflag,
2297       char *varid)
2298 {
2299     int pipes[2];
2300 
2301     if (varid) {
2302 	/* fd will be over 10, don't touch mfds */
2303 	fd1 = movefd(fd2);
2304 	if (fd1 == -1) {
2305 	    zerr("cannot moved fd %d: %e", fd2, errno);
2306 	    return;
2307 	} else {
2308 	    fdtable[fd1] = FDT_EXTERNAL;
2309 	    setiparam(varid, (zlong)fd1);
2310 	    /*
2311 	     * If setting the parameter failed, close the fd else
2312 	     * it will leak.
2313 	     */
2314 	    if (errflag)
2315 		zclose(fd1);
2316 	}
2317     } else if (!mfds[fd1] || unset(MULTIOS)) {
2318 	if(!mfds[fd1]) {		/* starting a new multio */
2319 	    mfds[fd1] = (struct multio *) zhalloc(sizeof(struct multio));
2320 	    if (!forked && save[fd1] == -2) {
2321 		if (fd1 == fd2)
2322 		    save[fd1] = -1;
2323 		else {
2324 		    int fdN = movefd(fd1);
2325 		    /*
2326 		     * fd1 may already be closed here, so
2327 		     * ignore bad file descriptor error
2328 		     */
2329 		    if (fdN < 0) {
2330 			if (errno != EBADF) {
2331 			    zerr("cannot duplicate fd %d: %e", fd1, errno);
2332 			    mfds[fd1] = NULL;
2333 			    closemnodes(mfds);
2334 			    return;
2335 			}
2336 		    } else {
2337 			DPUTS(fdtable[fdN] != FDT_INTERNAL,
2338 			      "Saved file descriptor not marked as internal");
2339 			fdtable[fdN] |= FDT_SAVED_MASK;
2340 		    }
2341 		    save[fd1] = fdN;
2342 		}
2343 	    }
2344 	}
2345 	if (!varid)
2346 	    redup(fd2, fd1);
2347 	mfds[fd1]->ct = 1;
2348 	mfds[fd1]->fds[0] = fd1;
2349 	mfds[fd1]->rflag = rflag;
2350     } else {
2351 	if (mfds[fd1]->rflag != rflag) {
2352 	    zerr("file mode mismatch on fd %d", fd1);
2353 	    closemnodes(mfds);
2354 	    return;
2355 	}
2356 	if (mfds[fd1]->ct == 1) {	/* split the stream */
2357 	    int fdN = movefd(fd1);
2358 	    if (fdN < 0) {
2359 		zerr("multio failed for fd %d: %e", fd1, errno);
2360 		closemnodes(mfds);
2361 		return;
2362 	    }
2363 	    mfds[fd1]->fds[0] = fdN;
2364 	    fdN = movefd(fd2);
2365 	    if (fdN < 0) {
2366 		zerr("multio failed for fd %d: %e", fd2, errno);
2367 		closemnodes(mfds);
2368 		return;
2369 	    }
2370 	    mfds[fd1]->fds[1] = fdN;
2371 	    if (mpipe(pipes) < 0) {
2372 		zerr("multio failed for fd %d: %e", fd2, errno);
2373 		closemnodes(mfds);
2374 		return;
2375 	    }
2376 	    mfds[fd1]->pipe = pipes[1 - rflag];
2377 	    redup(pipes[rflag], fd1);
2378 	    mfds[fd1]->ct = 2;
2379 	} else {		/* add another fd to an already split stream */
2380 	    int fdN;
2381 	    if(!(mfds[fd1]->ct % MULTIOUNIT)) {
2382 		int new = sizeof(struct multio) + sizeof(int) * mfds[fd1]->ct;
2383 		int old = new - sizeof(int) * MULTIOUNIT;
2384 		mfds[fd1] = hrealloc((char *)mfds[fd1], old, new);
2385 	    }
2386 	    if ((fdN = movefd(fd2)) < 0) {
2387 		zerr("multio failed for fd %d: %e", fd2, errno);
2388 		closemnodes(mfds);
2389 		return;
2390 	    }
2391 	    mfds[fd1]->fds[mfds[fd1]->ct++] = fdN;
2392 	}
2393     }
2394 }
2395 
2396 /**/
2397 static void
addvars(Estate state,Wordcode pc,int addflags)2398 addvars(Estate state, Wordcode pc, int addflags)
2399 {
2400     LinkList vl;
2401     int xtr, isstr, htok = 0;
2402     char **arr, **ptr, *name;
2403     int flags;
2404 
2405     Wordcode opc = state->pc;
2406     wordcode ac;
2407     local_list1(svl);
2408 
2409     /*
2410      * Warn when creating a global without using typeset -g in a
2411      * function.  Don't do this if there is a list of variables marked
2412      * to be restored after the command, since then the assignment
2413      * is implicitly scoped.
2414      */
2415     flags = !(addflags & ADDVAR_RESTORE) ? ASSPM_WARN : 0;
2416     xtr = isset(XTRACE);
2417     if (xtr) {
2418 	printprompt4();
2419 	doneps4 = 1;
2420     }
2421     state->pc = pc;
2422     while (wc_code(ac = *state->pc++) == WC_ASSIGN) {
2423 	int myflags = flags;
2424 	name = ecgetstr(state, EC_DUPTOK, &htok);
2425 	if (htok)
2426 	    untokenize(name);
2427 	if (WC_ASSIGN_TYPE2(ac) == WC_ASSIGN_INC)
2428 	    myflags |= ASSPM_AUGMENT;
2429 	if (xtr)
2430 	    fprintf(xtrerr,
2431 		WC_ASSIGN_TYPE2(ac) == WC_ASSIGN_INC ? "%s+=" : "%s=", name);
2432 	if ((isstr = (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR))) {
2433 	    init_list1(svl, ecgetstr(state, EC_DUPTOK, &htok));
2434 	    vl = &svl;
2435 	} else {
2436 	    vl = ecgetlist(state, WC_ASSIGN_NUM(ac), EC_DUPTOK, &htok);
2437 	    if (errflag) {
2438 		state->pc = opc;
2439 		return;
2440 	    }
2441 	}
2442 
2443 	if (vl && htok) {
2444 	    int prefork_ret = 0;
2445 	    prefork(vl, (isstr ? (PREFORK_SINGLE|PREFORK_ASSIGN) :
2446 			 PREFORK_ASSIGN), &prefork_ret);
2447 	    if (errflag) {
2448 		state->pc = opc;
2449 		return;
2450 	    }
2451 	    if (prefork_ret & PREFORK_KEY_VALUE)
2452 		myflags |= ASSPM_KEY_VALUE;
2453 	    if (!isstr || (isset(GLOBASSIGN) && isstr &&
2454 			   haswilds((char *)getdata(firstnode(vl))))) {
2455 		globlist(vl, prefork_ret);
2456 		/* Unset the parameter to force it to be recreated
2457 		 * as either scalar or array depending on how many
2458 		 * matches were found for the glob.
2459 		 */
2460 		if (isset(GLOBASSIGN) && isstr)
2461 			unsetparam(name);
2462 		if (errflag) {
2463 		    state->pc = opc;
2464 		    return;
2465 		}
2466 	    }
2467 	}
2468 	if (isstr && (empty(vl) || !nextnode(firstnode(vl)))) {
2469 	    Param pm;
2470 	    char *val;
2471 	    int allexp;
2472 
2473 	    if (empty(vl))
2474 		val = ztrdup("");
2475 	    else {
2476 		untokenize(peekfirst(vl));
2477 		val = ztrdup(ugetnode(vl));
2478 	    }
2479 	    if (xtr) {
2480 		quotedzputs(val, xtrerr);
2481 		fputc(' ', xtrerr);
2482 	    }
2483 	    if ((addflags & ADDVAR_EXPORT) && !strchr(name, '[')) {
2484 		if ((addflags & ADDVAR_RESTRICT) && isset(RESTRICTED) &&
2485 		    (pm = (Param) paramtab->removenode(paramtab, name)) &&
2486 		    (pm->node.flags & PM_RESTRICTED)) {
2487 		    zerr("%s: restricted", pm->node.nam);
2488 		    zsfree(val);
2489 		    state->pc = opc;
2490 		    return;
2491 		}
2492 		if (strcmp(name, "STTY") == 0) {
2493 		    zsfree(STTYval);
2494 		    STTYval = ztrdup(val);
2495 		}
2496 		allexp = opts[ALLEXPORT];
2497 		opts[ALLEXPORT] = 1;
2498 		if (isset(KSHARRAYS))
2499 		    unsetparam(name);
2500 	    	pm = assignsparam(name, val, myflags);
2501 		opts[ALLEXPORT] = allexp;
2502 	    } else
2503 	    	pm = assignsparam(name, val, myflags);
2504 	    if (errflag) {
2505 		state->pc = opc;
2506 		return;
2507 	    }
2508 	    continue;
2509 	}
2510 	if (vl) {
2511 	    ptr = arr = (char **) zalloc(sizeof(char *) *
2512 					 (countlinknodes(vl) + 1));
2513 
2514 	    while (nonempty(vl))
2515 		*ptr++ = ztrdup((char *) ugetnode(vl));
2516 	} else
2517 	    ptr = arr = (char **) zalloc(sizeof(char *));
2518 
2519 	*ptr = NULL;
2520 	if (xtr) {
2521 	    fprintf(xtrerr, "( ");
2522 	    for (ptr = arr; *ptr; ptr++) {
2523 		quotedzputs(*ptr, xtrerr);
2524 		fputc(' ', xtrerr);
2525 	    }
2526 	    fprintf(xtrerr, ") ");
2527 	}
2528 	assignaparam(name, arr, myflags);
2529 	if (errflag) {
2530 	    state->pc = opc;
2531 	    return;
2532 	}
2533     }
2534     state->pc = opc;
2535 }
2536 
2537 /**/
2538 void
setunderscore(char * str)2539 setunderscore(char *str)
2540 {
2541     queue_signals();
2542     if (str && *str) {
2543 	size_t l = strlen(str) + 1, nl = (l + 31) & ~31;
2544 
2545 	if (nl > underscorelen || (underscorelen - nl) > 64) {
2546 	    zfree(zunderscore, underscorelen);
2547 	    zunderscore = (char *) zalloc(underscorelen = nl);
2548 	}
2549 	strcpy(zunderscore, str);
2550 	underscoreused = l;
2551     } else {
2552 	if (underscorelen > 128) {
2553 	    zfree(zunderscore, underscorelen);
2554 	    zunderscore = (char *) zalloc(underscorelen = 32);
2555 	}
2556 	*zunderscore = '\0';
2557 	underscoreused = 1;
2558     }
2559     unqueue_signals();
2560 }
2561 
2562 /* These describe the type of expansions that need to be done on the words
2563  * used in the thing we are about to execute. They are set in execcmd() and
2564  * used in execsubst() which might be called from one of the functions
2565  * called from execcmd() (like execfor() and so on). */
2566 
2567 static int esprefork, esglob = 1;
2568 
2569 /**/
2570 void
execsubst(LinkList strs)2571 execsubst(LinkList strs)
2572 {
2573     if (strs) {
2574 	prefork(strs, esprefork, NULL);
2575 	if (esglob && !errflag) {
2576 	    LinkList ostrs = strs;
2577 	    globlist(strs, 0);
2578 	    strs = ostrs;
2579 	}
2580     }
2581 }
2582 
2583 /*
2584  * Check if a builtin requires an autoload and if so
2585  * deal with it.  This may return NULL.
2586  */
2587 
2588 /**/
2589 static HashNode
resolvebuiltin(const char * cmdarg,HashNode hn)2590 resolvebuiltin(const char *cmdarg, HashNode hn)
2591 {
2592     if (!((Builtin) hn)->handlerfunc) {
2593 	char *modname = dupstring(((Builtin) hn)->optstr);
2594 	/*
2595 	 * Ensure the module is loaded and the
2596 	 * feature corresponding to the builtin
2597 	 * is enabled.
2598 	 */
2599 	(void)ensurefeature(modname, "b:",
2600 			    (hn->flags & BINF_AUTOALL) ? NULL :
2601 			    hn->nam);
2602 	hn = builtintab->getnode(builtintab, cmdarg);
2603 	if (!hn) {
2604 	    lastval = 1;
2605 	    zerr("autoloading module %s failed to define builtin: %s",
2606 		 modname, cmdarg);
2607 	    return NULL;
2608 	}
2609     }
2610     return hn;
2611 }
2612 
2613 /*
2614  * We are about to execute a command at the lowest level of the
2615  * hierarchy.  Analyse the parameters from the wordcode.
2616  */
2617 
2618 /**/
2619 static void
execcmd_analyse(Estate state,Execcmd_params eparams)2620 execcmd_analyse(Estate state, Execcmd_params eparams)
2621 {
2622     wordcode code;
2623     int i;
2624 
2625     eparams->beg = state->pc;
2626     eparams->redir =
2627 	(wc_code(*state->pc) == WC_REDIR ? ecgetredirs(state) : NULL);
2628     if (wc_code(*state->pc) == WC_ASSIGN) {
2629 	cmdoutval = 0;
2630 	eparams->varspc = state->pc;
2631 	while (wc_code((code = *state->pc)) == WC_ASSIGN)
2632 	    state->pc += (WC_ASSIGN_TYPE(code) == WC_ASSIGN_SCALAR ?
2633 			  3 : WC_ASSIGN_NUM(code) + 2);
2634     } else
2635 	eparams->varspc = NULL;
2636 
2637     code = *state->pc++;
2638 
2639     eparams->type = wc_code(code);
2640     eparams->postassigns = 0;
2641 
2642     /* It would be nice if we could use EC_DUPTOK instead of EC_DUP here.
2643      * But for that we would need to check/change all builtins so that
2644      * they don't modify their argument strings. */
2645     switch (eparams->type) {
2646     case WC_SIMPLE:
2647 	eparams->args = ecgetlist(state, WC_SIMPLE_ARGC(code), EC_DUP,
2648 				  &eparams->htok);
2649 	eparams->assignspc = NULL;
2650 	break;
2651 
2652     case WC_TYPESET:
2653 	eparams->args = ecgetlist(state, WC_TYPESET_ARGC(code), EC_DUP,
2654 				  &eparams->htok);
2655 	eparams->postassigns = *state->pc++;
2656 	eparams->assignspc = state->pc;
2657 	for (i = 0; i < eparams->postassigns; i++) {
2658 	    code = *state->pc;
2659 	    DPUTS(wc_code(code) != WC_ASSIGN,
2660 		  "BUG: miscounted typeset assignments");
2661 	    state->pc += (WC_ASSIGN_TYPE(code) == WC_ASSIGN_SCALAR ?
2662 			  3 : WC_ASSIGN_NUM(code) + 2);
2663 	}
2664 	break;
2665 
2666     default:
2667 	eparams->args = NULL;
2668 	eparams->assignspc = NULL;
2669 	eparams->htok = 0;
2670 	break;
2671     }
2672 }
2673 
2674 /*
2675  * Transfer the first node of args to preargs, performing
2676  * prefork expansion on the way if necessary.
2677  */
execcmd_getargs(LinkList preargs,LinkList args,int expand)2678 static void execcmd_getargs(LinkList preargs, LinkList args, int expand)
2679 {
2680     if (!firstnode(args)) {
2681 	return;
2682     } else if (expand) {
2683 	local_list0(svl);
2684 	init_list0(svl);
2685 	/* not init_list1, as we need real nodes */
2686 	addlinknode(&svl, uremnode(args, firstnode(args)));
2687 	/* Analysing commands, so vanilla options to prefork */
2688 	prefork(&svl, 0, NULL);
2689 	joinlists(preargs, &svl);
2690     } else {
2691         addlinknode(preargs, uremnode(args, firstnode(args)));
2692     }
2693 }
2694 
2695 /**/
2696 static int
execcmd_fork(Estate state,int how,int type,Wordcode varspc,LinkList * filelistp,char * text,int oautocont,int close_if_forked)2697 execcmd_fork(Estate state, int how, int type, Wordcode varspc,
2698 	     LinkList *filelistp, char *text, int oautocont,
2699 	     int close_if_forked)
2700 {
2701     pid_t pid;
2702     int synch[2], flags;
2703     struct entersubsh_ret esret;
2704     struct timeval bgtime;
2705 
2706     child_block();
2707     esret.gleader = -1;
2708     esret.list_pipe_job = -1;
2709 
2710     if (pipe(synch) < 0) {
2711 	zerr("pipe failed: %e", errno);
2712 	return -1;
2713     } else if ((pid = zfork(&bgtime)) == -1) {
2714 	close(synch[0]);
2715 	close(synch[1]);
2716 	lastval = 1;
2717 	errflag |= ERRFLAG_ERROR;
2718 	return -1;
2719     }
2720     if (pid) {
2721 	close(synch[1]);
2722 	read_loop(synch[0], (char *)&esret, sizeof(esret));
2723 	close(synch[0]);
2724 	if (how & Z_ASYNC) {
2725 	    lastpid = (zlong) pid;
2726 	} else if (!jobtab[thisjob].stty_in_env && varspc) {
2727 	    /* search for STTY=... */
2728 	    Wordcode p = varspc;
2729 	    wordcode ac;
2730 
2731 	    while (wc_code(ac = *p) == WC_ASSIGN) {
2732 		if (!strcmp(ecrawstr(state->prog, p + 1, NULL), "STTY")) {
2733 		    jobtab[thisjob].stty_in_env = 1;
2734 		    break;
2735 		}
2736 		p += (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR ?
2737 		      3 : WC_ASSIGN_NUM(ac) + 2);
2738 	    }
2739 	}
2740 	addproc(pid, text, 0, &bgtime, esret.gleader, esret.list_pipe_job);
2741 	if (oautocont >= 0)
2742 	    opts[AUTOCONTINUE] = oautocont;
2743 	pipecleanfilelist(jobtab[thisjob].filelist, 1);
2744 	return pid;
2745     }
2746 
2747     /* pid == 0 */
2748     close(synch[0]);
2749     flags = ((how & Z_ASYNC) ? ESUB_ASYNC : 0) | ESUB_PGRP;
2750     if ((type != WC_SUBSH) && !(how & Z_ASYNC))
2751 	flags |= ESUB_KEEPTRAP;
2752     if (type == WC_SUBSH && !(how & Z_ASYNC))
2753 	flags |= ESUB_JOB_CONTROL;
2754     *filelistp = jobtab[thisjob].filelist;
2755     entersubsh(flags, &esret);
2756     if (write_loop(synch[1], (const void *) &esret, sizeof(esret)) != sizeof(esret)) {
2757 	zerr("Failed to send entersubsh_ret report: %e", errno);
2758 	return -1;
2759     }
2760     close(synch[1]);
2761     zclose(close_if_forked);
2762 
2763     if (sigtrapped[SIGINT] & ZSIG_IGNORED)
2764 	holdintr();
2765     /*
2766      * EXIT traps shouldn't be called even if we forked to run
2767      * shell code as this isn't the main shell.
2768      */
2769     sigtrapped[SIGEXIT] = 0;
2770 #ifdef HAVE_NICE
2771     /* Check if we should run background jobs at a lower priority. */
2772     if ((how & Z_ASYNC) && isset(BGNICE)) {
2773 	errno = 0;
2774 	nice(5);
2775 	if (errno)
2776 	    zwarn("nice(5) failed: %e", errno);
2777     }
2778 #endif /* HAVE_NICE */
2779 
2780     return 0;
2781 }
2782 
2783 /*
2784  * Execute a command at the lowest level of the hierarchy.
2785  */
2786 
2787 /**/
2788 static void
execcmd_exec(Estate state,Execcmd_params eparams,int input,int output,int how,int last1,int close_if_forked)2789 execcmd_exec(Estate state, Execcmd_params eparams,
2790 	     int input, int output, int how, int last1, int close_if_forked)
2791 {
2792     HashNode hn = NULL;
2793     LinkList filelist = NULL;
2794     LinkNode node;
2795     Redir fn;
2796     struct multio *mfds[10];
2797     char *text;
2798     int save[10];
2799     int fil, dfil, is_cursh, do_exec = 0, redir_err = 0, i;
2800     int nullexec = 0, magic_assign = 0, forked = 0, old_lastval;
2801     int is_shfunc = 0, is_builtin = 0, is_exec = 0, use_defpath = 0;
2802     /* Various flags to the command. */
2803     int cflags = 0, orig_cflags = 0, checked = 0, oautocont = -1;
2804     FILE *oxtrerr = xtrerr, *newxtrerr = NULL;
2805     /*
2806      * Retrieve parameters for quick reference (they are unique
2807      * to us so we can modify the structure if we want).
2808      */
2809     LinkList args = eparams->args;
2810     LinkList redir = eparams->redir;
2811     Wordcode varspc = eparams->varspc;
2812     int type = eparams->type;
2813     /*
2814      * preargs comes from expanding the head of the args list
2815      * in order to check for prefix commands.
2816      */
2817     LinkList preargs;
2818 
2819     doneps4 = 0;
2820 
2821     /*
2822      * If assignment but no command get the status from variable
2823      * assignment.
2824      */
2825     old_lastval = lastval;
2826     if (!args && varspc)
2827 	lastval = errflag ? errflag : cmdoutval;
2828     /*
2829      * If there are arguments, we should reset the status for the
2830      * command before execution---unless we are using the result of a
2831      * command substitution, which will be indicated by setting
2832      * use_cmdoutval to 1.  We haven't kicked those off yet, so
2833      * there's no race.
2834      */
2835     use_cmdoutval = !args;
2836 
2837     for (i = 0; i < 10; i++) {
2838 	save[i] = -2;
2839 	mfds[i] = NULL;
2840     }
2841 
2842     /* If the command begins with `%', then assume it is a *
2843      * reference to a job in the job table.                */
2844     if ((type == WC_SIMPLE || type == WC_TYPESET) && args && nonempty(args) &&
2845 	*(char *)peekfirst(args) == '%') {
2846         if (how & Z_DISOWN) {
2847 	    oautocont = opts[AUTOCONTINUE];
2848             opts[AUTOCONTINUE] = 1;
2849 	}
2850 	pushnode(args, dupstring((how & Z_DISOWN)
2851 				 ? "disown" : (how & Z_ASYNC) ? "bg" : "fg"));
2852 	how = Z_SYNC;
2853     }
2854 
2855     /* If AUTORESUME is set, the command is SIMPLE, and doesn't have *
2856      * any redirections, then check if it matches as a prefix of a   *
2857      * job currently in the job table.  If it does, then we treat it *
2858      * as a command to resume this job.                              */
2859     if (isset(AUTORESUME) && type == WC_SIMPLE && (how & Z_SYNC) &&
2860 	args && nonempty(args) && (!redir || empty(redir)) && !input &&
2861 	!nextnode(firstnode(args))) {
2862 	if (unset(NOTIFY))
2863 	    scanjobs();
2864 	if (findjobnam(peekfirst(args)) != -1)
2865 	    pushnode(args, dupstring("fg"));
2866     }
2867 
2868     if ((how & Z_ASYNC) || output) {
2869 	/*
2870 	 * If running in the background, or not the last command in a
2871 	 * pipeline, we don't need any of the rest of this function to
2872 	 * affect the state in the main shell, so fork immediately.
2873 	 *
2874 	 * In other cases we may need to process the command line
2875 	 * a bit further before we make the decision.
2876 	 */
2877 	text = getjobtext(state->prog, eparams->beg);
2878 	switch (execcmd_fork(state, how, type, varspc, &filelist,
2879 			     text, oautocont, close_if_forked)) {
2880 	case -1:
2881 	    goto fatal;
2882 	case 0:
2883 	    break;
2884 	default:
2885 	    return;
2886 	}
2887 	last1 = forked = 1;
2888     } else
2889 	text = NULL;
2890 
2891     /* Check if it's a builtin needing automatic MAGIC_EQUALS_SUBST      *
2892      * handling.  Things like typeset need this.  We can't detect the    *
2893      * command if it contains some tokens (e.g. x=ex; ${x}port), so this *
2894      * only works in simple cases.  has_token() is called to make sure   *
2895      * this really is a simple case.                                     */
2896     if ((type == WC_SIMPLE || type == WC_TYPESET) && args) {
2897 	/*
2898 	 * preargs contains args that have been expanded by prefork.
2899 	 * Running execcmd_getargs() causes any argument available
2900 	 * in args to be exanded where necessary and transferred to
2901 	 * preargs.  We call execcmd_getargs() every time we need to
2902 	 * analyse an argument not available in preargs, though there is
2903 	 * no guarantee a further argument will be available.
2904 	 */
2905 	preargs = newlinklist();
2906 	execcmd_getargs(preargs, args, eparams->htok);
2907 	while (nonempty(preargs)) {
2908 	    char *cmdarg = (char *) peekfirst(preargs);
2909 	    checked = !has_token(cmdarg);
2910 	    if (!checked)
2911 		break;
2912 	    if (type == WC_TYPESET &&
2913 		(hn = builtintab->getnode2(builtintab, cmdarg))) {
2914 		/*
2915 		 * If reserved word for typeset command found (and so
2916 		 * enabled), use regardless of whether builtin is
2917 		 * enabled as we share the implementation.
2918 		 *
2919 		 * Reserved words take precedence over shell functions.
2920 		 */
2921 		checked = 1;
2922 	    } else if (isset(POSIXBUILTINS) && (cflags & BINF_EXEC)) {
2923 		/*
2924 		 * POSIX doesn't allow "exec" to operate on builtins
2925 		 * or shell functions.
2926 		 */
2927 		break;
2928 	    } else {
2929 		if (!(cflags & (BINF_BUILTIN | BINF_COMMAND)) &&
2930 		    (hn = shfunctab->getnode(shfunctab, cmdarg))) {
2931 		    is_shfunc = 1;
2932 		    break;
2933 		}
2934 		if (!(hn = builtintab->getnode(builtintab, cmdarg))) {
2935 		    checked = !(cflags & BINF_BUILTIN);
2936 		    break;
2937 		}
2938 	    }
2939 	    orig_cflags |= cflags;
2940 	    cflags &= ~BINF_BUILTIN & ~BINF_COMMAND;
2941 	    cflags |= hn->flags;
2942 	    if (!(hn->flags & BINF_PREFIX)) {
2943 		is_builtin = 1;
2944 
2945 		/* autoload the builtin if necessary */
2946 		if (!(hn = resolvebuiltin(cmdarg, hn))) {
2947 		    if (forked)
2948 			_realexit();
2949 		    return;
2950 		}
2951 		if (type != WC_TYPESET)
2952 		    magic_assign = (hn->flags & BINF_MAGICEQUALS);
2953 		break;
2954 	    }
2955 	    checked = 0;
2956 	    /*
2957 	     * We usually don't need the argument containing the
2958 	     * precommand modifier itself.  Exception: when "command"
2959 	     * will implemented by a call to "whence", in which case
2960 	     * we'll simply re-insert the argument.
2961 	     */
2962 	    uremnode(preargs, firstnode(preargs));
2963 	    if (!firstnode(preargs)) {
2964 		execcmd_getargs(preargs, args, eparams->htok);
2965 		if (!firstnode(preargs))
2966 		    break;
2967 	    }
2968 	    if ((cflags & BINF_COMMAND)) {
2969 		/*
2970 		 * Check for options to "command".
2971 		 * If just -p, this is handled here: use the default
2972 		 * path to execute.
2973 		 * If -v or -V, possibly with -p, dispatch to bin_whence
2974 		 * but with flag to indicate special handling of -p.
2975 		 * Otherwise, just leave marked as BINF_COMMAND
2976 		 * modifier with no additional action.
2977 		 */
2978 		LinkNode argnode, oldnode, pnode = NULL;
2979 		char *argdata, *cmdopt;
2980 		int has_p = 0, has_vV = 0, has_other = 0;
2981 		argnode = firstnode(preargs);
2982 		argdata = (char *) getdata(argnode);
2983 		while (IS_DASH(*argdata)) {
2984 		    /* Just to be definite, stop on single "-", too, */
2985 		    if (!argdata[1] ||
2986 			(IS_DASH(argdata[1]) && !argdata[2]))
2987 			break;
2988 		    for (cmdopt = argdata+1; *cmdopt; cmdopt++) {
2989 			switch (*cmdopt) {
2990 			case 'p':
2991 			    /*
2992 			     * If we've got this multiple times (command
2993 			     * -p -p) we'll treat the second -p as a
2994 			     * command because we only remove one below.
2995 			     * Don't think that's a big issue, and it's
2996 			     * also traditional behaviour.
2997 			     */
2998 			    has_p = 1;
2999 			    pnode = argnode;
3000 			    break;
3001 			case 'v':
3002 			case 'V':
3003 			    has_vV = 1;
3004 			    break;
3005 			default:
3006 			    has_other = 1;
3007 			    break;
3008 			}
3009 		    }
3010 		    if (has_other) {
3011 			/* Don't know how to handle this, so don't */
3012 			has_p = has_vV = 0;
3013 			break;
3014 		    }
3015 
3016 		    oldnode = argnode;
3017 		    argnode = nextnode(argnode);
3018 		    if (!argnode) {
3019 			execcmd_getargs(preargs, args, eparams->htok);
3020 			if (!(argnode = nextnode(oldnode)))
3021 			    break;
3022 		    }
3023 		    argdata = (char *) getdata(argnode);
3024 		}
3025 		if (has_vV) {
3026 		    /*
3027 		     * Leave everything alone, dispatch to whence.
3028 		     * We need to put the name back in the list.
3029 		     */
3030 		    pushnode(preargs, "command");
3031 		    hn = &commandbn.node;
3032 		    is_builtin = 1;
3033 		    break;
3034 		} else if (has_p) {
3035 		    /* Use default path */
3036 		    use_defpath = 1;
3037 		    /*
3038 		     * We don't need this node as we're not treating
3039 		     * "command" as a builtin this time.
3040 		     */
3041 		    if (pnode)
3042 			uremnode(preargs, pnode);
3043 		}
3044 		/*
3045 		 * Else just any trailing
3046 		 * end-of-options marker.  This can only occur
3047 		 * if we just had -p or something including more
3048 		 * than just -p, -v and -V, in which case we behave
3049 		 * as if this is command [non-option-stuff].  This
3050 		 * isn't a good place for standard option handling.
3051 		 */
3052 		if (IS_DASH(argdata[0]) && IS_DASH(argdata[1]) && !argdata[2])
3053 		     uremnode(preargs, argnode);
3054 	    } else if (cflags & BINF_EXEC) {
3055 		/*
3056 		 * Check for compatibility options to exec builtin.
3057 		 * It would be nice to do these more generically,
3058 		 * but currently we don't have a mechanism for
3059 		 * precommand modifiers.
3060 		 */
3061 		LinkNode argnode = firstnode(preargs), oldnode;
3062 		char *argdata = (char *) getdata(argnode);
3063 		char *cmdopt, *exec_argv0 = NULL;
3064 		/*
3065 		 * Careful here: we want to make sure a final dash
3066 		 * is passed through in order that it still behaves
3067 		 * as a precommand modifier (zsh equivalent of -l).
3068 		 * It has to be last, but I think that's OK since
3069 		 * people aren't likely to mix the option style
3070 		 * with the zsh style.
3071 		 */
3072 		while (argdata && IS_DASH(*argdata) && strlen(argdata) >= 2) {
3073 		    oldnode = argnode;
3074 		    argnode = nextnode(oldnode);
3075 		    if (!argnode) {
3076 			execcmd_getargs(preargs, args, eparams->htok);
3077 			argnode = nextnode(oldnode);
3078 		    }
3079 		    if (!argnode) {
3080 			zerr("exec requires a command to execute");
3081 			lastval = 1;
3082 			errflag |= ERRFLAG_ERROR;
3083 			goto done;
3084 		    }
3085 		    uremnode(preargs, oldnode);
3086 		    if (IS_DASH(argdata[0]) && IS_DASH(argdata[1]) && !argdata[2])
3087 			break;
3088 		    for (cmdopt = &argdata[1]; *cmdopt; ++cmdopt) {
3089 			switch (*cmdopt) {
3090 			case 'a':
3091 			    /* argument is ARGV0 string */
3092 			    if (cmdopt[1]) {
3093 				exec_argv0 = cmdopt+1;
3094 				/* position on last non-NULL character */
3095 				cmdopt += strlen(cmdopt+1);
3096 			    } else {
3097 				if (!argnode) {
3098 				    zerr("exec requires a command to execute");
3099 				    lastval = 1;
3100 				    errflag |= ERRFLAG_ERROR;
3101 				    goto done;
3102 				}
3103 				if (!nextnode(argnode))
3104 				    execcmd_getargs(preargs, args,
3105 						    eparams->htok);
3106 				if (!nextnode(argnode)) {
3107 				    zerr("exec flag -a requires a parameter");
3108 				    lastval = 1;
3109 				    errflag |= ERRFLAG_ERROR;
3110 				    goto done;
3111 				}
3112 				exec_argv0 = (char *) getdata(argnode);
3113 				oldnode = argnode;
3114 				argnode = nextnode(argnode);
3115 				uremnode(args, oldnode);
3116 			    }
3117 			    break;
3118 			case 'c':
3119 			    cflags |= BINF_CLEARENV;
3120 			    break;
3121 			case 'l':
3122 			    cflags |= BINF_DASH;
3123 			    break;
3124 			default:
3125 			    zerr("unknown exec flag -%c", *cmdopt);
3126 			    lastval = 1;
3127 			    errflag |= ERRFLAG_ERROR;
3128 			    if (forked)
3129 				_realexit();
3130 			    return;
3131 			}
3132 		    }
3133 		    if (!argnode)
3134 			break;
3135 		    argdata = (char *) getdata(argnode);
3136 		}
3137 		if (exec_argv0) {
3138 		    char *str, *s;
3139 		    exec_argv0 = dupstring(exec_argv0);
3140 		    remnulargs(exec_argv0);
3141 		    untokenize(exec_argv0);
3142 		    size_t sz = strlen(exec_argv0);
3143 		    str = s = zalloc(5 + 1 + sz + 1);
3144 		    strcpy(s, "ARGV0=");
3145 		    s+=6;
3146 		    strcpy(s, exec_argv0);
3147 		    zputenv(str);
3148 		}
3149 	    }
3150 	    hn = NULL;
3151 	    if ((cflags & BINF_COMMAND) && unset(POSIXBUILTINS))
3152 		break;
3153 	    if (!nonempty(preargs))
3154 		execcmd_getargs(preargs, args, eparams->htok);
3155 	}
3156     } else
3157 	preargs = NULL;
3158 
3159     /* if we get this far, it is OK to pay attention to lastval again */
3160     if (noerrexit & NOERREXIT_UNTIL_EXEC)
3161 	noerrexit = 0;
3162 
3163     /* Do prefork substitutions.
3164      *
3165      * Decide if we need "magic" handling of ~'s etc. in
3166      * assignment-like arguments.
3167      * - If magic_assign is set, we are using a builtin of the
3168      *   tyepset family, but did not recognise this as a keyword,
3169      *   so need guess-o-matic behaviour.
3170      * - Otherwise, if we did recognise the keyword, we never need
3171      *   guess-o-matic behaviour as the argument was properly parsed
3172      *   as such.
3173      * - Otherwise, use the behaviour specified by the MAGIC_EQUAL_SUBST
3174      *   option.
3175      */
3176     esprefork = (magic_assign ||
3177 		 (isset(MAGICEQUALSUBST) && type != WC_TYPESET)) ?
3178 		 PREFORK_TYPESET : 0;
3179 
3180     if (args) {
3181 	if (eparams->htok)
3182 	    prefork(args, esprefork, NULL);
3183 	if (preargs)
3184 	    args = joinlists(preargs, args);
3185     }
3186 
3187     if (type == WC_SIMPLE || type == WC_TYPESET) {
3188 	int unglobbed = 0;
3189 
3190 	for (;;) {
3191 	    char *cmdarg;
3192 
3193 	    if (!(cflags & BINF_NOGLOB))
3194 		while (!checked && !errflag && args && nonempty(args) &&
3195 		       has_token((char *) peekfirst(args)))
3196 		    zglob(args, firstnode(args), 0);
3197 	    else if (!unglobbed) {
3198 		for (node = firstnode(args); node; incnode(node))
3199 		    untokenize((char *) getdata(node));
3200 		unglobbed = 1;
3201 	    }
3202 
3203 	    /* Current shell should not fork unless the *
3204 	     * exec occurs at the end of a pipeline.    */
3205 	    if ((cflags & BINF_EXEC) && last1)
3206 		do_exec = 1;
3207 
3208 	    /* Empty command */
3209 	    if (!args || empty(args)) {
3210 		if (redir && nonempty(redir)) {
3211 		    if (do_exec) {
3212 			/* Was this "exec < foobar"? */
3213 			nullexec = 1;
3214 			break;
3215 		    } else if (varspc) {
3216 			nullexec = 2;
3217 			break;
3218 		    } else if (!nullcmd || !*nullcmd || opts[CSHNULLCMD] ||
3219 			       (cflags & BINF_PREFIX)) {
3220 			zerr("redirection with no command");
3221 			lastval = 1;
3222 			errflag |= ERRFLAG_ERROR;
3223 			if (forked)
3224 			    _realexit();
3225 			return;
3226 		    } else if (!nullcmd || !*nullcmd || opts[SHNULLCMD]) {
3227 			if (!args)
3228 			    args = newlinklist();
3229 			addlinknode(args, dupstring(":"));
3230 		    } else if (readnullcmd && *readnullcmd &&
3231 			       ((Redir) peekfirst(redir))->type == REDIR_READ &&
3232 			       !nextnode(firstnode(redir))) {
3233 			if (!args)
3234 			    args = newlinklist();
3235 			addlinknode(args, dupstring(readnullcmd));
3236 		    } else {
3237 			if (!args)
3238 			    args = newlinklist();
3239 			addlinknode(args, dupstring(nullcmd));
3240 		    }
3241 		} else if ((cflags & BINF_PREFIX) && (cflags & BINF_COMMAND)) {
3242 		    lastval = 0;
3243 		    if (forked)
3244 			_realexit();
3245 		    return;
3246 		} else {
3247 		    /*
3248 		     * No arguments.  Reset the status if there were
3249 		     * arguments before and no command substitution
3250 		     * has provided a status.
3251 		     */
3252 		    if (badcshglob == 1) {
3253 			zerr("no match");
3254 			lastval = 1;
3255 			if (forked)
3256 			    _realexit();
3257 			return;
3258 		    }
3259 		    cmdoutval = use_cmdoutval ? lastval : 0;
3260 		    if (varspc) {
3261 			/* Make sure $? is still correct for assignment */
3262 			lastval = old_lastval;
3263 			addvars(state, varspc, 0);
3264 		    }
3265 		    if (errflag)
3266 			lastval = 1;
3267 		    else
3268 			lastval = cmdoutval;
3269 		    if (isset(XTRACE)) {
3270 			fputc('\n', xtrerr);
3271 			fflush(xtrerr);
3272 		    }
3273 		    if (forked)
3274 			_realexit();
3275 		    return;
3276 		}
3277 	    } else if (isset(RESTRICTED) && (cflags & BINF_EXEC) && do_exec) {
3278 		zerrnam("exec", "%s: restricted",
3279 			(char *) getdata(firstnode(args)));
3280 		lastval = 1;
3281 		if (forked)
3282 		    _realexit();
3283 		return;
3284 	    }
3285 
3286 	    /*
3287 	     * Quit looking for a command if:
3288 	     * - there was an error; or
3289 	     * - we checked the simple cases needing MAGIC_EQUAL_SUBST; or
3290 	     * - we know we already found a builtin (because either:
3291 	     *   - we loaded a builtin from a module, or
3292 	     *   - we have determined there are options which would
3293 	     *     require us to use the "command" builtin); or
3294 	     * - we aren't using POSIX and so BINF_COMMAND indicates a zsh
3295 	     *   precommand modifier is being used in place of the
3296 	     *   builtin
3297 	     * - we are using POSIX and this is an EXEC, so we can't
3298 	     *   execute a builtin or function.
3299 	     */
3300 	    if (errflag || checked || is_builtin ||
3301 		(isset(POSIXBUILTINS) ?
3302 		 (cflags & BINF_EXEC) : (cflags & BINF_COMMAND)))
3303 		break;
3304 
3305 	    cmdarg = (char *) peekfirst(args);
3306 	    if (!(cflags & (BINF_BUILTIN | BINF_COMMAND)) &&
3307 		(hn = shfunctab->getnode(shfunctab, cmdarg))) {
3308 		is_shfunc = 1;
3309 		break;
3310 	    }
3311 	    if (!(hn = builtintab->getnode(builtintab, cmdarg))) {
3312 		if (cflags & BINF_BUILTIN) {
3313 		    zwarn("no such builtin: %s", cmdarg);
3314 		    lastval = 1;
3315 		    if (oautocont >= 0)
3316 			opts[AUTOCONTINUE] = oautocont;
3317 		    if (forked)
3318 			_realexit();
3319 		    return;
3320 		}
3321 		break;
3322 	    }
3323 	    if (!(hn->flags & BINF_PREFIX)) {
3324 		is_builtin = 1;
3325 
3326 		/* autoload the builtin if necessary */
3327 		if (!(hn = resolvebuiltin(cmdarg, hn))) {
3328 		    if (forked)
3329 			_realexit();
3330 		    return;
3331 		}
3332 		break;
3333 	    }
3334 	    cflags &= ~BINF_BUILTIN & ~BINF_COMMAND;
3335 	    cflags |= hn->flags;
3336 	    uremnode(args, firstnode(args));
3337 	    hn = NULL;
3338 	}
3339     }
3340 
3341     if (errflag) {
3342 	if (!lastval)
3343 	    lastval = 1;
3344 	if (oautocont >= 0)
3345 	    opts[AUTOCONTINUE] = oautocont;
3346 	if (forked)
3347 	    _realexit();
3348 	return;
3349     }
3350 
3351     /* Get the text associated with this command. */
3352     if (!text &&
3353 	(!sfcontext && (jobbing || (how & Z_TIMED))))
3354 	text = getjobtext(state->prog, eparams->beg);
3355 
3356     /*
3357      * Set up special parameter $_
3358      * For execfuncdef we may need to take account of an
3359      * anonymous function with arguments.
3360      */
3361     if (type != WC_FUNCDEF)
3362 	setunderscore((args && nonempty(args)) ?
3363 		      ((char *) getdata(lastnode(args))) : "");
3364 
3365     /* Warn about "rm *" */
3366     if (type == WC_SIMPLE && interact && unset(RMSTARSILENT) &&
3367 	isset(SHINSTDIN) && args && nonempty(args) &&
3368 	nextnode(firstnode(args)) && !strcmp(peekfirst(args), "rm")) {
3369 	LinkNode node, next;
3370 
3371 	for (node = nextnode(firstnode(args)); node && !errflag; node = next) {
3372 	    char *s = (char *) getdata(node);
3373 	    int l = strlen(s);
3374 
3375 	    next = nextnode(node);
3376 	    if (s[0] == Star && !s[1]) {
3377 		if (!checkrmall(pwd)) {
3378 		    errflag |= ERRFLAG_ERROR;
3379 		    break;
3380 		}
3381 	    } else if (l >= 2 && s[l - 2] == '/' && s[l - 1] == Star) {
3382 		char t = s[l - 2];
3383 		int rmall;
3384 
3385 		s[l - 2] = 0;
3386 		rmall = checkrmall(s);
3387 		s[l - 2] = t;
3388 
3389 		if (!rmall) {
3390 		    errflag |= ERRFLAG_ERROR;
3391 		    break;
3392 		}
3393 	    }
3394 	}
3395     }
3396 
3397     if (type == WC_FUNCDEF) {
3398 	/*
3399 	 * The first word of a function definition is a list of
3400 	 * names.  If this is empty, we're doing an anonymous function:
3401 	 * in that case redirections are handled normally.
3402 	 * If not, it's a function definition: then we don't do
3403 	 * redirections here but pass in the list of redirections to
3404 	 * be stored for recall with the function.
3405 	 */
3406 	if (*state->pc != 0) {
3407 	    /* Nonymous, don't do redirections here */
3408 	    redir = NULL;
3409 	}
3410     } else if (is_shfunc || type == WC_AUTOFN) {
3411 	Shfunc shf;
3412 	if (is_shfunc)
3413 	    shf = (Shfunc)hn;
3414 	else {
3415 	    shf = loadautofn(state->prog->shf, 1, 0, 0);
3416 	    if (shf)
3417 		state->prog->shf = shf;
3418 	    else {
3419 		/*
3420 		 * This doesn't set errflag, so just return now.
3421 		 */
3422 		lastval = 1;
3423 		if (oautocont >= 0)
3424 		    opts[AUTOCONTINUE] = oautocont;
3425 		if (forked)
3426 		    _realexit();
3427 		return;
3428 	    }
3429 	}
3430 	/*
3431 	 * A function definition may have a list of additional
3432 	 * redirections to apply, so retrieve it.
3433 	 */
3434 	if (shf->redir) {
3435 	    struct estate s;
3436 	    LinkList redir2;
3437 
3438 	    s.prog = shf->redir;
3439 	    s.pc = shf->redir->prog;
3440 	    s.strs = shf->redir->strs;
3441 	    redir2 = ecgetredirs(&s);
3442 	    if (!redir)
3443 		redir = redir2;
3444 	    else {
3445 		while (nonempty(redir2))
3446 		    addlinknode(redir, ugetnode(redir2));
3447 	    }
3448 	}
3449     }
3450 
3451     if (errflag) {
3452 	lastval = 1;
3453 	if (oautocont >= 0)
3454 	    opts[AUTOCONTINUE] = oautocont;
3455 	if (forked)
3456 	    _realexit();
3457 	return;
3458     }
3459 
3460     if ((type == WC_SIMPLE || type == WC_TYPESET) && !nullexec) {
3461 	char *s;
3462 	char trycd = (isset(AUTOCD) && isset(SHINSTDIN) &&
3463 		      (!redir || empty(redir)) && args && !empty(args) &&
3464 		      !nextnode(firstnode(args)) && *(char *)peekfirst(args));
3465 
3466 	DPUTS((!args || empty(args)), "BUG: empty(args) in exec.c");
3467 	if (!hn) {
3468 	    /* Resolve external commands */
3469 	    char *cmdarg = (char *) peekfirst(args);
3470 	    char **checkpath = pathchecked;
3471 	    int dohashcmd = isset(HASHCMDS);
3472 
3473 	    hn = cmdnamtab->getnode(cmdnamtab, cmdarg);
3474 	    if (hn && trycd && !isreallycom((Cmdnam)hn)) {
3475 		if (!(((Cmdnam)hn)->node.flags & HASHED)) {
3476 		    checkpath = path;
3477 		    dohashcmd = 1;
3478 		}
3479 		cmdnamtab->removenode(cmdnamtab, cmdarg);
3480 		cmdnamtab->freenode(hn);
3481 		hn = NULL;
3482 	    }
3483 	    if (!hn && dohashcmd && strcmp(cmdarg, "..")) {
3484 		for (s = cmdarg; *s && *s != '/'; s++);
3485 		if (!*s)
3486 		    hn = (HashNode) hashcmd(cmdarg, checkpath);
3487 	    }
3488 	}
3489 
3490 	/* If no command found yet, see if it  *
3491 	 * is a directory we should AUTOCD to. */
3492 	if (!hn && trycd && (s = cancd(peekfirst(args)))) {
3493 	    peekfirst(args) = (void *) s;
3494 	    pushnode(args, dupstring("--"));
3495 	    pushnode(args, dupstring("cd"));
3496 	    if ((hn = builtintab->getnode(builtintab, "cd")))
3497 		is_builtin = 1;
3498 	}
3499     }
3500 
3501     /* This is nonzero if the command is a current shell procedure? */
3502     is_cursh = (is_builtin || is_shfunc || nullexec || type >= WC_CURSH);
3503 
3504     /**************************************************************************
3505      * Do we need to fork?  We need to fork if:                               *
3506      * 1) The command is supposed to run in the background.  This             *
3507      *    case is now handled above (forked = 1 here). (or)                   *
3508      * 2) There is no `exec' flag, and either:                                *
3509      *    a) This is a builtin or shell function with output piped somewhere. *
3510      *    b) This is an external command and we can't do a `fake exec'.       *
3511      *                                                                        *
3512      * A `fake exec' is possible if we have all the following conditions:     *
3513      * 1) last1 flag is 1.  This indicates that the current shell will not    *
3514      *    be needed after the current command.  This is typically the case    *
3515      *    when the command is the last stage in a subshell, or is the         *
3516      *    last command after the option `-c'.                                 *
3517      * 2) We don't have any traps set.                                        *
3518      * 3) We don't have any files to delete.                                  *
3519      *                                                                        *
3520      * The condition above for a `fake exec' will also work for a current     *
3521      * shell command such as a builtin, but doesn't really buy us anything    *
3522      * (doesn't save us a process), since it is already running in the        *
3523      * current shell.                                                         *
3524      **************************************************************************/
3525 
3526     if (!forked) {
3527 	if (!do_exec &&
3528 	    (((is_builtin || is_shfunc) && output) ||
3529 	     (!is_cursh && (last1 != 1 || nsigtrapped || havefiles() ||
3530 			    fdtable_flocks)))) {
3531 	    switch (execcmd_fork(state, how, type, varspc, &filelist,
3532 				 text, oautocont, close_if_forked)) {
3533 	    case -1:
3534 		goto fatal;
3535 	    case 0:
3536 		break;
3537 	    default:
3538 		return;
3539 	    }
3540 	    forked = 1;
3541 	} else if (is_cursh) {
3542 	    /* This is a current shell procedure that didn't need to fork.    *
3543 	     * This includes current shell procedures that are being exec'ed, *
3544 	     * as well as null execs.                                         */
3545 	    jobtab[thisjob].stat |= STAT_CURSH;
3546 	    if (!jobtab[thisjob].procs)
3547 		jobtab[thisjob].stat |= STAT_NOPRINT;
3548 	    if (is_builtin)
3549 		jobtab[thisjob].stat |= STAT_BUILTIN;
3550 	} else {
3551 	    /* This is an exec (real or fake) for an external command.    *
3552 	     * Note that any form of exec means that the subshell is fake *
3553 	     * (but we may be in a subshell already).                     */
3554 	    is_exec = 1;
3555 	    /*
3556 	     * If we are in a subshell environment anyway, say we're forked,
3557 	     * even if we're actually not forked because we know the
3558 	     * subshell is exiting.  This ensures SHLVL reflects the current
3559 	     * shell, and also optimises out any save/restore we'd need to
3560 	     * do if we were returning to the main shell.
3561 	     */
3562 	    if (type == WC_SUBSH)
3563 		forked = 1;
3564 	}
3565     }
3566 
3567     if ((esglob = !(cflags & BINF_NOGLOB)) && args && eparams->htok) {
3568 	LinkList oargs = args;
3569 	globlist(args, 0);
3570 	args = oargs;
3571     }
3572     if (errflag) {
3573 	lastval = 1;
3574 	goto err;
3575     }
3576 
3577     /* Make a copy of stderr for xtrace output before redirecting */
3578     fflush(xtrerr);
3579     if (isset(XTRACE) && xtrerr == stderr &&
3580 	(type < WC_SUBSH || type == WC_TIMED)) {
3581 	if ((newxtrerr = fdopen(movefd(dup(fileno(stderr))), "w"))) {
3582 	    xtrerr = newxtrerr;
3583 	    fdtable[fileno(xtrerr)] = FDT_XTRACE;
3584 	}
3585     }
3586 
3587     /* Add pipeline input/output to mnodes */
3588     if (input)
3589 	addfd(forked, save, mfds, 0, input, 0, NULL);
3590     if (output)
3591 	addfd(forked, save, mfds, 1, output, 1, NULL);
3592 
3593     /* Do process substitutions */
3594     if (redir)
3595 	spawnpipes(redir, nullexec);
3596 
3597     /* Do io redirections */
3598     while (redir && nonempty(redir)) {
3599 	fn = (Redir) ugetnode(redir);
3600 
3601 	DPUTS(fn->type == REDIR_HEREDOC || fn->type == REDIR_HEREDOCDASH,
3602 	      "BUG: unexpanded here document");
3603 	if (fn->type == REDIR_INPIPE) {
3604 	    if (!checkclobberparam(fn) || fn->fd2 == -1) {
3605 		if (fn->fd2 != -1)
3606 		    zclose(fn->fd2);
3607 		closemnodes(mfds);
3608 		fixfds(save);
3609 		execerr();
3610 	    }
3611 	    addfd(forked, save, mfds, fn->fd1, fn->fd2, 0, fn->varid);
3612 	} else if (fn->type == REDIR_OUTPIPE) {
3613 	    if (!checkclobberparam(fn) || fn->fd2 == -1) {
3614 		if (fn->fd2 != -1)
3615 		    zclose(fn->fd2);
3616 		closemnodes(mfds);
3617 		fixfds(save);
3618 		execerr();
3619 	    }
3620 	    addfd(forked, save, mfds, fn->fd1, fn->fd2, 1, fn->varid);
3621 	} else {
3622 	    int closed;
3623 	    if (fn->type != REDIR_HERESTR && xpandredir(fn, redir))
3624 		continue;
3625 	    if (errflag) {
3626 		closemnodes(mfds);
3627 		fixfds(save);
3628 		execerr();
3629 	    }
3630 	    if (isset(RESTRICTED) && IS_WRITE_FILE(fn->type)) {
3631 		zwarn("writing redirection not allowed in restricted mode");
3632 		execerr();
3633 	    }
3634 	    if (unset(EXECOPT))
3635 		continue;
3636 	    switch(fn->type) {
3637 	    case REDIR_HERESTR:
3638 		if (!checkclobberparam(fn))
3639 		    fil = -1;
3640 		else
3641 		    fil = getherestr(fn);
3642 		if (fil == -1) {
3643 		    if (errno && errno != EINTR)
3644 			zwarn("can't create temp file for here document: %e",
3645 			      errno);
3646 		    closemnodes(mfds);
3647 		    fixfds(save);
3648 		    execerr();
3649 		}
3650 		addfd(forked, save, mfds, fn->fd1, fil, 0, fn->varid);
3651 		break;
3652 	    case REDIR_READ:
3653 	    case REDIR_READWRITE:
3654 		if (!checkclobberparam(fn))
3655 		    fil = -1;
3656 		else if (fn->type == REDIR_READ)
3657 		    fil = open(unmeta(fn->name), O_RDONLY | O_NOCTTY);
3658 		else
3659 		    fil = open(unmeta(fn->name),
3660 			       O_RDWR | O_CREAT | O_NOCTTY, 0666);
3661 		if (fil == -1) {
3662 		    closemnodes(mfds);
3663 		    fixfds(save);
3664 		    if (errno != EINTR)
3665 			zwarn("%e: %s", errno, fn->name);
3666 		    execerr();
3667 		}
3668 		addfd(forked, save, mfds, fn->fd1, fil, 0, fn->varid);
3669 		/* If this is 'exec < file', read from stdin, *
3670 		 * not terminal, unless `file' is a terminal. */
3671 		if (nullexec == 1 && fn->fd1 == 0 &&
3672 		    isset(SHINSTDIN) && interact && !zleactive)
3673 		    init_io(NULL);
3674 		break;
3675 	    case REDIR_CLOSE:
3676 		if (fn->varid) {
3677 		    char *s = fn->varid, *t;
3678 		    struct value vbuf;
3679 		    Value v;
3680 		    int bad = 0;
3681 
3682 		    if (!(v = getvalue(&vbuf, &s, 0))) {
3683 			bad = 1;
3684 		    } else if (v->pm->node.flags & PM_READONLY) {
3685 			bad = 2;
3686 		    } else {
3687 			s = getstrvalue(v);
3688 			if (errflag)
3689 			    bad = 1;
3690 			else {
3691 			    fn->fd1 = zstrtol(s, &t, 0);
3692 			    if (s == t)
3693 				bad = 1;
3694 			    else if (*t) {
3695 				/* Check for base#number format */
3696 				if (*t == '#' && *s != '0')
3697 				    fn->fd1 = zstrtol(s = t+1, &t, fn->fd1);
3698 				if (s == t || *t)
3699 				    bad = 1;
3700 			    }
3701 			    if (!bad && fn->fd1 <= max_zsh_fd) {
3702 				if (fn->fd1 >= 10 &&
3703 				    (fdtable[fn->fd1] & FDT_TYPE_MASK) ==
3704 				    FDT_INTERNAL)
3705 				    bad = 3;
3706 			    }
3707 			}
3708 		    }
3709 		    if (bad) {
3710 			const char *bad_msg[] = {
3711 			    "parameter %s does not contain a file descriptor",
3712 			    "can't close file descriptor from readonly parameter %s",
3713 			    "file descriptor %d used by shell, not closed"
3714 			};
3715 			if (bad > 2)
3716 			    zwarn(bad_msg[bad-1], fn->fd1);
3717 			else
3718 			    zwarn(bad_msg[bad-1], fn->varid);
3719 			execerr();
3720 		    }
3721 		}
3722 		/*
3723 		 * Note we may attempt to close an fd beyond max_zsh_fd:
3724 		 * OK as long as we never look in fdtable for it.
3725  		 */
3726 		closed = 0;
3727 		if (!forked && fn->fd1 < 10 && save[fn->fd1] == -2) {
3728 		    save[fn->fd1] = movefd(fn->fd1);
3729 		    if (save[fn->fd1] >= 0) {
3730 			/*
3731 			 * The original fd is now closed, we don't need
3732 			 * to do it below.
3733 			 */
3734 			closed = 1;
3735 		    }
3736 		}
3737 		if (fn->fd1 < 10)
3738 		    closemn(mfds, fn->fd1, REDIR_CLOSE);
3739 		/*
3740 		 * Only report failures to close file descriptors
3741 		 * if they're under user control as we don't know
3742 		 * what the previous status of others was.
3743 		 */
3744 		if (!closed && zclose(fn->fd1) < 0 && fn->varid) {
3745 		    zwarn("failed to close file descriptor %d: %e",
3746 			  fn->fd1, errno);
3747 		}
3748 		break;
3749 	    case REDIR_MERGEIN:
3750 	    case REDIR_MERGEOUT:
3751 		if (fn->fd2 < 10)
3752 		    closemn(mfds, fn->fd2, fn->type);
3753 		if (!checkclobberparam(fn))
3754 		    fil = -1;
3755 		else if (fn->fd2 > 9 &&
3756 			 /*
3757 			  * If the requested fd is > max_zsh_fd,
3758 			  * the shell doesn't know about it.
3759 			  * Just assume the user knows what they're
3760 			  * doing.
3761 			  */
3762 			 (fn->fd2 <= max_zsh_fd &&
3763 			  ((fdtable[fn->fd2] != FDT_UNUSED &&
3764 			    fdtable[fn->fd2] != FDT_EXTERNAL) ||
3765 			   fn->fd2 == coprocin ||
3766 			   fn->fd2 == coprocout))) {
3767 		    fil = -1;
3768 		    errno = EBADF;
3769 		} else {
3770 		    int fd = fn->fd2;
3771 		    if(fd == -2)
3772 			fd = (fn->type == REDIR_MERGEOUT) ? coprocout : coprocin;
3773 		    fil = movefd(dup(fd));
3774 		}
3775 		if (fil == -1) {
3776 		    char fdstr[DIGBUFSIZE];
3777 
3778 		    closemnodes(mfds);
3779 		    fixfds(save);
3780 		    if (fn->fd2 != -2)
3781 		    	sprintf(fdstr, "%d", fn->fd2);
3782 		    if (errno)
3783 			zwarn("%s: %e", fn->fd2 == -2 ? "coprocess" : fdstr,
3784 			      errno);
3785 		    execerr();
3786 		}
3787 		addfd(forked, save, mfds, fn->fd1, fil,
3788 		      fn->type == REDIR_MERGEOUT, fn->varid);
3789 		break;
3790 	    default:
3791 		if (!checkclobberparam(fn))
3792 		    fil = -1;
3793 		else if (IS_APPEND_REDIR(fn->type))
3794 		    fil = open(unmeta(fn->name),
3795 			       ((unset(CLOBBER) && unset(APPENDCREATE)) &&
3796 				!IS_CLOBBER_REDIR(fn->type)) ?
3797 			       O_WRONLY | O_APPEND | O_NOCTTY :
3798 			       O_WRONLY | O_APPEND | O_CREAT | O_NOCTTY, 0666);
3799 		else
3800 		    fil = clobber_open(fn);
3801 		if(fil != -1 && IS_ERROR_REDIR(fn->type))
3802 		    dfil = movefd(dup(fil));
3803 		else
3804 		    dfil = 0;
3805 		if (fil == -1 || dfil == -1) {
3806 		    if(fil != -1)
3807 			close(fil);
3808 		    closemnodes(mfds);
3809 		    fixfds(save);
3810 		    if (errno && errno != EINTR)
3811 			zwarn("%e: %s", errno, fn->name);
3812 		    execerr();
3813 		}
3814 		addfd(forked, save, mfds, fn->fd1, fil, 1, fn->varid);
3815 		if(IS_ERROR_REDIR(fn->type))
3816 		    addfd(forked, save, mfds, 2, dfil, 1, NULL);
3817 		break;
3818 	    }
3819 	    /* May be error in addfd due to setting parameter. */
3820 	    if (errflag) {
3821 		closemnodes(mfds);
3822 		fixfds(save);
3823 		execerr();
3824 	    }
3825 	}
3826     }
3827 
3828     /* We are done with redirection.  close the mnodes, *
3829      * spawning tee/cat processes as necessary.         */
3830     for (i = 0; i < 10; i++)
3831 	if (mfds[i] && mfds[i]->ct >= 2)
3832 	    closemn(mfds, i, REDIR_CLOSE);
3833 
3834     if (nullexec) {
3835 	/*
3836 	 * If nullexec is 2, we have variables to add with the redirections
3837 	 * in place.  If nullexec is 1, we may have variables but they
3838 	 * need the standard restore logic.
3839 	 */
3840 	if (varspc) {
3841 	    LinkList restorelist = 0, removelist = 0;
3842 	    if (!isset(POSIXBUILTINS) && nullexec != 2)
3843 		save_params(state, varspc, &restorelist, &removelist);
3844 	    addvars(state, varspc, 0);
3845 	    if (restorelist)
3846 		restore_params(restorelist, removelist);
3847 	}
3848 	lastval = errflag ? errflag : cmdoutval;
3849 	if (nullexec == 1) {
3850 	    /*
3851 	     * If nullexec is 1 we specifically *don't* restore the original
3852 	     * fd's before returning.
3853 	     */
3854 	    for (i = 0; i < 10; i++)
3855 		if (save[i] != -2)
3856 		    zclose(save[i]);
3857 	    goto done;
3858 	}
3859 	if (isset(XTRACE)) {
3860 	    fputc('\n', xtrerr);
3861 	    fflush(xtrerr);
3862 	}
3863     } else if (isset(EXECOPT) && !errflag) {
3864 	int q = queue_signal_level();
3865 	/*
3866 	 * We delay the entersubsh() to here when we are exec'ing
3867 	 * the current shell (including a fake exec to run a builtin then
3868 	 * exit) in case there is an error return.
3869 	 */
3870 	if (is_exec) {
3871 	    int flags = ((how & Z_ASYNC) ? ESUB_ASYNC : 0) |
3872 		ESUB_PGRP | ESUB_FAKE;
3873 	    if (type != WC_SUBSH)
3874 		flags |= ESUB_KEEPTRAP;
3875 	    if ((do_exec || (type >= WC_CURSH && last1 == 1))
3876 		&& !forked)
3877 		flags |= ESUB_REVERTPGRP;
3878 	    entersubsh(flags, NULL);
3879 	}
3880 	if (type == WC_FUNCDEF) {
3881 	    Eprog redir_prog;
3882 	    if (!redir && wc_code(*eparams->beg) == WC_REDIR)  {
3883 		/*
3884 		 * We're not using a redirection from the currently
3885 		 * parsed environment, which is what we'd do for an
3886 		 * anonymous function, but there are redirections we
3887 		 * should store with the new function.
3888 		 */
3889 		struct estate s;
3890 
3891 		s.prog = state->prog;
3892 		s.pc = eparams->beg;
3893 		s.strs = state->prog->strs;
3894 
3895 		/*
3896 		 * The copy uses the wordcode parsing area, so save and
3897 		 * restore state.
3898 		 */
3899 		zcontext_save();
3900 		redir_prog = eccopyredirs(&s);
3901 		zcontext_restore();
3902 	    } else
3903 		redir_prog = NULL;
3904 
3905 	    dont_queue_signals();
3906 	    lastval = execfuncdef(state, redir_prog);
3907 	    restore_queue_signals(q);
3908 	}
3909 	else if (type >= WC_CURSH) {
3910 	    if (last1 == 1)
3911 		do_exec = 1;
3912 	    dont_queue_signals();
3913 	    if (type == WC_AUTOFN) {
3914 		/*
3915 		 * We pre-loaded this to get any redirs.
3916 		 * So we execuate a simplified function here.
3917 		 */
3918 		lastval =  execautofn_basic(state, do_exec);
3919 	    } else
3920 		lastval = (execfuncs[type - WC_CURSH])(state, do_exec);
3921 	    restore_queue_signals(q);
3922 	} else if (is_builtin || is_shfunc) {
3923 	    LinkList restorelist = 0, removelist = 0;
3924 	    int do_save = 0;
3925 	    /* builtin or shell function */
3926 
3927 	    if (!forked) {
3928 		if (isset(POSIXBUILTINS)) {
3929 		    /*
3930 		     * If it's a function or special builtin --- save
3931 		     * if it's got "command" in front.
3932 		     * If it's a normal command --- save.
3933 		     */
3934 		    if (is_shfunc || (hn->flags & (BINF_PSPECIAL|BINF_ASSIGN)))
3935 			do_save = (orig_cflags & BINF_COMMAND);
3936 		    else
3937 			do_save = 1;
3938 		} else {
3939 		    /*
3940 		     * Save if it's got "command" in front or it's
3941 		     * not a magic-equals assignment.
3942 		     */
3943 		    if ((cflags & (BINF_COMMAND|BINF_ASSIGN)) || !magic_assign)
3944 			do_save = 1;
3945 		}
3946 		if (do_save && varspc)
3947 		    save_params(state, varspc, &restorelist, &removelist);
3948 	    }
3949 	    if (varspc) {
3950 		/* Export this if the command is a shell function,
3951 		 * but not if it's a builtin.
3952 		 */
3953 		int flags = 0;
3954 		if (is_shfunc)
3955 		    flags |= ADDVAR_EXPORT;
3956 		if (restorelist)
3957 		    flags |= ADDVAR_RESTORE;
3958 
3959 		addvars(state, varspc, flags);
3960 		if (errflag) {
3961 		    if (restorelist)
3962 			restore_params(restorelist, removelist);
3963 		    lastval = 1;
3964 		    fixfds(save);
3965 		    goto done;
3966 		}
3967 	    }
3968 
3969 	    if (is_shfunc) {
3970 		/* It's a shell function */
3971 		pipecleanfilelist(filelist, 0);
3972 		execshfunc((Shfunc) hn, args);
3973 	    } else {
3974 		/* It's a builtin */
3975 		LinkList assigns = (LinkList)0;
3976 		int postassigns = eparams->postassigns;
3977 		if (forked)
3978 		    closem(FDT_INTERNAL, 0);
3979 		if (postassigns) {
3980 		    Wordcode opc = state->pc;
3981 		    state->pc = eparams->assignspc;
3982 		    assigns = newlinklist();
3983 		    while (postassigns--) {
3984 			int htok;
3985 			wordcode ac = *state->pc++;
3986 			char *name = ecgetstr(state, EC_DUPTOK, &htok);
3987 			Asgment asg;
3988 			local_list1(svl);
3989 
3990 			DPUTS(wc_code(ac) != WC_ASSIGN,
3991 			      "BUG: bad assignment list for typeset");
3992 			if (htok) {
3993 			    init_list1(svl, name);
3994 			    if (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR &&
3995 				WC_ASSIGN_TYPE2(ac) == WC_ASSIGN_INC) {
3996 				char *data;
3997 				/*
3998 				 * Special case: this is a name only, so
3999 				 * it's not required to be a single
4000 				 * expansion.  Furthermore, for
4001 				 * consistency with the builtin
4002 				 * interface, it may expand into
4003 				 * scalar assignments:
4004 				 *  ass=(one=two three=four)
4005 				 *  typeset a=b $ass
4006 				 */
4007 				/* Unused dummy value for name */
4008 				(void)ecgetstr(state, EC_DUPTOK, &htok);
4009 				prefork(&svl, PREFORK_TYPESET, NULL);
4010 				if (errflag) {
4011 				    state->pc = opc;
4012 				    break;
4013 				}
4014 				globlist(&svl, 0);
4015 				if (errflag) {
4016 				    state->pc = opc;
4017 				    break;
4018 				}
4019 				while ((data = ugetnode(&svl))) {
4020 				    char *ptr;
4021 				    asg = (Asgment)zhalloc(sizeof(struct asgment));
4022 				    asg->flags = 0;
4023 				    if ((ptr = strchr(data, '='))) {
4024 					*ptr++ = '\0';
4025 					asg->name = data;
4026 					asg->value.scalar = ptr;
4027 				    } else {
4028 					asg->name = data;
4029 					asg->value.scalar = NULL;
4030 				    }
4031 				    uaddlinknode(assigns, &asg->node);
4032 				}
4033 				continue;
4034 			    }
4035 			    prefork(&svl, PREFORK_SINGLE, NULL);
4036 			    name = empty(&svl) ? "" :
4037 				(char *)getdata(firstnode(&svl));
4038 			}
4039 			untokenize(name);
4040 			asg = (Asgment)zhalloc(sizeof(struct asgment));
4041 			asg->name = name;
4042 			if (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR) {
4043 			    char *val = ecgetstr(state, EC_DUPTOK, &htok);
4044 			    asg->flags = 0;
4045 			    if (WC_ASSIGN_TYPE2(ac) == WC_ASSIGN_INC) {
4046 				/* Fake assignment, no value */
4047 				asg->value.scalar = NULL;
4048 			    } else {
4049 				if (htok) {
4050 				    init_list1(svl, val);
4051 				    prefork(&svl,
4052 					    PREFORK_SINGLE|PREFORK_ASSIGN,
4053 					    NULL);
4054 				    if (errflag) {
4055 					state->pc = opc;
4056 					break;
4057 				    }
4058 				    /*
4059 				     * No globassign for typeset
4060 				     * arguments, thank you
4061 				     */
4062 				    val = empty(&svl) ? "" :
4063 					(char *)getdata(firstnode(&svl));
4064 				}
4065 				untokenize(val);
4066 				asg->value.scalar = val;
4067 			    }
4068 			} else {
4069 			    asg->flags = ASG_ARRAY;
4070 			    asg->value.array =
4071 				ecgetlist(state, WC_ASSIGN_NUM(ac),
4072 					  EC_DUPTOK, &htok);
4073 			    if (asg->value.array)
4074 			    {
4075 				if (!errflag) {
4076 				    int prefork_ret = 0;
4077 				    prefork(asg->value.array, PREFORK_ASSIGN,
4078 					    &prefork_ret);
4079 				    if (errflag) {
4080 					state->pc = opc;
4081 					break;
4082 				    }
4083 				    if (prefork_ret & PREFORK_KEY_VALUE)
4084 					asg->flags |= ASG_KEY_VALUE;
4085 				    globlist(asg->value.array, prefork_ret);
4086 				}
4087 				if (errflag) {
4088 				    state->pc = opc;
4089 				    break;
4090 				}
4091 			    }
4092 			}
4093 
4094 			uaddlinknode(assigns, &asg->node);
4095 		    }
4096 		    state->pc = opc;
4097 		}
4098 		dont_queue_signals();
4099 		if (!errflag) {
4100 		    int ret = execbuiltin(args, assigns, (Builtin) hn);
4101 		    /*
4102 		     * In case of interruption assume builtin status
4103 		     * is less useful than what interrupt set.
4104 		     */
4105 		    if (!(errflag & ERRFLAG_INT))
4106 			lastval = ret;
4107 		}
4108 		if (do_save & BINF_COMMAND)
4109 		    errflag &= ~ERRFLAG_ERROR;
4110 		restore_queue_signals(q);
4111 		fflush(stdout);
4112 		if (save[1] == -2) {
4113 		    if (ferror(stdout)) {
4114 			zwarn("write error: %e", errno);
4115 			clearerr(stdout);
4116 		    }
4117 		} else
4118 		    clearerr(stdout);
4119 	    }
4120 	    if (isset(PRINTEXITVALUE) && isset(SHINSTDIN) &&
4121 		lastval && !subsh) {
4122 #if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD)
4123 		fprintf(stderr, "zsh: exit %lld\n", lastval);
4124 #else
4125 		fprintf(stderr, "zsh: exit %ld\n", (long)lastval);
4126 #endif
4127 		fflush(stderr);
4128 	    }
4129 
4130 	    if (do_exec) {
4131 		if (subsh)
4132 		    _realexit();
4133 
4134 		/* If we are exec'ing a command, and we are not in a subshell, *
4135 		 * then check if we should save the history file.              */
4136 		if (isset(RCS) && interact && !nohistsave)
4137 		    savehistfile(NULL, 1, HFILE_USE_OPTIONS);
4138 		realexit();
4139 	    }
4140 	    if (restorelist)
4141 		restore_params(restorelist, removelist);
4142 
4143 	} else {
4144 	    if (!subsh) {
4145 	        /* for either implicit or explicit "exec", decrease $SHLVL
4146 		 * as we're now done as a shell */
4147 		if (!forked)
4148 		    setiparam("SHLVL", --shlvl);
4149 
4150 		/* If we are exec'ing a command, and we are not *
4151 		 * in a subshell, then save the history file.   */
4152 		if (do_exec && isset(RCS) && interact && !nohistsave)
4153 		    savehistfile(NULL, 1, HFILE_USE_OPTIONS);
4154 	    }
4155 	    if (type == WC_SIMPLE || type == WC_TYPESET) {
4156 		if (varspc) {
4157 		    int addflags = ADDVAR_EXPORT|ADDVAR_RESTRICT;
4158 		    if (forked)
4159 			addflags |= ADDVAR_RESTORE;
4160 		    addvars(state, varspc, addflags);
4161 		    if (errflag)
4162 			_exit(1);
4163 		}
4164 		closem(FDT_INTERNAL, 0);
4165 		if (coprocin != -1) {
4166 		    zclose(coprocin);
4167 		    coprocin = -1;
4168 		}
4169 		if (coprocout != -1) {
4170 		    zclose(coprocout);
4171 		    coprocout = -1;
4172 		}
4173 #ifdef HAVE_GETRLIMIT
4174 		if (!forked)
4175 		    setlimits(NULL);
4176 #endif
4177 		if (how & Z_ASYNC) {
4178 		    zsfree(STTYval);
4179 		    STTYval = 0;
4180 		}
4181 		execute(args, cflags, use_defpath);
4182 	    } else {		/* ( ... ) */
4183 		DPUTS(varspc,
4184 		      "BUG: assignment before complex command");
4185 		list_pipe = 0;
4186 		pipecleanfilelist(filelist, 0);
4187 		/* If we're forked (and we should be), no need to return */
4188 		DPUTS(last1 != 1 && !forked, "BUG: not exiting?");
4189 		DPUTS(type != WC_SUBSH, "Not sure what we're doing.");
4190 		/* Skip word only used for try/always blocks */
4191 		state->pc++;
4192 		execlist(state, 0, 1);
4193 	    }
4194 	}
4195     }
4196 
4197   err:
4198     if (forked) {
4199 	/*
4200 	 * So what's going on here then?  Well, I'm glad you asked.
4201 	 *
4202 	 * If we create multios for use in a subshell we do
4203 	 * this after forking, in this function above.  That
4204 	 * means that the current (sub)process is responsible
4205 	 * for clearing them up.  However, the processes won't
4206 	 * go away until we have closed the fd's talking to them.
4207 	 * Since we're about to exit the shell there's nothing
4208 	 * to stop us closing all fd's (including the ones 0 to 9
4209 	 * that we usually leave alone).
4210 	 *
4211 	 * Then we wait for any processes.  When we forked,
4212 	 * we cleared the jobtable and started a new job just for
4213 	 * any oddments like this, so if there aren't any we won't
4214 	 * need to wait.  The result of not waiting is that
4215 	 * the multios haven't flushed the fd's properly, leading
4216 	 * to obscure missing data.
4217 	 *
4218 	 * It would probably be cleaner to ensure that the
4219 	 * parent shell handled multios, but that requires
4220 	 * some architectural changes which are likely to be
4221 	 * hairy.
4222 	 */
4223 	for (i = 0; i < 10; i++)
4224 	    if (fdtable[i] != FDT_UNUSED)
4225 		close(i);
4226 	closem(FDT_UNUSED, 1);
4227 	if (thisjob != -1)
4228 	    waitjobs();
4229 	_realexit();
4230     }
4231     fixfds(save);
4232 
4233  done:
4234     if (isset(POSIXBUILTINS) &&
4235 	(cflags & (BINF_PSPECIAL|BINF_EXEC)) &&
4236 	!(orig_cflags & BINF_COMMAND)) {
4237 	/*
4238 	 * For POSIX-compatible behaviour with special
4239 	 * builtins (including exec which we don't usually
4240 	 * classify as a builtin) we treat all errors as fatal.
4241 	 * The "command" builtin is not special so resets this behaviour.
4242 	 */
4243 	forked |= zsh_subshell;
4244     fatal:
4245 	if (redir_err || errflag) {
4246 	    if (!isset(INTERACTIVE)) {
4247 		if (forked)
4248 		    _exit(1);
4249 		else
4250 		    exit(1);
4251 	    }
4252 	    errflag |= ERRFLAG_ERROR;
4253 	}
4254     }
4255     if (newxtrerr) {
4256 	fil = fileno(newxtrerr);
4257 	fclose(newxtrerr);
4258 	xtrerr = oxtrerr;
4259 	zclose(fil);
4260     }
4261 
4262     zsfree(STTYval);
4263     STTYval = 0;
4264     if (oautocont >= 0)
4265 	opts[AUTOCONTINUE] = oautocont;
4266 }
4267 
4268 /* Arrange to have variables restored. */
4269 
4270 /**/
4271 static void
save_params(Estate state,Wordcode pc,LinkList * restore_p,LinkList * remove_p)4272 save_params(Estate state, Wordcode pc, LinkList *restore_p, LinkList *remove_p)
4273 {
4274     Param pm;
4275     char *s;
4276     wordcode ac;
4277 
4278     *restore_p = newlinklist();
4279     *remove_p = newlinklist();
4280 
4281     while (wc_code(ac = *pc) == WC_ASSIGN) {
4282 	s = ecrawstr(state->prog, pc + 1, NULL);
4283 	if ((pm = (Param) paramtab->getnode(paramtab, s))) {
4284 	    Param tpm;
4285 	    if (pm->env)
4286 		delenv(pm);
4287 	    if (!(pm->node.flags & PM_SPECIAL)) {
4288 		/*
4289 		 * We used to remove ordinary parameters from the
4290 		 * table, but that meant "HELLO=$HELLO shellfunc"
4291 		 * failed because the expansion of $HELLO hasn't
4292 		 * been done at this point.  Instead, copy the
4293 		 * parameter:  in this case, we'll insert the
4294 		 * copied parameter straight back into the parameter
4295 		 * table so we want to be sure everything is
4296 		 * properly set up and in permanent memory.
4297 		 */
4298 		tpm = (Param) zshcalloc(sizeof *tpm);
4299 		tpm->node.nam = ztrdup(pm->node.nam);
4300 		copyparam(tpm, pm, 0);
4301 		pm = tpm;
4302 	    } else if (!(pm->node.flags & PM_READONLY) &&
4303 		       (unset(RESTRICTED) || !(pm->node.flags & PM_RESTRICTED))) {
4304 		/*
4305 		 * In this case we're just saving parts of
4306 		 * the parameter in a temporary, so use heap allocation
4307 		 * and don't bother copying every detail.
4308 		 */
4309 		tpm = (Param) hcalloc(sizeof *tpm);
4310 		tpm->node.nam = pm->node.nam;
4311 		copyparam(tpm, pm, 1);
4312 		pm = tpm;
4313 	    }
4314 	    addlinknode(*remove_p, dupstring(s));
4315 	    addlinknode(*restore_p, pm);
4316 	} else
4317 	    addlinknode(*remove_p, dupstring(s));
4318 
4319 	pc += (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR ?
4320 	       3 : WC_ASSIGN_NUM(ac) + 2);
4321     }
4322 }
4323 
4324 /* Restore saved parameters after executing a shfunc or builtin */
4325 
4326 /**/
4327 static void
restore_params(LinkList restorelist,LinkList removelist)4328 restore_params(LinkList restorelist, LinkList removelist)
4329 {
4330     Param pm;
4331     char *s;
4332 
4333     /* remove temporary parameters */
4334     while ((s = (char *) ugetnode(removelist))) {
4335 	if ((pm = (Param) paramtab->getnode(paramtab, s)) &&
4336 	    !(pm->node.flags & PM_SPECIAL)) {
4337 	    pm->node.flags &= ~PM_READONLY;
4338 	    unsetparam_pm(pm, 0, 0);
4339 	}
4340     }
4341 
4342     if (restorelist) {
4343 	/* restore saved parameters */
4344 	while ((pm = (Param) ugetnode(restorelist))) {
4345 	    if (pm->node.flags & PM_SPECIAL) {
4346 		Param tpm = (Param) paramtab->getnode(paramtab, pm->node.nam);
4347 
4348 		DPUTS(!tpm || PM_TYPE(pm->node.flags) != PM_TYPE(tpm->node.flags) ||
4349 		      !(pm->node.flags & PM_SPECIAL),
4350 		      "BUG: in restoring special parameters");
4351 		if (!pm->env && tpm->env)
4352 		    delenv(tpm);
4353 		tpm->node.flags = pm->node.flags;
4354 		switch (PM_TYPE(pm->node.flags)) {
4355 		case PM_SCALAR:
4356 		    tpm->gsu.s->setfn(tpm, pm->u.str);
4357 		    break;
4358 		case PM_INTEGER:
4359 		    tpm->gsu.i->setfn(tpm, pm->u.val);
4360 		    break;
4361 		case PM_EFLOAT:
4362 		case PM_FFLOAT:
4363 		    tpm->gsu.f->setfn(tpm, pm->u.dval);
4364 		    break;
4365 		case PM_ARRAY:
4366 		    tpm->gsu.a->setfn(tpm, pm->u.arr);
4367 		    break;
4368 		case PM_HASHED:
4369 		    tpm->gsu.h->setfn(tpm, pm->u.hash);
4370 		    break;
4371 		}
4372 		pm = tpm;
4373 	    } else {
4374 		paramtab->addnode(paramtab, pm->node.nam, pm);
4375 	    }
4376 	    if ((pm->node.flags & PM_EXPORTED) && ((s = getsparam(pm->node.nam))))
4377 		addenv(pm, s);
4378 	}
4379     }
4380 }
4381 
4382 /* restore fds after redirecting a builtin */
4383 
4384 /**/
4385 static void
fixfds(int * save)4386 fixfds(int *save)
4387 {
4388     int old_errno = errno;
4389     int i;
4390 
4391     for (i = 0; i != 10; i++)
4392 	if (save[i] != -2)
4393 	    redup(save[i], i);
4394     errno = old_errno;
4395 }
4396 
4397 /*
4398  * Close internal shell fds.
4399  *
4400  * Close any that are marked as used if "how" is FDT_UNUSED, else
4401  * close any with the value "how".
4402  *
4403  * If "all" is zero, we'll skip cases where we need the file
4404  * descriptor to be visible externally.
4405  */
4406 
4407 /**/
4408 mod_export void
closem(int how,int all)4409 closem(int how, int all)
4410 {
4411     int i;
4412 
4413     for (i = 10; i <= max_zsh_fd; i++)
4414 	if (fdtable[i] != FDT_UNUSED &&
4415 	    /*
4416 	     * Process substitution needs to be visible to user;
4417 	     * fd's are explicitly cleaned up by filelist handling.
4418 	     * External FDs are managed directly by the user.
4419 	     */
4420 	    (all || (fdtable[i] != FDT_PROC_SUBST &&
4421 		     fdtable[i] != FDT_EXTERNAL)) &&
4422 	    (how == FDT_UNUSED || (fdtable[i] & FDT_TYPE_MASK) == how)) {
4423 	    if (i == SHTTY)
4424 		SHTTY = -1;
4425 	    zclose(i);
4426 	}
4427 }
4428 
4429 /* convert here document into a here string */
4430 
4431 /**/
4432 char *
gethere(char ** strp,int typ)4433 gethere(char **strp, int typ)
4434 {
4435     char *buf;
4436     int bsiz, qt = 0, strip = 0;
4437     char *s, *t, *bptr, c;
4438     char *str = *strp;
4439 
4440     for (s = str; *s; s++)
4441 	if (inull(*s)) {
4442 	    qt = 1;
4443 	    break;
4444 	}
4445     str = quotesubst(str);
4446     untokenize(str);
4447     if (typ == REDIR_HEREDOCDASH) {
4448 	strip = 1;
4449 	while (*str == '\t')
4450 	    str++;
4451     }
4452     *strp = str;
4453     bptr = buf = zalloc(bsiz = 256);
4454     for (;;) {
4455 	t = bptr;
4456 
4457 	while ((c = hgetc()) == '\t' && strip)
4458 	    ;
4459 	for (;;) {
4460 	    if (bptr >= buf + bsiz - 2) {
4461 		ptrdiff_t toff = t - buf;
4462 		ptrdiff_t bptroff = bptr - buf;
4463 		char *newbuf = realloc(buf, 2 * bsiz);
4464 		if (!newbuf) {
4465 		    /* out of memory */
4466 		    zfree(buf, bsiz);
4467 		    return NULL;
4468 		}
4469 		buf = newbuf;
4470 		t = buf + toff;
4471 		bptr = buf + bptroff;
4472 		bsiz *= 2;
4473 	    }
4474 	    if (lexstop || c == '\n')
4475 		break;
4476 	    if (!qt && c == '\\') {
4477 		*bptr++ = c;
4478 		c = hgetc();
4479 		if (c == '\n') {
4480 		    bptr--;
4481 		    c = hgetc();
4482 		    continue;
4483 		}
4484 	    }
4485 	    *bptr++ = c;
4486 	    c = hgetc();
4487 	}
4488 	*bptr = '\0';
4489 	if (!strcmp(t, str))
4490 	    break;
4491 	if (lexstop) {
4492 	    t = bptr;
4493 	    break;
4494 	}
4495 	*bptr++ = '\n';
4496     }
4497     *t = '\0';
4498     s = buf;
4499     buf = dupstring(buf);
4500     zfree(s, bsiz);
4501     if (!qt) {
4502 	int ef = errflag;
4503 
4504 	parsestr(&buf);
4505 
4506 	if (!(errflag & ERRFLAG_ERROR)) {
4507 	    /* Retain any user interrupt error */
4508 	    errflag = ef | (errflag & ERRFLAG_INT);
4509 	}
4510     }
4511     return buf;
4512 }
4513 
4514 /* open here string fd */
4515 
4516 /**/
4517 static int
getherestr(struct redir * fn)4518 getherestr(struct redir *fn)
4519 {
4520     char *s, *t;
4521     int fd, len;
4522 
4523     t = fn->name;
4524     singsub(&t);
4525     untokenize(t);
4526     unmetafy(t, &len);
4527     /*
4528      * For real here-strings we append a newline, as if the
4529      * string given was a complete command line.
4530      *
4531      * For here-strings from here documents, we use the original
4532      * text exactly.
4533      */
4534     if (!(fn->flags & REDIRF_FROM_HEREDOC))
4535 	t[len++] = '\n';
4536     if ((fd = gettempfile(NULL, 1, &s)) < 0)
4537 	return -1;
4538     write_loop(fd, t, len);
4539     close(fd);
4540     fd = open(s, O_RDONLY | O_NOCTTY);
4541     unlink(s);
4542     return fd;
4543 }
4544 
4545 /*
4546  * Test if some wordcode starts with a simple redirection of type
4547  * redir_type.  If it does, return the name of the file, copied onto
4548  * the heap.  If it doesn't, return NULL.
4549  */
4550 
4551 static char *
simple_redir_name(Eprog prog,int redir_type)4552 simple_redir_name(Eprog prog, int redir_type)
4553 {
4554     Wordcode pc;
4555 
4556     pc = prog->prog;
4557     if (prog != &dummy_eprog &&
4558 	wc_code(pc[0]) == WC_LIST && (WC_LIST_TYPE(pc[0]) & Z_END) &&
4559 	wc_code(pc[1]) == WC_SUBLIST && !WC_SUBLIST_FLAGS(pc[1]) &&
4560 	WC_SUBLIST_TYPE(pc[1]) == WC_SUBLIST_END &&
4561 	wc_code(pc[2]) == WC_PIPE && WC_PIPE_TYPE(pc[2]) == WC_PIPE_END &&
4562 	wc_code(pc[3]) == WC_REDIR && WC_REDIR_TYPE(pc[3]) == redir_type &&
4563 	!WC_REDIR_VARID(pc[3]) &&
4564 	!pc[4] &&
4565 	wc_code(pc[6]) == WC_SIMPLE && !WC_SIMPLE_ARGC(pc[6])) {
4566 	return dupstring(ecrawstr(prog, pc + 5, NULL));
4567     }
4568 
4569     return NULL;
4570 }
4571 
4572 /* $(...) */
4573 
4574 /**/
4575 LinkList
getoutput(char * cmd,int qt)4576 getoutput(char *cmd, int qt)
4577 {
4578     Eprog prog;
4579     int pipes[2];
4580     pid_t pid;
4581     char *s;
4582 
4583     int onc = nocomments;
4584     nocomments = (interact && unset(INTERACTIVECOMMENTS));
4585     prog = parse_string(cmd, 0);
4586     nocomments = onc;
4587 
4588     if (!prog)
4589 	return NULL;
4590 
4591     if ((s = simple_redir_name(prog, REDIR_READ))) {
4592 	/* $(< word) */
4593 	int stream;
4594 	LinkList retval;
4595 	int readerror;
4596 
4597 	singsub(&s);
4598 	if (errflag)
4599 	    return NULL;
4600 	untokenize(s);
4601 	if ((stream = open(unmeta(s), O_RDONLY | O_NOCTTY)) == -1) {
4602 	    zwarn("%e: %s", errno, s);
4603 	    lastval = cmdoutval = 1;
4604 	    return newlinklist();
4605 	}
4606 	retval = readoutput(stream, qt, &readerror);
4607 	if (readerror) {
4608 	  zwarn("error when reading %s: %e", s, readerror);
4609 	  lastval = cmdoutval = 1;
4610 	}
4611 	return retval;
4612     }
4613     if (mpipe(pipes) < 0) {
4614 	errflag |= ERRFLAG_ERROR;
4615 	cmdoutpid = 0;
4616 	return NULL;
4617     }
4618     child_block();
4619     cmdoutval = 0;
4620     if ((cmdoutpid = pid = zfork(NULL)) == -1) {
4621 	/* fork error */
4622 	zclose(pipes[0]);
4623 	zclose(pipes[1]);
4624 	errflag |= ERRFLAG_ERROR;
4625 	cmdoutpid = 0;
4626 	child_unblock();
4627 	return NULL;
4628     } else if (pid) {
4629 	LinkList retval;
4630 
4631 	zclose(pipes[1]);
4632 	retval = readoutput(pipes[0], qt, NULL);
4633 	fdtable[pipes[0]] = FDT_UNUSED;
4634 	waitforpid(pid, 0);		/* unblocks */
4635 	lastval = cmdoutval;
4636 	return retval;
4637     }
4638     /* pid == 0 */
4639     child_unblock();
4640     zclose(pipes[0]);
4641     redup(pipes[1], 1);
4642     entersubsh(ESUB_PGRP|ESUB_NOMONITOR, NULL);
4643     cmdpush(CS_CMDSUBST);
4644     execode(prog, 0, 1, "cmdsubst");
4645     cmdpop();
4646     close(1);
4647     _realexit();
4648     zerr("exit returned in child!!");
4649     kill(getpid(), SIGKILL);
4650     return NULL;
4651 }
4652 
4653 /* read output of command substitution
4654  *
4655  * The file descriptor "in" is closed by the function.
4656  *
4657  * "qt" indicates if the substitution was in double quotes.
4658  *
4659  * "readerror", if not NULL, is used to return any error that
4660  * occurred during the read.
4661  */
4662 
4663 /**/
4664 mod_export LinkList
readoutput(int in,int qt,int * readerror)4665 readoutput(int in, int qt, int *readerror)
4666 {
4667     LinkList ret;
4668     char *buf, *bufptr, *ptr, inbuf[64];
4669     int bsiz, c, cnt = 0, readret;
4670     int q = queue_signal_level();
4671 
4672     ret = newlinklist();
4673     ptr = buf = (char *) hcalloc(bsiz = 64);
4674     /*
4675      * We need to be sensitive to SIGCHLD else we can be
4676      * stuck forever with important processes unreaped.
4677      * The case that triggered this was where the exiting
4678      * process is group leader of the foreground process and we need
4679      * to reclaim the terminal else ^C doesn't work.
4680      */
4681     dont_queue_signals();
4682     child_unblock();
4683     for (;;) {
4684 	readret = read(in, inbuf, 64);
4685 	if (readret <= 0) {
4686 	    if (readret < 0 && errno == EINTR)
4687 		continue;
4688 	    else
4689 		break;
4690 	}
4691 	for (bufptr = inbuf; bufptr < inbuf + readret; bufptr++) {
4692 	    c = *bufptr;
4693 	    if (imeta(c)) {
4694 		*ptr++ = Meta;
4695 		c ^= 32;
4696 		cnt++;
4697 	    }
4698 	    if (++cnt >= bsiz) {
4699 		char *pp;
4700 		queue_signals();
4701 		pp = (char *) hcalloc(bsiz *= 2);
4702 		dont_queue_signals();
4703 
4704 		memcpy(pp, buf, cnt - 1);
4705 		ptr = (buf = pp) + cnt - 1;
4706 	    }
4707 	    *ptr++ = c;
4708 	}
4709     }
4710     child_block();
4711     restore_queue_signals(q);
4712     if (readerror)
4713 	*readerror = readret < 0 ? errno : 0;
4714     close(in);
4715     while (cnt && ptr[-1] == '\n')
4716 	ptr--, cnt--;
4717     *ptr = '\0';
4718     if (qt) {
4719 	if (!cnt) {
4720 	    *ptr++ = Nularg;
4721 	    *ptr = '\0';
4722 	}
4723 	addlinknode(ret, buf);
4724     } else {
4725 	char **words = spacesplit(buf, 0, 1, 0);
4726 
4727 	while (*words) {
4728 	    if (isset(GLOBSUBST))
4729 		shtokenize(*words);
4730 	    addlinknode(ret, *words++);
4731 	}
4732     }
4733     return ret;
4734 }
4735 
4736 /**/
4737 static Eprog
parsecmd(char * cmd,char ** eptr)4738 parsecmd(char *cmd, char **eptr)
4739 {
4740     char *str;
4741     Eprog prog;
4742 
4743     for (str = cmd + 2; *str && *str != Outpar; str++);
4744     if (!*str || cmd[1] != Inpar) {
4745 	/*
4746 	 * This can happen if the expression is being parsed
4747 	 * inside another construct, e.g. as a value within ${..:..} etc.
4748 	 * So print a proper error message instead of the not very
4749 	 * useful but traditional "oops".
4750  	 */
4751 	char *errstr = dupstrpfx(cmd, 2);
4752 	untokenize(errstr);
4753 	zerr("unterminated `%s...)'", errstr);
4754 	return NULL;
4755     }
4756     *str = '\0';
4757     if (eptr)
4758 	*eptr = str+1;
4759     if (!(prog = parse_string(cmd + 2, 0))) {
4760 	zerr("parse error in process substitution");
4761 	return NULL;
4762     }
4763     return prog;
4764 }
4765 
4766 /* =(...) */
4767 
4768 /**/
4769 char *
getoutputfile(char * cmd,char ** eptr)4770 getoutputfile(char *cmd, char **eptr)
4771 {
4772     pid_t pid;
4773     char *nam;
4774     Eprog prog;
4775     int fd;
4776     char *s;
4777 
4778     if (thisjob == -1){
4779 	zerr("process substitution %s cannot be used here", cmd);
4780 	return NULL;
4781     }
4782     if (!(prog = parsecmd(cmd, eptr)))
4783 	return NULL;
4784     if (!(nam = gettempname(NULL, 1)))
4785 	return NULL;
4786 
4787     if ((s = simple_redir_name(prog, REDIR_HERESTR))) {
4788 	/*
4789 	 * =(<<<stuff).  Optimise a la $(<file).  It's
4790 	 * effectively the reverse, converting a string into a file name
4791 	 * rather than vice versa.
4792 	 */
4793 	singsub(&s);
4794 	if (errflag)
4795 	    s = NULL;
4796 	else
4797 	    untokenize(s);
4798     }
4799 
4800     if (!s)             /* Unclear why we need to do this before open() */
4801 	child_block();  /* but it has been so for a long time: leave it */
4802 
4803     if ((fd = open(nam, O_WRONLY | O_CREAT | O_EXCL | O_NOCTTY, 0600)) < 0) {
4804 	zerr("process substitution failed: %e", errno);
4805 	free(nam);
4806 	if (!s)
4807 	    child_unblock();
4808 	return NULL;
4809     } else {
4810 	char *suffix = getsparam("TMPSUFFIX");
4811 	if (suffix && *suffix && !strstr(suffix, "/")) {
4812 	    suffix = dyncat(nam, unmeta(suffix));
4813 	    if (link(nam, suffix) == 0) {
4814 		addfilelist(nam, 0);
4815 		nam = suffix;
4816 	    }
4817 	}
4818     }
4819     addfilelist(nam, 0);
4820 
4821     if (s) {
4822 	/* optimised here-string */
4823 	int len;
4824 	unmetafy(s, &len);
4825 	write_loop(fd, s, len);
4826 	close(fd);
4827 	return nam;
4828     }
4829 
4830     if ((cmdoutpid = pid = zfork(NULL)) == -1) {
4831 	/* fork error */
4832 	close(fd);
4833 	child_unblock();
4834 	return nam;
4835     } else if (pid) {
4836 	int os;
4837 
4838 	close(fd);
4839 	os = jobtab[thisjob].stat;
4840 	waitforpid(pid, 0);
4841 	cmdoutval = 0;
4842 	jobtab[thisjob].stat = os;
4843 	return nam;
4844     }
4845 
4846     /* pid == 0 */
4847     closem(FDT_UNUSED, 0);
4848     redup(fd, 1);
4849     entersubsh(ESUB_PGRP|ESUB_NOMONITOR, NULL);
4850     cmdpush(CS_CMDSUBST);
4851     execode(prog, 0, 1, "equalsubst");
4852     cmdpop();
4853     close(1);
4854     _realexit();
4855     zerr("exit returned in child!!");
4856     kill(getpid(), SIGKILL);
4857     return NULL;
4858 }
4859 
4860 #if !defined(PATH_DEV_FD) && defined(HAVE_FIFOS)
4861 /* get a temporary named pipe */
4862 
4863 static char *
namedpipe(void)4864 namedpipe(void)
4865 {
4866     char *tnam = gettempname(NULL, 1);
4867 
4868     if (!tnam) {
4869 	zerr("failed to create named pipe: %e", errno);
4870 	return NULL;
4871     }
4872 # ifdef HAVE_MKFIFO
4873     if (mkfifo(tnam, 0600) < 0){
4874 # else
4875     if (mknod(tnam, 0010600, 0) < 0){
4876 # endif
4877 	zerr("failed to create named pipe: %s, %e", tnam, errno);
4878 	return NULL;
4879     }
4880     return tnam;
4881 }
4882 #endif /* ! PATH_DEV_FD && HAVE_FIFOS */
4883 
4884 /* <(...) or >(...) */
4885 
4886 /**/
4887 char *
4888 getproc(char *cmd, char **eptr)
4889 {
4890 #if !defined(HAVE_FIFOS) && !defined(PATH_DEV_FD)
4891     zerr("doesn't look like your system supports FIFOs.");
4892     return NULL;
4893 #else
4894     Eprog prog;
4895     int out = *cmd == Inang;
4896     char *pnam;
4897     pid_t pid;
4898     struct timeval bgtime;
4899 
4900 #ifndef PATH_DEV_FD
4901     int fd;
4902     if (thisjob == -1) {
4903 	zerr("process substitution %s cannot be used here", cmd);
4904 	return NULL;
4905     }
4906     if (!(pnam = namedpipe()))
4907 	return NULL;
4908     if (!(prog = parsecmd(cmd, eptr)))
4909 	return NULL;
4910     addfilelist(pnam, 0);
4911 
4912     if ((pid = zfork(&bgtime))) {
4913 	if (pid == -1)
4914 	    return NULL;
4915 	if (!out)
4916 	    addproc(pid, NULL, 1, &bgtime, -1, -1);
4917 	procsubstpid = pid;
4918 	return pnam;
4919     }
4920     closem(FDT_UNUSED, 0);
4921     fd = open(pnam, out ? O_WRONLY | O_NOCTTY : O_RDONLY | O_NOCTTY);
4922     if (fd == -1) {
4923 	zerr("can't open %s: %e", pnam, errno);
4924 	_exit(1);
4925     }
4926     entersubsh(ESUB_ASYNC|ESUB_PGRP, NULL);
4927     redup(fd, out);
4928 #else /* PATH_DEV_FD */
4929     int pipes[2], fd;
4930 
4931     if (thisjob == -1) {
4932 	zerr("process substitution %s cannot be used here", cmd);
4933 	return NULL;
4934     }
4935     pnam = zhalloc(strlen(PATH_DEV_FD) + 1 + DIGBUFSIZE);
4936     if (!(prog = parsecmd(cmd, eptr)))
4937 	return NULL;
4938     if (mpipe(pipes) < 0)
4939 	return NULL;
4940     if ((pid = zfork(&bgtime))) {
4941 	sprintf(pnam, "%s/%d", PATH_DEV_FD, pipes[!out]);
4942 	zclose(pipes[out]);
4943 	if (pid == -1)
4944 	{
4945 	    zclose(pipes[!out]);
4946 	    return NULL;
4947 	}
4948 	fd = pipes[!out];
4949 	fdtable[fd] = FDT_PROC_SUBST;
4950 	addfilelist(NULL, fd);
4951 	if (!out)
4952 	{
4953 	    addproc(pid, NULL, 1, &bgtime, -1, -1);
4954 	}
4955 	procsubstpid = pid;
4956 	return pnam;
4957     }
4958     entersubsh(ESUB_ASYNC|ESUB_PGRP, NULL);
4959     redup(pipes[out], out);
4960     closem(FDT_UNUSED, 0);   /* this closes pipes[!out] as well */
4961 #endif /* PATH_DEV_FD */
4962 
4963     cmdpush(CS_CMDSUBST);
4964     execode(prog, 0, 1, out ? "outsubst" : "insubst");
4965     cmdpop();
4966     zclose(out);
4967     _realexit();
4968     return NULL;
4969 #endif   /* HAVE_FIFOS and PATH_DEV_FD not defined */
4970 }
4971 
4972 /*
4973  * > >(...) or < <(...) (does not use named pipes)
4974  *
4975  * If the second argument is 1, this is part of
4976  * an "exec < <(...)" or "exec > >(...)" and we shouldn't
4977  * wait for the job to finish before continuing.
4978  */
4979 
4980 /**/
4981 static int
4982 getpipe(char *cmd, int nullexec)
4983 {
4984     Eprog prog;
4985     int pipes[2], out = *cmd == Inang;
4986     pid_t pid;
4987     struct timeval bgtime;
4988     char *ends;
4989 
4990     if (!(prog = parsecmd(cmd, &ends)))
4991 	return -1;
4992     if (*ends) {
4993 	zerr("invalid syntax for process substitution in redirection");
4994 	return -1;
4995     }
4996     if (mpipe(pipes) < 0)
4997 	return -1;
4998     if ((pid = zfork(&bgtime))) {
4999 	zclose(pipes[out]);
5000 	if (pid == -1) {
5001 	    zclose(pipes[!out]);
5002 	    return -1;
5003 	}
5004 	if (!nullexec)
5005 	    addproc(pid, NULL, 1, &bgtime, -1, -1);
5006 	procsubstpid = pid;
5007 	return pipes[!out];
5008     }
5009     entersubsh(ESUB_ASYNC|ESUB_PGRP, NULL);
5010     redup(pipes[out], out);
5011     closem(FDT_UNUSED, 0);	/* this closes pipes[!out] as well */
5012     cmdpush(CS_CMDSUBST);
5013     execode(prog, 0, 1, out ? "outsubst" : "insubst");
5014     cmdpop();
5015     _realexit();
5016     return 0;
5017 }
5018 
5019 /* open pipes with fds >= 10 */
5020 
5021 /**/
5022 static int
5023 mpipe(int *pp)
5024 {
5025     if (pipe(pp) < 0) {
5026 	zerr("pipe failed: %e", errno);
5027 	return -1;
5028     }
5029     pp[0] = movefd(pp[0]);
5030     pp[1] = movefd(pp[1]);
5031     return 0;
5032 }
5033 
5034 /*
5035  * Do process substitution with redirection
5036  *
5037  * If the second argument is 1, this is part of
5038  * an "exec < <(...)" or "exec > >(...)" and we shouldn't
5039  * wait for the job to finish before continuing.
5040  * Likewise, we shouldn't wait if we are opening the file
5041  * descriptor using the {fd}>>(...) notation since it stays
5042  * valid for subsequent commands.
5043  */
5044 
5045 /**/
5046 static void
5047 spawnpipes(LinkList l, int nullexec)
5048 {
5049     LinkNode n;
5050     Redir f;
5051     char *str;
5052 
5053     n = firstnode(l);
5054     for (; n; incnode(n)) {
5055 	f = (Redir) getdata(n);
5056 	if (f->type == REDIR_OUTPIPE || f->type == REDIR_INPIPE) {
5057 	    str = f->name;
5058 	    f->fd2 = getpipe(str, nullexec || f->varid);
5059 	}
5060     }
5061 }
5062 
5063 /* evaluate a [[ ... ]] */
5064 
5065 /**/
5066 static int
5067 execcond(Estate state, UNUSED(int do_exec))
5068 {
5069     int stat;
5070 
5071     state->pc--;
5072     if (isset(XTRACE)) {
5073 	printprompt4();
5074 	fprintf(xtrerr, "[[");
5075 	tracingcond++;
5076     }
5077     cmdpush(CS_COND);
5078     stat = evalcond(state, NULL);
5079     /*
5080      * 2 indicates a syntax error.  For compatibility, turn this
5081      * into a shell error.
5082      */
5083     if (stat == 2)
5084 	errflag |= ERRFLAG_ERROR;
5085     cmdpop();
5086     if (isset(XTRACE)) {
5087 	fprintf(xtrerr, " ]]\n");
5088 	fflush(xtrerr);
5089 	tracingcond--;
5090     }
5091     return stat;
5092 }
5093 
5094 /* evaluate a ((...)) arithmetic command */
5095 
5096 /**/
5097 static int
5098 execarith(Estate state, UNUSED(int do_exec))
5099 {
5100     char *e;
5101     mnumber val = zero_mnumber;
5102     int htok = 0;
5103 
5104     if (isset(XTRACE)) {
5105 	printprompt4();
5106 	fprintf(xtrerr, "((");
5107     }
5108     cmdpush(CS_MATH);
5109     e = ecgetstr(state, EC_DUPTOK, &htok);
5110     if (htok)
5111 	singsub(&e);
5112     if (isset(XTRACE))
5113 	fprintf(xtrerr, " %s", e);
5114 
5115     val = matheval(e);
5116 
5117     cmdpop();
5118 
5119     if (isset(XTRACE)) {
5120 	fprintf(xtrerr, " ))\n");
5121 	fflush(xtrerr);
5122     }
5123     if (errflag) {
5124 	errflag &= ~ERRFLAG_ERROR;
5125 	return 2;
5126     }
5127     /* should test for fabs(val.u.d) < epsilon? */
5128     return (val.type == MN_INTEGER) ? val.u.l == 0 : val.u.d == 0.0;
5129 }
5130 
5131 /* perform time ... command */
5132 
5133 /**/
5134 static int
5135 exectime(Estate state, UNUSED(int do_exec))
5136 {
5137     int jb;
5138 
5139     jb = thisjob;
5140     if (WC_TIMED_TYPE(state->pc[-1]) == WC_TIMED_EMPTY) {
5141 	shelltime();
5142 	return 0;
5143     }
5144     execpline(state, *state->pc++, Z_TIMED|Z_SYNC, 0);
5145     thisjob = jb;
5146     return lastval;
5147 }
5148 
5149 /* Define a shell function */
5150 
5151 static const char *const ANONYMOUS_FUNCTION_NAME = "(anon)";
5152 
5153 /**/
5154 static int
5155 execfuncdef(Estate state, Eprog redir_prog)
5156 {
5157     Shfunc shf;
5158     char *s = NULL;
5159     int signum, nprg, sbeg, nstrs, npats, len, plen, i, htok = 0, ret = 0;
5160     int anon_func = 0;
5161     Wordcode beg = state->pc, end;
5162     Eprog prog;
5163     Patprog *pp;
5164     LinkList names;
5165 
5166     end = beg + WC_FUNCDEF_SKIP(state->pc[-1]);
5167     names = ecgetlist(state, *state->pc++, EC_DUPTOK, &htok);
5168     nprg = end - beg;
5169     sbeg = *state->pc++;
5170     nstrs = *state->pc++;
5171     npats = *state->pc++;
5172 
5173     nprg = (end - state->pc);
5174     plen = nprg * sizeof(wordcode);
5175     len = plen + (npats * sizeof(Patprog)) + nstrs;
5176 
5177     if (htok && names) {
5178 	execsubst(names);
5179 	if (errflag) {
5180 	    state->pc = end;
5181 	    return 1;
5182 	}
5183     }
5184 
5185     DPUTS(!names && redir_prog,
5186 	  "Passing redirection to anon function definition.");
5187     while (!names || (s = (char *) ugetnode(names))) {
5188 	if (!names) {
5189 	    prog = (Eprog) zhalloc(sizeof(*prog));
5190 	    prog->nref = -1; /* on the heap */
5191 	} else {
5192 	    prog = (Eprog) zalloc(sizeof(*prog));
5193 	    prog->nref = 1; /* allocated from permanent storage */
5194 	}
5195 	prog->npats = npats;
5196 	prog->len = len;
5197 	if (state->prog->dump || !names) {
5198 	    if (!names) {
5199 		prog->flags = EF_HEAP;
5200 		prog->dump = NULL;
5201 		prog->pats = pp = (Patprog *) zhalloc(npats * sizeof(Patprog));
5202 	    } else {
5203 		prog->flags = EF_MAP;
5204 		incrdumpcount(state->prog->dump);
5205 		prog->dump = state->prog->dump;
5206 		prog->pats = pp = (Patprog *) zalloc(npats * sizeof(Patprog));
5207 	    }
5208 	    prog->prog = state->pc;
5209 	    prog->strs = state->strs + sbeg;
5210 	} else {
5211 	    prog->flags = EF_REAL;
5212 	    prog->pats = pp = (Patprog *) zalloc(len);
5213 	    prog->prog = (Wordcode) (prog->pats + npats);
5214 	    prog->strs = (char *) (prog->prog + nprg);
5215 	    prog->dump = NULL;
5216 	    memcpy(prog->prog, state->pc, plen);
5217 	    memcpy(prog->strs, state->strs + sbeg, nstrs);
5218 	}
5219 	for (i = npats; i--; pp++)
5220 	    *pp = dummy_patprog1;
5221 	prog->shf = NULL;
5222 
5223 	shf = (Shfunc) zalloc(sizeof(*shf));
5224 	shf->funcdef = prog;
5225 	shf->node.flags = 0;
5226 	/* No dircache here, not a directory */
5227 	shf->filename = ztrdup(scriptfilename);
5228 	shf->lineno =
5229 	    (funcstack && (funcstack->tp == FS_FUNC ||
5230 			   funcstack->tp == FS_EVAL)) ?
5231 	    funcstack->flineno + lineno :
5232 	    lineno;
5233 	/*
5234 	 * redir_prog is permanently allocated --- but if
5235 	 * this function has multiple names we need an additional
5236 	 * one. Original redir_prog used with the last name
5237 	 * because earlier functions are freed in case of duplicate
5238 	 * names.
5239 	 */
5240 	if (names && nonempty(names) && redir_prog)
5241 	    shf->redir = dupeprog(redir_prog, 0);
5242 	else {
5243 	    shf->redir = redir_prog;
5244 	    redir_prog = 0;
5245 	}
5246 	shfunc_set_sticky(shf);
5247 
5248 	if (!names) {
5249 	    /*
5250 	     * Anonymous function, execute immediately.
5251 	     * Function name is "(anon)".
5252 	     */
5253 	    LinkList args;
5254 
5255 	    anon_func = 1;
5256 	    shf->node.flags |= PM_ANONYMOUS;
5257 
5258 	    state->pc = end;
5259 	    end += *state->pc++;
5260 	    args = ecgetlist(state, *state->pc++, EC_DUPTOK, &htok);
5261 
5262 	    if (htok && args) {
5263 		execsubst(args);
5264 		if (errflag) {
5265 		    freeeprog(shf->funcdef);
5266 		    if (shf->redir) /* shouldn't be */
5267 			freeeprog(shf->redir);
5268 		    dircache_set(&shf->filename, NULL);
5269 		    zfree(shf, sizeof(*shf));
5270 		    state->pc = end;
5271 		    return 1;
5272 		}
5273 	    }
5274 
5275 	    setunderscore((args && nonempty(args)) ?
5276 			  ((char *) getdata(lastnode(args))) : "");
5277 
5278 	    if (!args)
5279 		args = newlinklist();
5280 	    shf->node.nam = (char *) ANONYMOUS_FUNCTION_NAME;
5281 	    pushnode(args, shf->node.nam);
5282 
5283 	    execshfunc(shf, args);
5284 	    ret = lastval;
5285 
5286 	    if (isset(PRINTEXITVALUE) && isset(SHINSTDIN) &&
5287 		lastval) {
5288 #if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD)
5289 		fprintf(stderr, "zsh: exit %lld\n", lastval);
5290 #else
5291 		fprintf(stderr, "zsh: exit %ld\n", (long)lastval);
5292 #endif
5293 		fflush(stderr);
5294 	    }
5295 
5296 	    freeeprog(shf->funcdef);
5297 	    if (shf->redir) /* shouldn't be */
5298 		freeeprog(shf->redir);
5299 	    dircache_set(&shf->filename, NULL);
5300 	    zfree(shf, sizeof(*shf));
5301 	    break;
5302 	} else {
5303 	    /* is this shell function a signal trap? */
5304 	    if (!strncmp(s, "TRAP", 4) &&
5305 		(signum = getsignum(s + 4)) != -1) {
5306 		if (settrap(signum, NULL, ZSIG_FUNC)) {
5307 		    freeeprog(shf->funcdef);
5308 		    dircache_set(&shf->filename, NULL);
5309 		    zfree(shf, sizeof(*shf));
5310 		    state->pc = end;
5311 		    return 1;
5312 		}
5313 
5314 		/*
5315 		 * Remove the old node explicitly in case it has
5316 		 * an alternative name
5317 		 */
5318 		removetrapnode(signum);
5319 	    }
5320 	    shfunctab->addnode(shfunctab, ztrdup(s), shf);
5321 	}
5322     }
5323     if (!anon_func)
5324 	setunderscore("");
5325     if (redir_prog) {
5326 	/* For completeness, shouldn't happen */
5327 	freeeprog(redir_prog);
5328     }
5329     state->pc = end;
5330     return ret;
5331 }
5332 
5333 /* Duplicate a sticky emulation */
5334 
5335 /**/
5336 
5337 mod_export Emulation_options
5338 sticky_emulation_dup(Emulation_options src, int useheap)
5339 {
5340     Emulation_options newsticky = useheap ?
5341 	hcalloc(sizeof(*src)) : zshcalloc(sizeof(*src));
5342     newsticky->emulation = src->emulation;
5343     if (src->n_on_opts) {
5344 	size_t sz = src->n_on_opts * sizeof(*src->on_opts);
5345 	newsticky->n_on_opts = src->n_on_opts;
5346 	newsticky->on_opts = useheap ? zhalloc(sz) : zalloc(sz);
5347 	memcpy(newsticky->on_opts, src->on_opts, sz);
5348     }
5349     if (src->n_off_opts) {
5350 	size_t sz = src->n_off_opts * sizeof(*src->off_opts);
5351 	newsticky->n_off_opts = src->n_off_opts;
5352 	newsticky->off_opts = useheap ? zhalloc(sz) : zalloc(sz);
5353 	memcpy(newsticky->off_opts, src->off_opts, sz);
5354     }
5355 
5356     return newsticky;
5357 }
5358 
5359 /* Set the sticky emulation attributes for a shell function */
5360 
5361 /**/
5362 
5363 mod_export void
5364 shfunc_set_sticky(Shfunc shf)
5365 {
5366     if (sticky)
5367 	shf->sticky = sticky_emulation_dup(sticky, 0);
5368     else
5369 	shf->sticky = NULL;
5370 }
5371 
5372 
5373 /* Main entry point to execute a shell function. */
5374 
5375 /**/
5376 static void
5377 execshfunc(Shfunc shf, LinkList args)
5378 {
5379     LinkList last_file_list = NULL;
5380     unsigned char *ocs;
5381     int ocsp, osfc;
5382 
5383     if (errflag)
5384 	return;
5385 
5386     /* thisjob may be invalid if we're called via execsimple: see execcursh */
5387     if (!list_pipe && thisjob != -1 && thisjob != list_pipe_job &&
5388 	!hasprocs(thisjob)) {
5389 	/* Without this deletejob the process table *
5390 	 * would be filled by a recursive function. */
5391 	last_file_list = jobtab[thisjob].filelist;
5392 	jobtab[thisjob].filelist = NULL;
5393 	deletejob(jobtab + thisjob, 0);
5394     }
5395 
5396     if (isset(XTRACE)) {
5397 	LinkNode lptr;
5398 	printprompt4();
5399 	if (args)
5400 	    for (lptr = firstnode(args); lptr; incnode(lptr)) {
5401 		if (lptr != firstnode(args))
5402 		    fputc(' ', xtrerr);
5403 		quotedzputs((char *)getdata(lptr), xtrerr);
5404 	    }
5405 	fputc('\n', xtrerr);
5406 	fflush(xtrerr);
5407     }
5408     queue_signals();
5409     ocs = cmdstack;
5410     ocsp = cmdsp;
5411     cmdstack = (unsigned char *) zalloc(CMDSTACKSZ);
5412     cmdsp = 0;
5413     if ((osfc = sfcontext) == SFC_NONE)
5414 	sfcontext = SFC_DIRECT;
5415     xtrerr = stderr;
5416 
5417     doshfunc(shf, args, 0);
5418 
5419     sfcontext = osfc;
5420     free(cmdstack);
5421     cmdstack = ocs;
5422     cmdsp = ocsp;
5423 
5424     if (!list_pipe)
5425 	deletefilelist(last_file_list, 0);
5426     unqueue_signals();
5427 }
5428 
5429 /*
5430  * Function to execute the special type of command that represents an
5431  * autoloaded shell function.  The command structure tells us which
5432  * function it is.  This function is actually called as part of the
5433  * execution of the autoloaded function itself, so when the function
5434  * has been autoloaded, its list is just run with no frills.
5435  *
5436  * There are two cases because if we are doing all-singing, all-dancing
5437  * non-simple code we load the shell function early in execcmd() (the
5438  * action also present in the non-basic version) to check if
5439  * there are redirections that need to be handled at that point.
5440  * Then we call execautofn_basic() to do the rest.
5441  */
5442 
5443 /**/
5444 static int
5445 execautofn_basic(Estate state, UNUSED(int do_exec))
5446 {
5447     Shfunc shf;
5448     char *oldscriptname, *oldscriptfilename;
5449 
5450     shf = state->prog->shf;
5451 
5452     /*
5453      * Probably we didn't know the filename where this function was
5454      * defined yet.
5455      */
5456     if (funcstack && !funcstack->filename)
5457 	funcstack->filename = getshfuncfile(shf);
5458 
5459     oldscriptname = scriptname;
5460     oldscriptfilename = scriptfilename;
5461     scriptname = dupstring(shf->node.nam);
5462     scriptfilename = getshfuncfile(shf);
5463     execode(shf->funcdef, 1, 0, "loadautofunc");
5464     scriptname = oldscriptname;
5465     scriptfilename = oldscriptfilename;
5466 
5467     return lastval;
5468 }
5469 
5470 /**/
5471 static int
5472 execautofn(Estate state, UNUSED(int do_exec))
5473 {
5474     Shfunc shf;
5475 
5476     if (!(shf = loadautofn(state->prog->shf, 1, 0, 0)))
5477 	return 1;
5478 
5479     state->prog->shf = shf;
5480     return execautofn_basic(state, 0);
5481 }
5482 
5483 /*
5484  * Helper function to install the source file name of a shell function
5485  * just autoloaded.
5486  *
5487  * We attempt to do this efficiently as the typical case is the
5488  * directory part is a well-known directory, which is cached, and
5489  * the non-directory part is the same as the node name.
5490  */
5491 
5492 /**/
5493 static void
5494 loadautofnsetfile(Shfunc shf, char *fdir)
5495 {
5496     /*
5497      * If shf->filename is already the load directory ---
5498      * keep it as we can still use it to get the load file.
5499      * This makes autoload with an absolute path particularly efficient.
5500      */
5501     if (!(shf->node.flags & PM_LOADDIR) ||
5502 	strcmp(shf->filename, fdir) != 0) {
5503 	/* Old directory name not useful... */
5504 	dircache_set(&shf->filename, NULL);
5505 	if (fdir) {
5506 	    /* ...can still cache directory */
5507 	    shf->node.flags |= PM_LOADDIR;
5508 	    dircache_set(&shf->filename, fdir);
5509 	} else {
5510 	    /* ...no separate directory part to cache, for some reason. */
5511 	    shf->node.flags &= ~PM_LOADDIR;
5512 	    shf->filename = ztrdup(shf->node.nam);
5513 	}
5514     }
5515 }
5516 
5517 /**/
5518 Shfunc
5519 loadautofn(Shfunc shf, int fksh, int autol, int current_fpath)
5520 {
5521     int noalias = noaliases, ksh = 1;
5522     Eprog prog;
5523     char *fdir;			/* Directory path where func found */
5524 
5525     pushheap();
5526 
5527     noaliases = (shf->node.flags & PM_UNALIASED);
5528     if (shf->filename && shf->filename[0] == '/' &&
5529 	(shf->node.flags & PM_LOADDIR))
5530     {
5531 	char *spec_path[2];
5532 	spec_path[0] = dupstring(shf->filename);
5533 	spec_path[1] = NULL;
5534 	prog = getfpfunc(shf->node.nam, &ksh, &fdir, spec_path, 0);
5535 	if (prog == &dummy_eprog &&
5536 	    (current_fpath || (shf->node.flags & PM_CUR_FPATH)))
5537 	    prog = getfpfunc(shf->node.nam, &ksh, &fdir, NULL, 0);
5538     }
5539     else
5540 	prog = getfpfunc(shf->node.nam, &ksh, &fdir, NULL, 0);
5541     noaliases = noalias;
5542 
5543     if (ksh == 1) {
5544 	ksh = fksh;
5545 	if (ksh == 1)
5546 	    ksh = (shf->node.flags & PM_KSHSTORED) ? 2 :
5547 		  (shf->node.flags & PM_ZSHSTORED) ? 0 : 1;
5548     }
5549 
5550     if (prog == &dummy_eprog) {
5551 	/* We're not actually in the function; decrement locallevel */
5552 	locallevel--;
5553 	zwarn("%s: function definition file not found", shf->node.nam);
5554 	locallevel++;
5555 	popheap();
5556 	return NULL;
5557     }
5558     if (!prog) {
5559 	popheap();
5560 	return NULL;
5561     }
5562     if (ksh == 2 || (ksh == 1 && isset(KSHAUTOLOAD))) {
5563 	if (autol) {
5564 	    prog->flags |= EF_RUN;
5565 
5566 	    freeeprog(shf->funcdef);
5567 	    if (prog->flags & EF_MAP)
5568 		shf->funcdef = prog;
5569 	    else
5570 		shf->funcdef = dupeprog(prog, 0);
5571 	    shf->node.flags &= ~PM_UNDEFINED;
5572 	    loadautofnsetfile(shf, fdir);
5573 	} else {
5574 	    VARARR(char, n, strlen(shf->node.nam) + 1);
5575 	    strcpy(n, shf->node.nam);
5576 	    execode(prog, 1, 0, "evalautofunc");
5577 	    shf = (Shfunc) shfunctab->getnode(shfunctab, n);
5578 	    if (!shf || (shf->node.flags & PM_UNDEFINED)) {
5579 		/* We're not actually in the function; decrement locallevel */
5580 		locallevel--;
5581 		zwarn("%s: function not defined by file", n);
5582 		locallevel++;
5583 		popheap();
5584 		return NULL;
5585 	    }
5586 	}
5587     } else {
5588 	freeeprog(shf->funcdef);
5589 	if (prog->flags & EF_MAP)
5590 	    shf->funcdef = stripkshdef(prog, shf->node.nam);
5591 	else
5592 	    shf->funcdef = dupeprog(stripkshdef(prog, shf->node.nam), 0);
5593 	shf->node.flags &= ~PM_UNDEFINED;
5594 	loadautofnsetfile(shf, fdir);
5595     }
5596     popheap();
5597 
5598     return shf;
5599 }
5600 
5601 /*
5602  * Check if a sticky emulation differs from the current one.
5603  */
5604 
5605 /**/
5606 
5607 int sticky_emulation_differs(Emulation_options sticky2)
5608 {
5609     /* If no new sticky emulation, not a different emulation */
5610     if (!sticky2)
5611 	return 0;
5612     /* If no current sticky emulation, different */
5613     if (!sticky)
5614 	return 1;
5615     /* If basic emulation different, different */
5616     if (sticky->emulation != sticky2->emulation)
5617 	return 1;
5618     /* If differing numbers of options, different */
5619     if (sticky->n_on_opts != sticky2->n_on_opts ||
5620 	sticky->n_off_opts != sticky2->n_off_opts)
5621 	return 1;
5622     /*
5623      * We need to compare option arrays, if non-null.
5624      * We made parseopts() create the list of options in option
5625      * order to make this easy.
5626      */
5627     /* If different options turned on, different */
5628     if (sticky->n_on_opts &&
5629 	memcmp(sticky->on_opts, sticky2->on_opts,
5630 	       sticky->n_on_opts * sizeof(*sticky->on_opts)) != 0)
5631 	return 1;
5632     /* If different options turned on, different */
5633     if (sticky->n_off_opts &&
5634 	memcmp(sticky->off_opts, sticky2->off_opts,
5635 	       sticky->n_off_opts * sizeof(*sticky->off_opts)) != 0)
5636 	return 1;
5637     return 0;
5638 }
5639 
5640 /*
5641  * execute a shell function
5642  *
5643  * name is the name of the function
5644  *
5645  * prog is the code to execute
5646  *
5647  * doshargs, if set, are parameters to pass to the function,
5648  * in which the first element is the function name (even if
5649  * FUNCTIONARGZERO is set as this is handled inside this function).
5650  *
5651  * If noreturnval is nonzero, then reset the current return
5652  * value (lastval) to its value before the shell function
5653  * was executed.  However, in any case return the status value
5654  * from the function (i.e. if noreturnval is not set, this
5655  * will be the same as lastval).
5656  */
5657 
5658 /**/
5659 mod_export int
5660 doshfunc(Shfunc shfunc, LinkList doshargs, int noreturnval)
5661 {
5662     char **pptab, **x;
5663     int ret;
5664     char *name = shfunc->node.nam;
5665     int flags = shfunc->node.flags;
5666     char *fname = dupstring(name);
5667     Eprog prog;
5668     static int oflags;
5669     static int funcdepth;
5670     Heap funcheap;
5671 
5672     queue_signals();	/* Lots of memory and global state changes coming */
5673 
5674     NEWHEAPS(funcheap) {
5675 	/*
5676 	 * Save data in heap rather than on stack to keep recursive
5677 	 * function cost down --- use of heap memory should be efficient
5678 	 * at this point.  Saving is not actually massive.
5679 	 */
5680 	Funcsave funcsave = zhalloc(sizeof(struct funcsave));
5681 	funcsave->scriptname = scriptname;
5682 	funcsave->argv0 = NULL;
5683 	funcsave->breaks = breaks;
5684 	funcsave->contflag = contflag;
5685 	funcsave->loops = loops;
5686 	funcsave->lastval = lastval;
5687 	funcsave->pipestats = NULL;
5688 	funcsave->numpipestats = numpipestats;
5689 	funcsave->noerrexit = noerrexit;
5690 	if (trap_state == TRAP_STATE_PRIMED)
5691 	    trap_return--;
5692 	/*
5693 	 * Suppression of ERR_RETURN is turned off in function scope.
5694 	 */
5695 	noerrexit &= ~NOERREXIT_RETURN;
5696 	if (noreturnval) {
5697 	    /*
5698 	     * Easiest to use the heap here since we're bracketed
5699 	     * immediately by a pushheap/popheap pair.
5700 	     */
5701 	    size_t bytes = sizeof(int)*numpipestats;
5702 	    funcsave->pipestats = (int *)zhalloc(bytes);
5703 	    memcpy(funcsave->pipestats, pipestats, bytes);
5704 	}
5705 
5706 	starttrapscope();
5707 	startpatternscope();
5708 
5709 	pptab = pparams;
5710 	if (!(flags & PM_UNDEFINED))
5711 	    scriptname = dupstring(name);
5712 	funcsave->zoptind = zoptind;
5713 	funcsave->optcind = optcind;
5714 	if (!isset(POSIXBUILTINS)) {
5715 	    zoptind = 1;
5716 	    optcind = 0;
5717 	}
5718 
5719 	/* We need to save the current options even if LOCALOPTIONS is *
5720 	 * not currently set.  That's because if it gets set in the    *
5721 	 * function we need to restore the original options on exit.   */
5722 	memcpy(funcsave->opts, opts, sizeof(opts));
5723 	funcsave->emulation = emulation;
5724 	funcsave->sticky = sticky;
5725 
5726 	if (sticky_emulation_differs(shfunc->sticky)) {
5727 	    /*
5728 	     * Function is marked for sticky emulation.
5729 	     * Enable it now.
5730 	     *
5731 	     * We deliberately do not do this if the sticky emulation
5732 	     * in effect is the same as that requested.  This enables
5733 	     * option setting naturally within emulation environments.
5734 	     * Note that a difference in EMULATE_FULLY (emulate with
5735 	     * or without -R) counts as a different environment.
5736 	     *
5737 	     * This propagates the sticky emulation to subfunctions.
5738 	     */
5739 	    sticky = sticky_emulation_dup(shfunc->sticky, 1);
5740 	    emulation = sticky->emulation;
5741 	    funcsave->restore_sticky = 1;
5742 	    installemulation(emulation, opts);
5743 	    if (sticky->n_on_opts) {
5744 		OptIndex *onptr;
5745 		for (onptr = sticky->on_opts;
5746 		     onptr < sticky->on_opts + sticky->n_on_opts;
5747 		     onptr++)
5748 		    opts[*onptr] = 1;
5749 	    }
5750 	    if (sticky->n_off_opts) {
5751 		OptIndex *offptr;
5752 		for (offptr = sticky->off_opts;
5753 		     offptr < sticky->off_opts + sticky->n_off_opts;
5754 		     offptr++)
5755 		    opts[*offptr] = 0;
5756 	    }
5757 	    /* All emulations start with pattern disables clear */
5758 	    clearpatterndisables();
5759 	} else
5760 	    funcsave->restore_sticky = 0;
5761 
5762 	if (flags & (PM_TAGGED|PM_TAGGED_LOCAL))
5763 	    opts[XTRACE] = 1;
5764 	else if (oflags & PM_TAGGED_LOCAL) {
5765 	    if (shfunc->node.nam == ANONYMOUS_FUNCTION_NAME /* pointer comparison */)
5766 		flags |= PM_TAGGED_LOCAL;
5767 	    else
5768 		opts[XTRACE] = 0;
5769 	}
5770 	if (flags & PM_WARNNESTED)
5771 	    opts[WARNNESTEDVAR] = 1;
5772 	else if (oflags & PM_WARNNESTED) {
5773 	    if (shfunc->node.nam == ANONYMOUS_FUNCTION_NAME)
5774 		flags |= PM_WARNNESTED;
5775 	    else
5776 		opts[WARNNESTEDVAR] = 0;
5777 	}
5778 	funcsave->oflags = oflags;
5779 	/*
5780 	 * oflags is static, because we compare it on the next recursive
5781 	 * call.  Hence also we maintain a saved version for restoring
5782 	 * the previous value of oflags after the call.
5783 	 */
5784 	oflags = flags;
5785 	opts[PRINTEXITVALUE] = 0;
5786 	if (doshargs) {
5787 	    LinkNode node;
5788 
5789 	    node = firstnode(doshargs);
5790 	    pparams = x = (char **) zshcalloc(((sizeof *x) *
5791 					       (1 + countlinknodes(doshargs))));
5792 	    if (isset(FUNCTIONARGZERO)) {
5793 		funcsave->argv0 = argzero;
5794 		argzero = ztrdup(getdata(node));
5795 	    }
5796 	    /* first node contains name regardless of option */
5797 	    node = node->next;
5798 	    for (; node; node = node->next, x++)
5799 		*x = ztrdup(getdata(node));
5800 	} else {
5801 	    pparams = (char **) zshcalloc(sizeof *pparams);
5802 	    if (isset(FUNCTIONARGZERO)) {
5803 		funcsave->argv0 = argzero;
5804 		argzero = ztrdup(argzero);
5805 	    }
5806 	}
5807 	++funcdepth;
5808 	if (zsh_funcnest >= 0 && funcdepth > zsh_funcnest) {
5809 	    zerr("maximum nested function level reached; increase FUNCNEST?");
5810 	    lastval = 1;
5811 	    goto undoshfunc;
5812 	}
5813 	funcsave->fstack.name = dupstring(name);
5814 	/*
5815 	 * The caller is whatever is immediately before on the stack,
5816 	 * unless we're at the top, in which case it's the script
5817 	 * or interactive shell name.
5818 	 */
5819 	funcsave->fstack.caller = funcstack ? funcstack->name :
5820 	    dupstring(funcsave->argv0 ? funcsave->argv0 : argzero);
5821 	funcsave->fstack.lineno = lineno;
5822 	funcsave->fstack.prev = funcstack;
5823 	funcsave->fstack.tp = FS_FUNC;
5824 	funcstack = &funcsave->fstack;
5825 
5826 	funcsave->fstack.flineno = shfunc->lineno;
5827 	funcsave->fstack.filename = getshfuncfile(shfunc);
5828 
5829 	prog = shfunc->funcdef;
5830 	if (prog->flags & EF_RUN) {
5831 	    Shfunc shf;
5832 
5833 	    prog->flags &= ~EF_RUN;
5834 
5835 	    runshfunc(prog, NULL, funcsave->fstack.name);
5836 
5837 	    if (!(shf = (Shfunc) shfunctab->getnode(shfunctab,
5838 						    (name = fname)))) {
5839 		zwarn("%s: function not defined by file", name);
5840 		if (noreturnval)
5841 		    errflag |= ERRFLAG_ERROR;
5842 		else
5843 		    lastval = 1;
5844 		goto doneshfunc;
5845 	    }
5846 	    prog = shf->funcdef;
5847 	}
5848 	runshfunc(prog, wrappers, funcsave->fstack.name);
5849     doneshfunc:
5850 	funcstack = funcsave->fstack.prev;
5851     undoshfunc:
5852 	--funcdepth;
5853 	if (retflag) {
5854 	    /*
5855 	     * This function is forced to return.
5856 	     */
5857 	    retflag = 0;
5858 	    /*
5859 	     * The calling function isn't necessarily forced to return,
5860 	     * but it should be made sensitive to ERR_EXIT and
5861 	     * ERR_RETURN as the assumptions we made at the end of
5862 	     * constructs within this function no longer apply.  If
5863 	     * there are cases where this is not true, they need adding
5864 	     * to C03traps.ztst.
5865 	     */
5866 	    this_noerrexit = 0;
5867 	    breaks = funcsave->breaks;
5868 	}
5869 	freearray(pparams);
5870 	if (funcsave->argv0) {
5871 	    zsfree(argzero);
5872 	    argzero = funcsave->argv0;
5873 	}
5874 	pparams = pptab;
5875 	if (!isset(POSIXBUILTINS)) {
5876 	    zoptind = funcsave->zoptind;
5877 	    optcind = funcsave->optcind;
5878 	}
5879 	scriptname = funcsave->scriptname;
5880 	oflags = funcsave->oflags;
5881 
5882 	endpatternscope();	/* before restoring old LOCALPATTERNS */
5883 
5884 	if (funcsave->restore_sticky) {
5885 	    /*
5886 	     * If we switched to an emulation environment just for
5887 	     * this function, we interpret the option and emulation
5888 	     * switch as being a firewall between environments.
5889 	     */
5890 	    memcpy(opts, funcsave->opts, sizeof(opts));
5891 	    emulation = funcsave->emulation;
5892 	    sticky = funcsave->sticky;
5893 	} else if (isset(LOCALOPTIONS)) {
5894 	    /* restore all shell options except PRIVILEGED and RESTRICTED */
5895 	    funcsave->opts[PRIVILEGED] = opts[PRIVILEGED];
5896 	    funcsave->opts[RESTRICTED] = opts[RESTRICTED];
5897 	    memcpy(opts, funcsave->opts, sizeof(opts));
5898 	    emulation = funcsave->emulation;
5899 	} else {
5900 	    /* just restore a couple. */
5901 	    opts[XTRACE] = funcsave->opts[XTRACE];
5902 	    opts[PRINTEXITVALUE] = funcsave->opts[PRINTEXITVALUE];
5903 	    opts[LOCALOPTIONS] = funcsave->opts[LOCALOPTIONS];
5904 	    opts[LOCALLOOPS] = funcsave->opts[LOCALLOOPS];
5905 	    opts[WARNNESTEDVAR] = funcsave->opts[WARNNESTEDVAR];
5906 	}
5907 
5908 	if (opts[LOCALLOOPS]) {
5909 	    if (contflag)
5910 		zwarn("`continue' active at end of function scope");
5911 	    if (breaks)
5912 		zwarn("`break' active at end of function scope");
5913 	    breaks = funcsave->breaks;
5914 	    contflag = funcsave->contflag;
5915 	    loops = funcsave->loops;
5916 	}
5917 
5918 	endtrapscope();
5919 
5920 	if (trap_state == TRAP_STATE_PRIMED)
5921 	    trap_return++;
5922 	ret = lastval;
5923 	noerrexit = funcsave->noerrexit;
5924 	if (noreturnval) {
5925 	    lastval = funcsave->lastval;
5926 	    numpipestats = funcsave->numpipestats;
5927 	    memcpy(pipestats, funcsave->pipestats, sizeof(int)*numpipestats);
5928 	}
5929     } OLDHEAPS;
5930 
5931     unqueue_signals();
5932 
5933     /*
5934      * Exit with a tidy up.
5935      * Only leave if we're at the end of the appropriate function ---
5936      * not a nested function.  As we usually skip the function body,
5937      * the only likely case where we need that second test is
5938      * when we have an "always" block.  The endparamscope() has
5939      * already happened, hence the "+1" here.
5940      *
5941      * If we are in an exit trap, finish it first... we wouldn't set
5942      * exit_pending if we were already in one.
5943      */
5944     if (exit_pending && exit_level >= locallevel+1 && !in_exit_trap) {
5945 	if (locallevel > forklevel) {
5946 	    /* Still functions to return: force them to do so. */
5947 	    retflag = 1;
5948 	    breaks = loops;
5949 	} else {
5950 	    /*
5951 	     * All functions finished: time to exit the shell.
5952 	     * We already did the `stopmsg' test when the
5953 	     * exit command was handled.
5954 	     */
5955 	    stopmsg = 1;
5956 	    zexit(exit_val, ZEXIT_NORMAL);
5957 	}
5958     }
5959 
5960     return ret;
5961 }
5962 
5963 /* This finally executes a shell function and any function wrappers     *
5964  * defined by modules. This works by calling the wrapper function which *
5965  * in turn has to call back this function with the arguments it gets.   */
5966 
5967 /**/
5968 mod_export void
5969 runshfunc(Eprog prog, FuncWrap wrap, char *name)
5970 {
5971     int cont, ouu;
5972     char *ou;
5973 
5974     queue_signals();
5975 
5976     ou = zalloc(ouu = underscoreused);
5977     if (ou)
5978 	memcpy(ou, zunderscore, underscoreused);
5979 
5980     while (wrap) {
5981 	wrap->module->wrapper++;
5982 	cont = wrap->handler(prog, wrap->next, name);
5983 	wrap->module->wrapper--;
5984 
5985 	if (!wrap->module->wrapper &&
5986 	    (wrap->module->node.flags & MOD_UNLOAD))
5987 	    unload_module(wrap->module);
5988 
5989 	if (!cont) {
5990 	    if (ou)
5991 		zfree(ou, ouu);
5992 	    unqueue_signals();
5993 	    return;
5994 	}
5995 	wrap = wrap->next;
5996     }
5997     startparamscope();
5998     execode(prog, 1, 0, "shfunc");	/* handles signal unqueueing */
5999     if (ou) {
6000 	setunderscore(ou);
6001 	zfree(ou, ouu);
6002     }
6003     endparamscope();
6004 
6005     unqueue_signals();
6006 }
6007 
6008 /*
6009  * Search fpath for an undefined function.  Finds the file, and returns the
6010  * list of its contents.
6011  *
6012  * If test is 0, load the function.
6013  *
6014  * If test_only is 1, don't load function, just test for it:
6015  * Non-null return means function was found
6016  *
6017  * *fdir points to path at which found (as passed in, not duplicated)
6018  */
6019 
6020 /**/
6021 Eprog
6022 getfpfunc(char *s, int *ksh, char **fdir, char **alt_path, int test_only)
6023 {
6024     char **pp, buf[PATH_MAX+1];
6025     off_t len;
6026     off_t rlen;
6027     char *d;
6028     Eprog r;
6029     int fd;
6030 
6031     pp = alt_path ? alt_path : fpath;
6032     for (; *pp; pp++) {
6033 	if (strlen(*pp) + strlen(s) + 1 >= PATH_MAX)
6034 	    continue;
6035 	if (**pp)
6036 	    sprintf(buf, "%s/%s", *pp, s);
6037 	else
6038 	    strcpy(buf, s);
6039 	if ((r = try_dump_file(*pp, s, buf, ksh, test_only))) {
6040 	    if (fdir)
6041 		*fdir = *pp;
6042 	    return r;
6043 	}
6044 	unmetafy(buf, NULL);
6045 	if (!access(buf, R_OK) && (fd = open(buf, O_RDONLY | O_NOCTTY)) != -1) {
6046 	    struct stat st;
6047 	    if (!fstat(fd, &st) && S_ISREG(st.st_mode) &&
6048 		(len = lseek(fd, 0, 2)) != -1) {
6049 		if (test_only) {
6050 		    close(fd);
6051 		    if (fdir)
6052 			*fdir = *pp;
6053 		    return &dummy_eprog;
6054 		}
6055 		d = (char *) zalloc(len + 1);
6056 		lseek(fd, 0, 0);
6057 		if ((rlen = read(fd, d, len)) >= 0) {
6058 		    char *oldscriptname = scriptname;
6059 
6060 		    close(fd);
6061 		    d[rlen] = '\0';
6062 		    d = metafy(d, rlen, META_REALLOC);
6063 
6064 		    scriptname = dupstring(s);
6065 		    r = parse_string(d, 1);
6066 		    scriptname = oldscriptname;
6067 
6068 		    if (fdir)
6069 			*fdir = *pp;
6070 
6071 		    zfree(d, len + 1);
6072 
6073 		    return r;
6074 		} else
6075 		    close(fd);
6076 
6077 		zfree(d, len + 1);
6078 	    } else
6079 		close(fd);
6080 	}
6081     }
6082     return test_only ? NULL : &dummy_eprog;
6083 }
6084 
6085 /* Handle the most common type of ksh-style autoloading, when doing a      *
6086  * zsh-style autoload.  Given the list read from an autoload file, and the *
6087  * name of the function being defined, check to see if the file consists   *
6088  * entirely of a single definition for that function.  If so, use the      *
6089  * contents of that definition.  Otherwise, use the entire file.           */
6090 
6091 /**/
6092 Eprog
6093 stripkshdef(Eprog prog, char *name)
6094 {
6095     Wordcode pc;
6096     wordcode code;
6097     char *ptr1, *ptr2;
6098 
6099     if (!prog)
6100 	return NULL;
6101     pc = prog->prog;
6102     code = *pc++;
6103     if (wc_code(code) != WC_LIST ||
6104 	(WC_LIST_TYPE(code) & (Z_SYNC|Z_END|Z_SIMPLE)) != (Z_SYNC|Z_END|Z_SIMPLE))
6105 	return prog;
6106     pc++;
6107     code = *pc++;
6108     if (wc_code(code) != WC_FUNCDEF ||	*pc != 1)
6109 	return prog;
6110 
6111     /*
6112      * See if name of function requested (name) is same as
6113      * name of function in word code.  name may still have "-"
6114      * tokenised.  The word code shouldn't, as function names should be
6115      * untokenised, but reports say it sometimes does.
6116      */
6117     ptr1 = name;
6118     ptr2 = ecrawstr(prog, pc + 1, NULL);
6119     while (*ptr1 && *ptr2) {
6120 	if (*ptr1 != *ptr2 && *ptr1 != Dash && *ptr1 != '-' &&
6121 	    *ptr2 != Dash && *ptr2 != '-')
6122 	    break;
6123 	ptr1++;
6124 	ptr2++;
6125     }
6126     if (*ptr1 || *ptr2)
6127 	return prog;
6128 
6129     {
6130 	Eprog ret;
6131 	Wordcode end = pc + WC_FUNCDEF_SKIP(code);
6132 	int sbeg = pc[2], nstrs = pc[3], nprg, npats = pc[4], plen, len, i;
6133 	Patprog *pp;
6134 
6135 	pc += 5;
6136 
6137 	nprg = end - pc;
6138 	plen = nprg * sizeof(wordcode);
6139 	len = plen + (npats * sizeof(Patprog)) + nstrs;
6140 
6141 	if (prog->flags & EF_MAP) {
6142 	    ret = prog;
6143 	    free(prog->pats);
6144 	    ret->pats = pp = (Patprog *) zalloc(npats * sizeof(Patprog));
6145 	    ret->prog = pc;
6146 	    ret->strs = prog->strs + sbeg;
6147 	} else {
6148 	    ret = (Eprog) zhalloc(sizeof(*ret));
6149 	    ret->flags = EF_HEAP;
6150 	    ret->pats = pp = (Patprog *) zhalloc(len);
6151 	    ret->prog = (Wordcode) (ret->pats + npats);
6152 	    ret->strs = (char *) (ret->prog + nprg);
6153 	    memcpy(ret->prog, pc, plen);
6154 	    memcpy(ret->strs, prog->strs + sbeg, nstrs);
6155 	    ret->dump = NULL;
6156 	}
6157 	ret->len = len;
6158 	ret->npats = npats;
6159 	for (i = npats; i--; pp++)
6160 	    *pp = dummy_patprog1;
6161 	ret->shf = NULL;
6162 
6163 	return ret;
6164     }
6165 }
6166 
6167 /* check to see if AUTOCD applies here */
6168 
6169 /**/
6170 static char *
6171 cancd(char *s)
6172 {
6173     int nocdpath = s[0] == '.' &&
6174     (s[1] == '/' || !s[1] || (s[1] == '.' && (s[2] == '/' || !s[1])));
6175     char *t;
6176 
6177     if (*s != '/') {
6178 	char sbuf[PATH_MAX+1], **cp;
6179 
6180 	if (cancd2(s))
6181 	    return s;
6182 	if (access(unmeta(s), X_OK) == 0)
6183 	    return NULL;
6184 	if (!nocdpath)
6185 	    for (cp = cdpath; *cp; cp++) {
6186 		if (strlen(*cp) + strlen(s) + 1 >= PATH_MAX)
6187 		    continue;
6188 		if (**cp)
6189 		    sprintf(sbuf, "%s/%s", *cp, s);
6190 		else
6191 		    strcpy(sbuf, s);
6192 		if (cancd2(sbuf)) {
6193 		    doprintdir = -1;
6194 		    return dupstring(sbuf);
6195 		}
6196 	    }
6197 	if ((t = cd_able_vars(s))) {
6198 	    if (cancd2(t)) {
6199 		doprintdir = -1;
6200 		return t;
6201 	    }
6202 	}
6203 	return NULL;
6204     }
6205     return cancd2(s) ? s : NULL;
6206 }
6207 
6208 /**/
6209 static int
6210 cancd2(char *s)
6211 {
6212     struct stat buf;
6213     char *us, *us2 = NULL;
6214     int ret;
6215 
6216     /*
6217      * If CHASEDOTS and CHASELINKS are not set, we want to rationalize the
6218      * path by removing foo/.. combinations in the logical rather than
6219      * the physical path.  If either is set, we test the physical path.
6220      */
6221     if (!isset(CHASEDOTS) && !isset(CHASELINKS)) {
6222 	if (*s != '/')
6223 	    us = tricat(pwd[1] ? pwd : "", "/", s);
6224 	else
6225 	    us = ztrdup(s);
6226 	fixdir(us2 = us);
6227     } else
6228 	us = unmeta(s);
6229     ret = !(access(us, X_OK) || stat(us, &buf) || !S_ISDIR(buf.st_mode));
6230     if (us2)
6231 	free(us2);
6232     return ret;
6233 }
6234 
6235 /**/
6236 void
6237 execsave(void)
6238 {
6239     struct execstack *es;
6240 
6241     es = (struct execstack *) zalloc(sizeof(struct execstack));
6242     es->list_pipe_pid = list_pipe_pid;
6243     es->nowait = nowait;
6244     es->pline_level = pline_level;
6245     es->list_pipe_child = list_pipe_child;
6246     es->list_pipe_job = list_pipe_job;
6247     strcpy(es->list_pipe_text, list_pipe_text);
6248     es->lastval = lastval;
6249     es->noeval = noeval;
6250     es->badcshglob = badcshglob;
6251     es->cmdoutpid = cmdoutpid;
6252     es->cmdoutval = cmdoutval;
6253     es->use_cmdoutval = use_cmdoutval;
6254     es->procsubstpid = procsubstpid;
6255     es->trap_return = trap_return;
6256     es->trap_state = trap_state;
6257     es->trapisfunc = trapisfunc;
6258     es->traplocallevel = traplocallevel;
6259     es->noerrs = noerrs;
6260     es->this_noerrexit = this_noerrexit;
6261     es->underscore = ztrdup(zunderscore);
6262     es->next = exstack;
6263     exstack = es;
6264     noerrs = cmdoutpid = 0;
6265 }
6266 
6267 /**/
6268 void
6269 execrestore(void)
6270 {
6271     struct execstack *en = exstack;
6272 
6273     DPUTS(!exstack, "BUG: execrestore() without execsave()");
6274 
6275     queue_signals();
6276     exstack = exstack->next;
6277 
6278     list_pipe_pid = en->list_pipe_pid;
6279     nowait = en->nowait;
6280     pline_level = en->pline_level;
6281     list_pipe_child = en->list_pipe_child;
6282     list_pipe_job = en->list_pipe_job;
6283     strcpy(list_pipe_text, en->list_pipe_text);
6284     lastval = en->lastval;
6285     noeval = en->noeval;
6286     badcshglob = en->badcshglob;
6287     cmdoutpid = en->cmdoutpid;
6288     cmdoutval = en->cmdoutval;
6289     use_cmdoutval = en->use_cmdoutval;
6290     procsubstpid = en->procsubstpid;
6291     trap_return = en->trap_return;
6292     trap_state = en->trap_state;
6293     trapisfunc = en->trapisfunc;
6294     traplocallevel = en->traplocallevel;
6295     noerrs = en->noerrs;
6296     this_noerrexit = en->this_noerrexit;
6297     setunderscore(en->underscore);
6298     zsfree(en->underscore);
6299     free(en);
6300 
6301     unqueue_signals();
6302 }
6303