Import tcsh-6.17.00
[dragonfly.git] / contrib / tcsh-6 / sh.sem.c
1 /* $Header: /p/tcsh/cvsroot/tcsh/sh.sem.c,v 3.80 2009/06/25 21:27:38 christos Exp $ */
2 /*
3  * sh.sem.c: I/O redirections and job forking. A touchy issue!
4  *           Most stuff with builtins is incorrect
5  */
6 /*-
7  * Copyright (c) 1980, 1991 The Regents of the University of California.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 #include "sh.h"
35
36 RCSID("$tcsh: sh.sem.c,v 3.80 2009/06/25 21:27:38 christos Exp $")
37
38 #include "tc.h"
39 #include "tw.h"
40 #ifdef WINNT_NATIVE
41 #include "nt.const.h"
42 #endif /*WINNT_NATIVE*/
43
44 #ifdef CLOSE_ON_EXEC
45 # ifndef SUNOS4
46 #  ifndef CLEX_DUPS
47 #   define CLEX_DUPS
48 #  endif /* CLEX_DUPS */
49 # endif /* !SUNOS4 */
50 #endif /* CLOSE_ON_EXEC */
51
52 #if defined(__sparc__) || defined(sparc)
53 # if !defined(MACH) && SYSVREL == 0 && !defined(Lynx) && !defined(BSD4_4) && !defined(linux) && !defined(__GNU__) && !defined(__GLIBC__)
54 #  include <vfork.h>
55 # endif /* !MACH && SYSVREL == 0 && !Lynx && !BSD4_4 && !glibc */
56 #endif /* __sparc__ || sparc */
57
58 #ifdef VFORK
59 static  void            vffree          (int);
60 #endif 
61 static  Char            *splicepipe     (struct command *, Char *);
62 static  void             doio           (struct command *, int *, int *);
63 static  void             chkclob        (const char *);
64
65 /*
66  * C shell
67  */
68
69 /*
70  * For SVR4, there are problems with pipelines having the first process as
71  * the group leader.  The problem occurs when the first process exits before
72  * the others have a chance to setpgid().  This is because in SVR4 you can't
73  * have a zombie as a group leader.  The solution I have used is to reverse
74  * the order in which pipelines are started, making the last process the
75  * group leader.  (Note I am not using 'pipeline' in the generic sense -- I
76  * mean processes connected by '|'.)  I don't know yet if this causes other
77  * problems.
78  *
79  * All the changes for this are in execute(), and are enclosed in 
80  * '#ifdef BACKPIPE'
81  *
82  * David Dawes (dawes@physics.su.oz.au) Oct 1991
83  */
84
85 /*VARARGS 1*/
86 void
87 execute(struct command *t, volatile int wanttty, int *pipein, int *pipeout,
88     int do_glob)
89 {
90     int    forked = 0;
91     const struct biltins * volatile bifunc;
92     pid_t pid = 0;
93     int     pv[2];
94     sigset_t set;
95     static sigset_t csigset;
96 #ifdef VFORK
97     static int onosigchld = 0;
98 #endif /* VFORK */
99     static int nosigchld = 0;
100
101     (void) &wanttty;
102     (void) &forked;
103     (void) &bifunc;
104
105     if (t == 0) 
106         return;
107
108 #ifdef WINNT_NATIVE
109     {
110         if ((varval(STRNTslowexec) == STRNULL) &&
111             !t->t_dcdr && !t->t_dcar && !t->t_dflg && !didfds &&
112             (intty || intact) && (t->t_dtyp == NODE_COMMAND) &&
113             !isbfunc(t)) {
114             if ((t->t_dcom[0][0] & (QUOTE | TRIM)) == QUOTE)
115                 (void) Strcpy(t->t_dcom[0], t->t_dcom[0] + 1);
116             Dfix(t);
117             if (nt_try_fast_exec(t) == 0)
118                 return;
119         }
120     }
121 #endif /* WINNT_NATIVE */
122
123     /*
124      * Ed hutchins@sgi.com & Dominic dbg@sgi.com
125      * Sat Feb 25 03:13:11 PST 1995
126      * try implicit cd if we have a 1 word command 
127      */
128     if (implicit_cd && (intty || intact) && t->t_dcom && t->t_dcom[0] &&
129          t->t_dcom[0][0] && (blklen(t->t_dcom) == 1) && !noexec) {
130         Char *sCName;
131         struct stat stbuf;
132         char *pathname;
133
134         sCName = dollar(t->t_dcom[0]);
135         if (sCName != NULL && sCName[0] == '~') {
136             struct Strbuf buf = Strbuf_INIT;
137             const Char *name_end;
138
139             for (name_end = sCName + 1; *name_end != '\0' && *name_end != '/';
140                  name_end++)
141                 continue;
142             if (name_end != sCName + 1) {
143                 Char *name, *home;
144
145                 name = Strnsave(sCName + 1, name_end - (sCName + 1));
146                 home = gethdir(name);
147                 if (home != NULL) {
148                     Strbuf_append(&buf, home);
149                     xfree(home);
150                 } else
151                     Strbuf_append(&buf, name);
152                 xfree(name);
153             } else
154                 Strbuf_append(&buf, varval(STRhome));
155             Strbuf_append(&buf, name_end);
156             xfree(sCName);
157             sCName = Strbuf_finish(&buf);
158         }
159
160         pathname = short2str(sCName);
161         xfree(sCName);
162         /* if this is a dir, tack a "cd" on as the first arg */
163         if (pathname != NULL &&
164             ((stat(pathname, &stbuf) != -1 && S_ISDIR(stbuf.st_mode))
165 #ifdef WINNT_NATIVE
166              || (pathname[0] && pathname[1] == ':' && pathname[2] == '\0')
167 #endif /* WINNT_NATIVE */
168              )) {
169             Char *vCD[2];
170             Char **ot_dcom = t->t_dcom;
171         
172             vCD[0] = Strsave(STRcd);
173             vCD[1] = NULL;
174             t->t_dcom = blkspl(vCD, ot_dcom);
175             xfree(ot_dcom);
176             if (implicit_cd > 1) {
177                 blkpr(t->t_dcom);
178                 xputchar( '\n' );
179             }
180         }
181     }
182
183     /*
184      * From: Michael Schroeder <mlschroe@immd4.informatik.uni-erlangen.de>
185      * Don't check for wantty > 0...
186      */
187     if (t->t_dflg & F_AMPERSAND)
188         wanttty = 0;
189     switch (t->t_dtyp) {
190
191     case NODE_COMMAND:
192         if ((t->t_dcom[0][0] & (QUOTE | TRIM)) == QUOTE)
193             memmove(t->t_dcom[0], t->t_dcom[0] + 1,
194                     (Strlen(t->t_dcom[0] + 1) + 1) * sizeof (*t->t_dcom[0]));
195         if ((t->t_dflg & F_REPEAT) == 0)
196             Dfix(t);            /* $ " ' \ */
197         if (t->t_dcom[0] == 0) {
198             return;
199         }
200         /*FALLTHROUGH*/
201
202     case NODE_PAREN:
203 #ifdef BACKPIPE
204         if (t->t_dflg & F_PIPEIN)
205             mypipe(pipein);
206 #else /* !BACKPIPE */
207         if (t->t_dflg & F_PIPEOUT)
208             mypipe(pipeout);
209 #endif /* BACKPIPE */
210         /*
211          * Must do << early so parent will know where input pointer should be.
212          * If noexec then this is all we do.
213          */
214         if (t->t_dflg & F_READ) {
215             xclose(0);
216             heredoc(t->t_dlef);
217             if (noexec)
218                 xclose(0);
219         }
220
221         setcopy(STRstatus, STR0, VAR_READWRITE);
222
223         /*
224          * This mess is the necessary kludge to handle the prefix builtins:
225          * nice, nohup, time.  These commands can also be used by themselves,
226          * and this is not handled here. This will also work when loops are
227          * parsed.
228          */
229         while (t->t_dtyp == NODE_COMMAND)
230             if (eq(t->t_dcom[0], STRnice)) {
231                 if (t->t_dcom[1]) {
232                     if (strchr("+-", t->t_dcom[1][0])) {
233                         if (t->t_dcom[2]) {
234                             setname("nice");
235                             t->t_nice =
236                                 getn(t->t_dcom[1]);
237                             lshift(t->t_dcom, 2);
238                             t->t_dflg |= F_NICE;
239                         }
240                         else
241                             break;
242                     }
243                     else {
244                         t->t_nice = 4;
245                         lshift(t->t_dcom, 1);
246                         t->t_dflg |= F_NICE;
247                     }
248                 }
249                 else
250                     break;
251             }
252             else if (eq(t->t_dcom[0], STRnohup)) {
253                 if (t->t_dcom[1]) {
254                     t->t_dflg |= F_NOHUP;
255                     lshift(t->t_dcom, 1);
256                 }
257                 else
258                     break;
259             }
260             else if (eq(t->t_dcom[0], STRhup)) {
261                 if (t->t_dcom[1]) {
262                     t->t_dflg |= F_HUP;
263                     lshift(t->t_dcom, 1);
264                 }
265                 else
266                     break;
267             }
268             else if (eq(t->t_dcom[0], STRtime)) {
269                 if (t->t_dcom[1]) {
270                     t->t_dflg |= F_TIME;
271                     lshift(t->t_dcom, 1);
272                 }
273                 else
274                     break;
275             }
276 #ifdef F_VER
277             else if (eq(t->t_dcom[0], STRver))
278                 if (t->t_dcom[1] && t->t_dcom[2]) {
279                     setname("ver");
280                     t->t_systype = getv(t->t_dcom[1]);
281                     lshift(t->t_dcom, 2);
282                     t->t_dflg |= F_VER;
283                 }
284                 else
285                     break;
286 #endif  /* F_VER */
287             else
288                 break;
289
290         /* is it a command */
291         if (t->t_dtyp == NODE_COMMAND) {
292             /*
293              * Check if we have a builtin function and remember which one.
294              */
295             bifunc = isbfunc(t);
296             if (noexec) {
297                 /*
298                  * Continue for builtins that are part of the scripting language
299                  */
300                 if (bifunc == NULL)
301                     break;
302                 if (bifunc->bfunct != (bfunc_t)dobreak  &&
303                     bifunc->bfunct != (bfunc_t)docontin &&
304                     bifunc->bfunct != (bfunc_t)doelse   &&
305                     bifunc->bfunct != (bfunc_t)doend    &&
306                     bifunc->bfunct != (bfunc_t)doforeach&&
307                     bifunc->bfunct != (bfunc_t)dogoto   &&
308                     bifunc->bfunct != (bfunc_t)doif     &&
309                     bifunc->bfunct != (bfunc_t)dorepeat &&
310                     bifunc->bfunct != (bfunc_t)doswbrk  &&
311                     bifunc->bfunct != (bfunc_t)doswitch &&
312                     bifunc->bfunct != (bfunc_t)dowhile  &&
313                     bifunc->bfunct != (bfunc_t)dozip)
314                     break;
315             }
316         }
317         else {                  /* not a command */
318             bifunc = NULL;
319             if (noexec)
320                 break;
321         }
322
323         /* 
324          * GrP Executing a command - run jobcmd hook
325          * Don't run for builtins
326          * Don't run if we're not in a tty
327          * Don't run if we're not really executing 
328          */
329         /*
330          * CR  -  Charles Ross Aug 2005
331          * added "isoutatty".
332          * The new behavior is that the jobcmd won't be executed
333          * if stdout (SHOUT) isnt attached to a tty.. IE when
334          * redirecting, or using backquotes etc..
335          */
336         if (t->t_dtyp == NODE_COMMAND && !bifunc && !noexec && intty && isoutatty) {
337             Char *cmd = unparse(t);
338
339             cleanup_push(cmd, xfree);
340             job_cmd(cmd);
341             cleanup_until(cmd);
342         }
343            
344         /*
345          * We fork only if we are timed, or are not the end of a parenthesized
346          * list and not a simple builtin function. Simple meaning one that is
347          * not pipedout, niced, nohupped, or &'d. It would be nice(?) to not
348          * fork in some of these cases.
349          */
350         /*
351          * Prevent forking cd, pushd, popd, chdir cause this will cause the
352          * shell not to change dir!
353          */
354 #ifdef BACKPIPE
355         /*
356          * Can't have NOFORK for the tail of a pipe - because it is not the
357          * last command spawned (even if it is at the end of a parenthesised
358          * list).
359          */
360         if (t->t_dflg & F_PIPEIN)
361             t->t_dflg &= ~(F_NOFORK);
362 #endif /* BACKPIPE */
363         if (bifunc && (bifunc->bfunct == (bfunc_t)dochngd ||
364                        bifunc->bfunct == (bfunc_t)dopushd ||
365                        bifunc->bfunct == (bfunc_t)dopopd))
366             t->t_dflg &= ~(F_NICE);
367         if (((t->t_dflg & F_TIME) || ((t->t_dflg & F_NOFORK) == 0 &&
368              (!bifunc || t->t_dflg &
369               (F_PIPEOUT | F_AMPERSAND | F_NICE | F_NOHUP | F_HUP)))) ||
370         /*
371          * We have to fork for eval too.
372          */
373             (bifunc && (t->t_dflg & F_PIPEIN) != 0 &&
374              bifunc->bfunct == (bfunc_t)doeval)) {
375 #ifdef VFORK
376             if (t->t_dtyp == NODE_PAREN ||
377                 t->t_dflg & (F_REPEAT | F_AMPERSAND) || bifunc)
378 #endif /* VFORK */
379             {
380                 forked++;
381                 /*
382                  * We need to block SIGCHLD here, so that if the process does
383                  * not die before we can set the process group
384                  */
385                 if (wanttty >= 0 && !nosigchld) {
386                     sigemptyset(&set);
387                     sigaddset(&set, SIGCHLD);
388                     (void)sigprocmask(SIG_BLOCK, &set, &csigset);
389
390                     nosigchld = 1;
391                 }
392
393                 pid = pfork(t, wanttty);
394                 if (pid == 0 && nosigchld) {
395                     sigprocmask(SIG_SETMASK, &csigset, NULL);
396                     nosigchld = 0;
397                 }
398                 else if (pid != 0 && (t->t_dflg & F_AMPERSAND))
399                     backpid = pid;
400             }
401
402 #ifdef VFORK
403             else {
404                 int     ochild, osetintr, ohaderr, odidfds;
405                 int     oSHIN, oSHOUT, oSHDIAG, oOLDSTD, otpgrp;
406                 int     oisoutatty, oisdiagatty;
407                 sigset_t oset, ocsigset;
408 # ifndef CLOSE_ON_EXEC
409                 int     odidcch;
410 # endif  /* !CLOSE_ON_EXEC */
411
412                 /*
413                  * Prepare for the vfork by saving everything that the child
414                  * corrupts before it exec's. Note that in some signal
415                  * implementations which keep the signal info in user space
416                  * (e.g. Sun's) it will also be necessary to save and restore
417                  * the current sigvec's for the signals the child touches
418                  * before it exec's.
419                  */
420
421                 /*
422                  * Sooooo true... If this is a Sun, save the sigvec's. (Skip
423                  * Gilbrech - 11/22/87)
424                  */
425 # ifdef SAVESIGVEC
426                 struct sigaction savesv[NSIGSAVED];
427                 sigset_t savesm;
428
429 # endif /* SAVESIGVEC */
430                 if (wanttty >= 0 && !nosigchld && !noexec) {
431                     sigemptyset(&set);
432                     sigaddset(&set, SIGCHLD);
433                     (void)sigprocmask(SIG_BLOCK, &set, &csigset);
434                     nosigchld = 1;
435                 }
436                 sigemptyset(&set);
437                 sigaddset(&set, SIGCHLD);
438                 sigaddset(&set, SIGINT);
439                 (void)sigprocmask(SIG_BLOCK, &set, &oset);
440                 ochild = child;
441                 osetintr = setintr;
442                 ohaderr = haderr;
443                 odidfds = didfds;
444 # ifndef CLOSE_ON_EXEC
445                 odidcch = didcch;
446 # endif /* !CLOSE_ON_EXEC */
447                 oSHIN = SHIN;
448                 oSHOUT = SHOUT;
449                 oSHDIAG = SHDIAG;
450                 oOLDSTD = OLDSTD;
451                 otpgrp = tpgrp;
452                 oisoutatty = isoutatty;
453                 oisdiagatty = isdiagatty;
454                 ocsigset = csigset;
455                 onosigchld = nosigchld;
456                 Vsav = Vdp = 0;
457                 Vexpath = 0;
458                 Vt = 0;
459 # ifdef SAVESIGVEC
460                 savesigvec(savesv, savesm);
461 # endif /* SAVESIGVEC */
462                 if (use_fork)
463                     pid = fork();
464                 else
465                     pid = vfork();
466
467                 if (pid < 0) {
468 # ifdef SAVESIGVEC
469                     restoresigvec(savesv, savesm);
470 # endif /* SAVESIGVEC */
471                     sigprocmask(SIG_SETMASK, &oset, NULL);
472                     stderror(ERR_NOPROC);
473                 }
474                 forked++;
475                 if (pid) {      /* parent */
476 # ifdef SAVESIGVEC
477                     restoresigvec(savesv, savesm);
478 # endif /* SAVESIGVEC */
479                     child = ochild;
480                     setintr = osetintr;
481                     haderr = ohaderr;
482                     didfds = odidfds;
483                     SHIN = oSHIN;
484 # ifndef CLOSE_ON_EXEC
485                     didcch = odidcch;
486 # endif /* !CLOSE_ON_EXEC */
487                     SHOUT = oSHOUT;
488                     SHDIAG = oSHDIAG;
489                     OLDSTD = oOLDSTD;
490                     tpgrp = otpgrp;
491                     isoutatty = oisoutatty;
492                     isdiagatty = oisdiagatty;
493                     csigset = ocsigset;
494                     nosigchld = onosigchld;
495
496                     xfree(Vsav);
497                     Vsav = 0;
498                     xfree(Vdp);
499                     Vdp = 0;
500                     xfree(Vexpath);
501                     Vexpath = 0;
502                     blk_cleanup(Vt);
503                     Vt = 0;
504                     /* this is from pfork() */
505                     palloc(pid, t);
506                     sigprocmask(SIG_SETMASK, &oset, NULL);
507                 }
508                 else {          /* child */
509                     /* this is from pfork() */
510                     pid_t pgrp;
511                     int    ignint = 0;
512                     if (nosigchld) {
513                         sigprocmask(SIG_SETMASK, &csigset, NULL);
514                         nosigchld = 0;
515                     }
516
517                     if (setintr)
518                         ignint = (tpgrp == -1 && (t->t_dflg & F_NOINTERRUPT))
519                                 || (gointr && eq(gointr, STRminus));
520                     pgrp = pcurrjob ? pcurrjob->p_jobid : getpid();
521                     child++;
522                     if (setintr) {
523                         setintr = 0;
524 /*
525  * casts made right for SunOS 4.0 by Douglas C. Schmidt
526  * <schmidt%sunshine.ics.uci.edu@ROME.ICS.UCI.EDU>
527  * (thanks! -- PWP)
528  *
529  * ignint ifs cleaned by Johan Widen <mcvax!osiris.sics.se!jw@uunet.UU.NET>
530  * (thanks again)
531  */
532                         if (ignint) {
533                             (void) signal(SIGINT, SIG_IGN);
534                             (void) signal(SIGQUIT, SIG_IGN);
535                         }
536                         else {
537                             (void) signal(SIGINT, vffree);
538                             (void) signal(SIGQUIT, SIG_DFL);
539                         }
540 # ifdef BSDJOBS
541                         if (wanttty >= 0) {
542                             (void) signal(SIGTSTP, SIG_DFL);
543                             (void) signal(SIGTTIN, SIG_DFL);
544                             (void) signal(SIGTTOU, SIG_DFL);
545                         }
546 # endif /* BSDJOBS */
547
548                         sigaction(SIGTERM, &parterm, NULL);
549                     }
550                     else if (tpgrp == -1 &&
551                              (t->t_dflg & F_NOINTERRUPT)) {
552                         (void) signal(SIGINT, SIG_IGN);
553                         (void) signal(SIGQUIT, SIG_IGN);
554                     }
555
556                     pgetty(wanttty, pgrp);
557
558                     if (t->t_dflg & F_NOHUP)
559                         (void) signal(SIGHUP, SIG_IGN);
560                     if (t->t_dflg & F_HUP)
561                         (void) signal(SIGHUP, SIG_DFL);
562                     if (t->t_dflg & F_NICE) {
563                         int nval = SIGN_EXTEND_CHAR(t->t_nice);
564 # ifdef HAVE_SETPRIORITY
565                         if (setpriority(PRIO_PROCESS, 0, nval) == -1 && errno)
566                                 stderror(ERR_SYSTEM, "setpriority",
567                                     strerror(errno));
568 # else /* !HAVE_SETPRIORITY */
569                         (void) nice(nval);
570 # endif /* HAVE_SETPRIORITY */
571                     }
572 # ifdef F_VER
573                     if (t->t_dflg & F_VER) {
574                         tsetenv(STRSYSTYPE, t->t_systype ? STRbsd43 : STRsys53);
575                         dohash(NULL, NULL);
576                     }
577 # endif /* F_VER */
578                 }
579
580             }
581 #endif /* VFORK */
582         }
583         if (pid != 0) {
584             /*
585              * It would be better if we could wait for the whole job when we
586              * knew the last process had been started.  Pwait, in fact, does
587              * wait for the whole job anyway, but this test doesn't really
588              * express our intentions.
589              */
590 #ifdef BACKPIPE
591             if (didfds == 0 && t->t_dflg & F_PIPEOUT) {
592                 xclose(pipeout[0]);
593                 xclose(pipeout[1]);
594             }
595             if ((t->t_dflg & F_PIPEIN) != 0)
596                 break;
597 #else /* !BACKPIPE */
598             if (didfds == 0 && t->t_dflg & F_PIPEIN) {
599                 xclose(pipein[0]);
600                 xclose(pipein[1]);
601             }
602             if ((t->t_dflg & F_PIPEOUT) != 0)
603                 break;
604 #endif /* BACKPIPE */
605
606             if (nosigchld) {
607                 sigprocmask(SIG_SETMASK, &csigset, NULL);
608                 nosigchld = 0;
609             }
610             if ((t->t_dflg & F_AMPERSAND) == 0)
611                 pwait();
612             break;
613         }
614
615         doio(t, pipein, pipeout);
616 #ifdef BACKPIPE
617         if (t->t_dflg & F_PIPEIN) {
618             xclose(pipein[0]);
619             xclose(pipein[1]);
620         }
621 #else /* !BACKPIPE */
622         if (t->t_dflg & F_PIPEOUT) {
623             xclose(pipeout[0]);
624             xclose(pipeout[1]);
625         }
626 #endif /* BACKPIPE */
627         /*
628          * Perform a builtin function. If we are not forked, arrange for
629          * possible stopping
630          */
631         if (bifunc) {
632             func(t, bifunc);
633             if (forked)
634                 exitstat();
635             else {
636                 if (adrof(STRprintexitvalue)) {
637                     int rv = getn(varval(STRstatus));
638                     if (rv != 0)
639                         xprintf(CGETS(17, 2, "Exit %d\n"), rv);
640                 }
641             }
642             break;
643         }
644         if (t->t_dtyp != NODE_PAREN) {
645             doexec(t, do_glob);
646             /* NOTREACHED */
647         }
648         /*
649          * For () commands must put new 0,1,2 in FSH* and recurse
650          */
651         (void)close_on_exec(OLDSTD = dcopy(0, FOLDSTD), 1);
652         (void)close_on_exec(SHOUT = dcopy(1, FSHOUT), 1);
653         isoutatty = isatty(SHOUT);
654         (void)close_on_exec(SHDIAG = dcopy(2, FSHDIAG), 1);
655         isdiagatty = isatty(SHDIAG);
656         xclose(SHIN);
657         SHIN = -1;
658 #ifndef CLOSE_ON_EXEC
659         didcch = 0;
660 #else
661         (void) close_on_exec(FSHOUT, 1);
662         (void) close_on_exec(FSHDIAG, 1);
663         (void) close_on_exec(FOLDSTD, 1);
664 #endif /* !CLOSE_ON_EXEC */
665         didfds = 0;
666         wanttty = -1;
667         t->t_dspr->t_dflg |= t->t_dflg & F_NOINTERRUPT;
668         execute(t->t_dspr, wanttty, NULL, NULL, do_glob);
669         exitstat();
670
671     case NODE_PIPE:
672 #ifdef BACKPIPE
673         t->t_dcdr->t_dflg |= F_PIPEIN | (t->t_dflg &
674                         (F_PIPEOUT | F_AMPERSAND | F_NOFORK | F_NOINTERRUPT));
675         execute(t->t_dcdr, wanttty, pv, pipeout, do_glob);
676         t->t_dcar->t_dflg |= F_PIPEOUT |
677             (t->t_dflg & (F_PIPEIN | F_AMPERSAND | F_STDERR | F_NOINTERRUPT));
678         execute(t->t_dcar, wanttty, pipein, pv, do_glob);
679 #else /* !BACKPIPE */
680         t->t_dcar->t_dflg |= F_PIPEOUT |
681             (t->t_dflg & (F_PIPEIN | F_AMPERSAND | F_STDERR | F_NOINTERRUPT));
682         execute(t->t_dcar, wanttty, pipein, pv, do_glob);
683         t->t_dcdr->t_dflg |= F_PIPEIN | (t->t_dflg &
684                         (F_PIPEOUT | F_AMPERSAND | F_NOFORK | F_NOINTERRUPT));
685         execute(t->t_dcdr, wanttty, pv, pipeout, do_glob);
686 #endif /* BACKPIPE */
687         break;
688
689     case NODE_LIST:
690         if (t->t_dcar) {
691             t->t_dcar->t_dflg |= t->t_dflg & F_NOINTERRUPT;
692             execute(t->t_dcar, wanttty, NULL, NULL, do_glob);
693             /*
694              * In strange case of A&B make a new job after A
695              */
696             if (t->t_dcar->t_dflg & F_AMPERSAND && t->t_dcdr &&
697                 (t->t_dcdr->t_dflg & F_AMPERSAND) == 0)
698                 pendjob();
699         }
700         if (t->t_dcdr) {
701             t->t_dcdr->t_dflg |= t->t_dflg &
702                 (F_NOFORK | F_NOINTERRUPT);
703             execute(t->t_dcdr, wanttty, NULL, NULL, do_glob);
704         }
705         break;
706
707     case NODE_OR:
708     case NODE_AND:
709         if (t->t_dcar) {
710             t->t_dcar->t_dflg |= t->t_dflg & F_NOINTERRUPT;
711             execute(t->t_dcar, wanttty, NULL, NULL, do_glob);
712             if ((getn(varval(STRstatus)) == 0) !=
713                 (t->t_dtyp == NODE_AND)) {
714                 return;
715             }
716         }
717         if (t->t_dcdr) {
718             t->t_dcdr->t_dflg |= t->t_dflg &
719                 (F_NOFORK | F_NOINTERRUPT);
720             execute(t->t_dcdr, wanttty, NULL, NULL, do_glob);
721         }
722         break;
723
724     default:
725         break;
726     }
727     /*
728      * Fall through for all breaks from switch
729      * 
730      * If there will be no more executions of this command, flush all file
731      * descriptors. Places that turn on the F_REPEAT bit are responsible for
732      * doing donefds after the last re-execution
733      */
734     if (didfds && !(t->t_dflg & F_REPEAT))
735         donefds();
736 }
737
738 #ifdef VFORK
739 static void
740 /*ARGSUSED*/
741 vffree(int snum)
742 {
743     USE(snum);
744
745     _exit(1);
746 }
747 #endif /* VFORK */
748
749 /*
750  * Expand and glob the words after an i/o redirection.
751  * If more than one word is generated, then update the command vector.
752  *
753  * This is done differently in all the shells:
754  * 1. in the bourne shell and ksh globbing is not performed
755  * 2. Bash/csh say ambiguous
756  * 3. zsh does i/o to/from all the files
757  * 4. itcsh concatenates the words.
758  *
759  * I don't know what is best to do. I think that Ambiguous is better
760  * than restructuring the command vector, because the user can get
761  * unexpected results. In any case, the command vector restructuring 
762  * code is present and the user can choose it by setting noambiguous
763  */
764 static Char *
765 splicepipe(struct command *t, Char *cp)
766 {
767     Char *blk[2];
768
769     if (adrof(STRnoambiguous)) {
770         Char **pv;
771         int gflag;
772
773         blk[0] = Dfix1(cp); /* expand $ */
774         blk[1] = NULL;
775
776         gflag = tglob(blk);
777         if (gflag) {
778             pv = globall(blk, gflag);
779             if (pv == NULL) {
780                 setname(short2str(blk[0]));
781                 xfree(blk[0]);
782                 stderror(ERR_NAME | ERR_NOMATCH);
783             }
784             if (pv[1] != NULL) { /* we need to fix the command vector */
785                 Char **av = blkspl(t->t_dcom, &pv[1]);
786                 xfree(t->t_dcom);
787                 t->t_dcom = av;
788             }
789             xfree(blk[0]);
790             blk[0] = pv[0];
791             xfree(pv);
792         }
793     }
794     else {
795         Char *buf;
796
797         buf = Dfix1(cp);
798         cleanup_push(buf, xfree);
799         blk[0] = globone(buf, G_ERROR);
800         cleanup_until(buf);
801     }
802     return(blk[0]);
803 }
804     
805 /*
806  * Perform io redirection.
807  * We may or maynot be forked here.
808  */
809 static void
810 doio(struct command *t, int *pipein, int *pipeout)
811 {
812     int fd;
813     Char *cp;
814     unsigned long flags = t->t_dflg;
815
816     if (didfds || (flags & F_REPEAT))
817         return;
818     if ((flags & F_READ) == 0) {/* F_READ already done */
819         if (t->t_dlef) {
820             char *tmp;
821
822             /*
823              * so < /dev/std{in,out,err} work
824              */
825             (void) dcopy(SHIN, 0);
826             (void) dcopy(SHOUT, 1);
827             (void) dcopy(SHDIAG, 2);
828             cp = splicepipe(t, t->t_dlef);
829             tmp = strsave(short2str(cp));
830             xfree(cp);
831             cleanup_push(tmp, xfree);
832             if ((fd = xopen(tmp, O_RDONLY|O_LARGEFILE)) < 0)
833                 stderror(ERR_SYSTEM, tmp, strerror(errno));
834             cleanup_until(tmp);
835             /* allow input files larger than 2Gb  */
836 #ifndef WINNT_NATIVE
837             (void) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_LARGEFILE);
838 #endif /*!WINNT_NATIVE*/
839             (void) dmove(fd, 0);
840         }
841         else if (flags & F_PIPEIN) {
842             xclose(0);
843             IGNORE(dup(pipein[0]));
844             xclose(pipein[0]);
845             xclose(pipein[1]);
846         }
847         else if ((flags & F_NOINTERRUPT) && tpgrp == -1) {
848             xclose(0);
849             (void) xopen(_PATH_DEVNULL, O_RDONLY|O_LARGEFILE);
850         }
851         else {
852             xclose(0);
853             IGNORE(dup(OLDSTD));
854 #if defined(CLOSE_ON_EXEC) && defined(CLEX_DUPS)
855             /*
856              * PWP: Unlike Bezerkeley 4.3, FIONCLEX for Pyramid is preserved
857              * across dup()s, so we have to UNSET it here or else we get a
858              * command with NO stdin, stdout, or stderr at all (a bad thing
859              * indeed)
860              */
861             (void) close_on_exec(0, 0);
862 #endif /* CLOSE_ON_EXEC && CLEX_DUPS */
863         }
864     }
865     if (t->t_drit) {
866         char *tmp;
867
868         cp = splicepipe(t, t->t_drit);
869         tmp = strsave(short2str(cp));
870         xfree(cp);
871         cleanup_push(tmp, xfree);
872         /*
873          * so > /dev/std{out,err} work
874          */
875         (void) dcopy(SHOUT, 1);
876         (void) dcopy(SHDIAG, 2);
877         if ((flags & F_APPEND) != 0) {
878 #ifdef O_APPEND
879             fd = xopen(tmp, O_WRONLY|O_APPEND|O_LARGEFILE);
880 #else /* !O_APPEND */
881             fd = xopen(tmp, O_WRONLY|O_LARGEFILE);
882             (void) lseek(fd, (off_t) 0, L_XTND);
883 #endif /* O_APPEND */
884         }
885         else
886             fd = 0;
887         if ((flags & F_APPEND) == 0 || fd == -1) {
888             if (!(flags & F_OVERWRITE) && adrof(STRnoclobber)) {
889                 if (flags & F_APPEND)
890                     stderror(ERR_SYSTEM, tmp, strerror(errno));
891                 chkclob(tmp);
892             }
893             if ((fd = xcreat(tmp, 0666)) < 0)
894                 stderror(ERR_SYSTEM, tmp, strerror(errno));
895             /* allow input files larger than 2Gb  */
896 #ifndef WINNT_NATIVE
897             (void) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_LARGEFILE);
898 #endif /*!WINNT_NATIVE*/
899         }
900         cleanup_until(tmp);
901         (void) dmove(fd, 1);
902         is1atty = isatty(1);
903     }
904     else if (flags & F_PIPEOUT) {
905         xclose(1);
906         IGNORE(dup(pipeout[1]));
907         is1atty = 0;
908     }
909     else {
910         xclose(1);
911         IGNORE(dup(SHOUT));
912         is1atty = isoutatty;
913 # if defined(CLOSE_ON_EXEC) && defined(CLEX_DUPS)
914         (void) close_on_exec(1, 0);
915 # endif /* CLOSE_ON_EXEC && CLEX_DUPS */
916     }
917
918     xclose(2);
919     if (flags & F_STDERR) {
920         IGNORE(dup(1));
921         is2atty = is1atty;
922     }
923     else {
924         IGNORE(dup(SHDIAG));
925         is2atty = isdiagatty;
926 # if defined(CLOSE_ON_EXEC) && defined(CLEX_DUPS)
927         (void) close_on_exec(2, 0);
928 # endif /* CLOSE_ON_EXEC && CLEX_DUPS */
929     }
930     didfds = 1;
931 }
932
933 void
934 mypipe(int *pv)
935 {
936
937     if (pipe(pv) < 0)
938         goto oops;
939     (void)close_on_exec(pv[0] = dmove(pv[0], -1), 1);
940     (void)close_on_exec(pv[1] = dmove(pv[1], -1), 1);
941     if (pv[0] >= 0 && pv[1] >= 0)
942         return;
943     if (pv[0] >= 0)
944         xclose(pv[0]);
945     if (pv[1] >= 0)
946         xclose(pv[1]);
947 oops:
948     stderror(ERR_PIPE);
949 }
950
951 static void
952 chkclob(const char *cp)
953 {
954     struct stat stb;
955
956     if (stat(cp, &stb) < 0)
957         return;
958     if (S_ISCHR(stb.st_mode))
959         return;
960     stderror(ERR_EXISTS, cp);
961 }