Cleanup code near the top part of JobFinish()
[dragonfly.git] / usr.bin / make / job.c
1 /*-
2  * Copyright (c) 1988, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1988, 1989 by Adam de Boor
5  * Copyright (c) 1989 by Berkeley Softworks
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Adam de Boor.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *      This product includes software developed by the University of
22  *      California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  *
39  * @(#)job.c    8.2 (Berkeley) 3/19/94
40  * $FreeBSD: src/usr.bin/make/job.c,v 1.75 2005/02/10 14:32:14 harti Exp $
41  * $DragonFly: src/usr.bin/make/job.c,v 1.82 2005/04/28 18:47:09 okumoto Exp $
42  */
43
44 #ifndef OLD_JOKE
45 #define OLD_JOKE 0
46 #endif /* OLD_JOKE */
47
48 /*-
49  * job.c --
50  *      handle the creation etc. of our child processes.
51  *
52  * Interface:
53  *      Job_Make        Start the creation of the given target.
54  *
55  *      Job_CatchChildren
56  *                      Check for and handle the termination of any children.
57  *                      This must be called reasonably frequently to keep the
58  *                      whole make going at a decent clip, since job table
59  *                      entries aren't removed until their process is caught
60  *                      this way. Its single argument is TRUE if the function
61  *                      should block waiting for a child to terminate.
62  *
63  *      Job_CatchOutput Print any output our children have produced. Should
64  *                      also be called fairly frequently to keep the user
65  *                      informed of what's going on. If no output is waiting,
66  *                      it will block for a time given by the SEL_* constants,
67  *                      below, or until output is ready.
68  *
69  *      Job_Init        Called to intialize this module. in addition, any
70  *                      commands attached to the .BEGIN target are executed
71  *                      before this function returns. Hence, the makefile must
72  *                      have been parsed before this function is called.
73  *
74  *      Job_Full        Return TRUE if the job table is filled.
75  *
76  *      Job_Empty       Return TRUE if the job table is completely empty.
77  *
78  *      Job_ParseShell  Given the line following a .SHELL target, parse the
79  *                      line as a shell specification. Returns FAILURE if the
80  *                      spec was incorrect.
81  *
82  *      Job_Finish      Perform any final processing which needs doing. This
83  *                      includes the execution of any commands which have
84  *                      been/were attached to the .END target. It should only
85  *                      be called when the job table is empty.
86  *
87  *      Job_AbortAll    Abort all currently running jobs. It doesn't handle
88  *                      output or do anything for the jobs, just kills them.
89  *                      It should only be called in an emergency, as it were.
90  *
91  *      Job_CheckCommands
92  *                      Verify that the commands for a target are ok. Provide
93  *                      them if necessary and possible.
94  *
95  *      Job_Touch       Update a target without really updating it.
96  *
97  *      Job_Wait        Wait for all currently-running jobs to finish.
98  *
99  * compat.c --
100  *      The routines in this file implement the full-compatibility
101  *      mode of PMake. Most of the special functionality of PMake
102  *      is available in this mode. Things not supported:
103  *          - different shells.
104  *          - friendly variable substitution.
105  *
106  * Interface:
107  *      Compat_Run          Initialize things for this module and recreate
108  *                          thems as need creatin'
109  */
110
111 #include <sys/queue.h>
112 #include <sys/types.h>
113 #include <sys/select.h>
114 #include <sys/stat.h>
115 #ifdef USE_KQUEUE
116 #include <sys/event.h>
117 #endif
118 #include <sys/wait.h>
119 #include <ctype.h>
120 #include <errno.h>
121 #include <fcntl.h>
122 #include <inttypes.h>
123 #include <string.h>
124 #include <signal.h>
125 #include <stdlib.h>
126 #include <unistd.h>
127 #include <utime.h>
128
129 #include "arch.h"
130 #include "buf.h"
131 #include "config.h"
132 #include "dir.h"
133 #include "globals.h"
134 #include "GNode.h"
135 #include "job.h"
136 #include "make.h"
137 #include "parse.h"
138 #include "pathnames.h"
139 #include "str.h"
140 #include "suff.h"
141 #include "targ.h"
142 #include "util.h"
143 #include "var.h"
144
145 #define TMPPAT  "/tmp/makeXXXXXXXXXX"
146
147 #ifndef USE_KQUEUE
148 /*
149  * The SEL_ constants determine the maximum amount of time spent in select
150  * before coming out to see if a child has finished. SEL_SEC is the number of
151  * seconds and SEL_USEC is the number of micro-seconds
152  */
153 #define SEL_SEC         2
154 #define SEL_USEC        0
155 #endif /* !USE_KQUEUE */
156
157 /*
158  * Job Table definitions.
159  *
160  * The job "table" is kept as a linked Lst in 'jobs', with the number of
161  * active jobs maintained in the 'nJobs' variable. At no time will this
162  * exceed the value of 'maxJobs', initialized by the Job_Init function.
163  *
164  * When a job is finished, the Make_Update function is called on each of the
165  * parents of the node which was just remade. This takes care of the upward
166  * traversal of the dependency graph.
167  */
168 #define JOB_BUFSIZE     1024
169 typedef struct Job {
170         pid_t           pid;    /* The child's process ID */
171
172         struct GNode    *node;  /* The target the child is making */
173
174         /*
175          * A LstNode for the first command to be saved after the job completes.
176          * This is NULL if there was no "..." in the job's commands.
177          */
178         LstNode         *tailCmds;
179
180         /*
181          * An FILE* for writing out the commands. This is only
182          * used before the job is actually started.
183          */
184         FILE            *cmdFILE;
185
186         /*
187          * A word of flags which determine how the module handles errors,
188          * echoing, etc. for the job
189          */
190         short           flags;  /* Flags to control treatment of job */
191 #define JOB_IGNERR      0x001   /* Ignore non-zero exits */
192 #define JOB_SILENT      0x002   /* no output */
193 #define JOB_SPECIAL     0x004   /* Target is a special one. i.e. run it locally
194                                  * if we can't export it and maxLocal is 0 */
195 #define JOB_IGNDOTS     0x008   /* Ignore "..." lines when processing
196                                  * commands */
197 #define JOB_FIRST       0x020   /* Job is first job for the node */
198 #define JOB_RESTART     0x080   /* Job needs to be completely restarted */
199 #define JOB_RESUME      0x100   /* Job needs to be resumed b/c it stopped,
200                                  * for some reason */
201 #define JOB_CONTINUING  0x200   /* We are in the process of resuming this job.
202                                  * Used to avoid infinite recursion between
203                                  * JobFinish and JobRestart */
204
205         /* union for handling shell's output */
206         union {
207                 /*
208                  * This part is used when usePipes is true.
209                  * The output is being caught via a pipe and the descriptors
210                  * of our pipe, an array in which output is line buffered and
211                  * the current position in that buffer are all maintained for
212                  * each job.
213                  */
214                 struct {
215                         /*
216                          * Input side of pipe associated with
217                          * job's output channel
218                          */
219                         int     op_inPipe;
220
221                         /*
222                          * Output side of pipe associated with job's
223                          * output channel
224                          */
225                         int     op_outPipe;
226
227                         /*
228                          * Buffer for storing the output of the
229                          * job, line by line
230                          */
231                         char    op_outBuf[JOB_BUFSIZE + 1];
232
233                         /* Current position in op_outBuf */
234                         int     op_curPos;
235                 }       o_pipe;
236
237                 /*
238                  * If usePipes is false the output is routed to a temporary
239                  * file and all that is kept is the name of the file and the
240                  * descriptor open to the file.
241                  */
242                 struct {
243                         /* Name of file to which shell output was rerouted */
244                         char    of_outFile[sizeof(TMPPAT)];
245
246                         /*
247                          * Stream open to the output file. Used to funnel all
248                          * from a single job to one file while still allowing
249                          * multiple shell invocations
250                          */
251                         int     of_outFd;
252                 }       o_file;
253
254         }       output;     /* Data for tracking a shell's output */
255
256         TAILQ_ENTRY(Job) link;  /* list link */
257 } Job;
258
259 #define outPipe         output.o_pipe.op_outPipe
260 #define inPipe          output.o_pipe.op_inPipe
261 #define outBuf          output.o_pipe.op_outBuf
262 #define curPos          output.o_pipe.op_curPos
263 #define outFile         output.o_file.of_outFile
264 #define outFd           output.o_file.of_outFd
265
266 TAILQ_HEAD(JobList, Job);
267
268 /*
269  * Shell Specifications:
270  *
271  * Some special stuff goes on if a shell doesn't have error control. In such
272  * a case, errCheck becomes a printf template for echoing the command,
273  * should echoing be on and ignErr becomes another printf template for
274  * executing the command while ignoring the return status. If either of these
275  * strings is empty when hasErrCtl is FALSE, the command will be executed
276  * anyway as is and if it causes an error, so be it.
277  */
278 #define DEF_SHELL_STRUCT(TAG, CONST)                                    \
279 struct TAG {                                                            \
280         /*                                                              \
281          * the name of the shell. For Bourne and C shells, this is used \
282          * only to find the shell description when used as the single   \
283          * source of a .SHELL target. For user-defined shells, this is  \
284          * the full path of the shell.                                  \
285          */                                                             \
286         CONST char      *name;                                          \
287                                                                         \
288         /* True if both echoOff and echoOn defined */                   \
289         Boolean         hasEchoCtl;                                     \
290                                                                         \
291         CONST char      *echoOff;       /* command to turn off echo */  \
292         CONST char      *echoOn;        /* command to turn it back on */\
293                                                                         \
294         /*                                                              \
295          * What the shell prints, and its length, when given the        \
296          * echo-off command. This line will not be printed when         \
297          * received from the shell. This is usually the command which   \
298          * was executed to turn off echoing                             \
299          */                                                             \
300         CONST char      *noPrint;                                       \
301                                                                         \
302         /* set if can control error checking for individual commands */ \
303         Boolean         hasErrCtl;                                      \
304                                                                         \
305         /* string to turn error checking on */                          \
306         CONST char      *errCheck;                                      \
307                                                                         \
308         /* string to turn off error checking */                         \
309         CONST char      *ignErr;                                        \
310                                                                         \
311         CONST char      *echo;  /* command line flag: echo commands */  \
312         CONST char      *exit;  /* command line flag: exit on error */  \
313 }
314
315 DEF_SHELL_STRUCT(Shell,);
316 DEF_SHELL_STRUCT(CShell, const);
317
318 /*
319  * error handling variables
320  */
321 static int      errors = 0;     /* number of errors reported */
322 static int      aborting = 0;   /* why is the make aborting? */
323 #define ABORT_ERROR     1       /* Because of an error */
324 #define ABORT_INTERRUPT 2       /* Because it was interrupted */
325 #define ABORT_WAIT      3       /* Waiting for jobs to finish */
326
327 /*
328  * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
329  * is a char! So when we go above 127 we turn negative!
330  */
331 #define FILENO(a) ((unsigned)fileno(a))
332
333 /*
334  * post-make command processing. The node postCommands is really just the
335  * .END target but we keep it around to avoid having to search for it
336  * all the time.
337  */
338 static GNode    *postCommands;
339
340 /*
341  * The number of commands actually printed for a target. Should this
342  * number be 0, no shell will be executed.
343  */
344 static int      numCommands;
345
346 /*
347  * Return values from JobStart.
348  */
349 #define JOB_RUNNING     0       /* Job is running */
350 #define JOB_ERROR       1       /* Error in starting the job */
351 #define JOB_FINISHED    2       /* The job is already finished */
352 #define JOB_STOPPED     3       /* The job is stopped */
353
354 /*
355  * Descriptions for various shells.
356  */
357 static const struct CShell shells[] = {
358         /*
359          * CSH description. The csh can do echo control by playing
360          * with the setting of the 'echo' shell variable. Sadly,
361          * however, it is unable to do error control nicely.
362          */
363         {
364                 "csh",
365                 TRUE, "unset verbose", "set verbose", "unset verbose",
366                 FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"",
367                 "v", "e",
368         },
369         /*
370          * SH description. Echo control is also possible and, under
371          * sun UNIX anyway, one can even control error checking.
372          */
373         {
374                 "sh",
375                 TRUE, "set -", "set -v", "set -",
376                 TRUE, "set -e", "set +e",
377 #ifdef OLDBOURNESHELL
378                 FALSE, "echo \"%s\"\n", "sh -c '%s || exit 0'\n",
379 #endif
380                 "v", "e",
381         },
382         /*
383          * KSH description. The Korn shell has a superset of
384          * the Bourne shell's functionality.
385          */
386         {
387                 "ksh",
388                 TRUE, "set -", "set -v", "set -",
389                 TRUE, "set -e", "set +e",
390                 "v", "e",
391         },
392 };
393
394 /*
395  * This is the shell to which we pass all commands in the Makefile.
396  * It is set by the Job_ParseShell function.
397  */
398 static struct Shell *commandShell = NULL;
399 static char     *shellPath = NULL;      /* full pathname of executable image */
400 static char     *shellName = NULL;      /* last component of shell */
401
402 int             maxJobs;        /* The most children we can run at once */
403 static int      nJobs;          /* The number of children currently running */
404
405 /* The structures that describe them */
406 static struct JobList jobs = TAILQ_HEAD_INITIALIZER(jobs);
407
408 static Boolean  jobFull;        /* Flag to tell when the job table is full. It
409                                  * is set TRUE when (1) the total number of
410                                  * running jobs equals the maximum allowed */
411 #ifdef USE_KQUEUE
412 static int      kqfd;           /* File descriptor obtained by kqueue() */
413 #else
414 static fd_set   outputs;        /* Set of descriptors of pipes connected to
415                                  * the output channels of children */
416 #endif
417
418 static GNode    *lastNode;      /* The node for which output was most recently
419                                  * produced. */
420 static const char *targFmt;     /* Format string to use to head output from a
421                                  * job when it's not the most-recent job heard
422                                  * from */
423
424 #define TARG_FMT  "--- %s ---\n" /* Default format */
425 #define MESSAGE(fp, gn) \
426          fprintf(fp, targFmt, gn->name);
427
428 /*
429  * When JobStart attempts to run a job but isn't allowed to
430  * or when Job_CatchChildren detects a job that has
431  * been stopped somehow, the job is placed on the stoppedJobs queue to be run
432  * when the next job finishes.
433  *
434  * Lst of Job structures describing jobs that were stopped due to
435  * concurrency limits or externally
436  */
437 static struct JobList stoppedJobs = TAILQ_HEAD_INITIALIZER(stoppedJobs);
438
439 static int      fifoFd;         /* Fd of our job fifo */
440 static char     fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
441 static int      fifoMaster;
442
443 static sig_atomic_t interrupted;
444
445
446 #if defined(USE_PGRP) && defined(SYSV)
447 # define KILL(pid, sig)         killpg(-(pid), (sig))
448 #else
449 # if defined(USE_PGRP)
450 #  define KILL(pid, sig)        killpg((pid), (sig))
451 # else
452 #  define KILL(pid, sig)        kill((pid), (sig))
453 # endif
454 #endif
455
456 /*
457  * Grmpf... There is no way to set bits of the wait structure
458  * anymore with the stupid W*() macros. I liked the union wait
459  * stuff much more. So, we devise our own macros... This is
460  * really ugly, use dramamine sparingly. You have been warned.
461  */
462 #define W_SETMASKED(st, val, fun)                               \
463         {                                                       \
464                 int sh = (int)~0;                               \
465                 int mask = fun(sh);                             \
466                                                                 \
467                 for (sh = 0; ((mask >> sh) & 1) == 0; sh++)     \
468                         continue;                               \
469                 *(st) = (*(st) & ~mask) | ((val) << sh);        \
470         }
471
472 #define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
473 #define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
474
475 /**
476  * Information used to create a new process.
477  */
478 typedef struct ProcStuff {
479         int     in;     /* stdin for new process */
480         int     out;    /* stdout for new process */
481         int     err;    /* stderr for new process */
482
483         int     merge_errors;   /* true if stderr is redirected to stdin */
484         int     pgroup;         /* true if new process a process leader */
485         int     searchpath;     /* true if binary should be found via $PATH */
486
487         char    **argv;
488
489         pid_t   child_pid;
490 } ProcStuff;
491
492 static void JobRestart(Job *);
493 static int JobStart(GNode *, int, Job *);
494 static void JobDoOutput(Job *, Boolean);
495 static struct Shell *JobMatchShell(const char *);
496 static void JobInterrupt(int, int);
497 static void JobRestartJobs(void);
498 static void ProcExec(ProcStuff *) __dead2;
499
500 /*
501  * The following array is used to make a fast determination of which
502  * characters are interpreted specially by the shell.  If a command
503  * contains any of these characters, it is executed by the shell, not
504  * directly by us.
505  */
506 static char         meta[256];
507
508 static GNode        *curTarg = NULL;
509 static GNode        *ENDNode;
510
511 /**
512  * Replace the current process.
513  */
514 static void
515 ProcExec(ProcStuff *ps)
516 {
517         if (ps->in != STDIN_FILENO) {
518                 /*
519                  * Redirect the child's stdin to the input fd
520                  * and reset it to the beginning (again).
521                  */
522                 if (dup2(ps->in, STDIN_FILENO) == -1)
523                         Punt("Cannot dup2: %s", strerror(errno));
524                 lseek(STDIN_FILENO, (off_t)0, SEEK_SET);
525         }
526
527         if (ps->out != STDOUT_FILENO) {
528                 /*
529                  * Redirect the child's stdout to the output fd.
530                  */
531                 if (dup2(ps->out, STDOUT_FILENO) == -1)
532                         Punt("Cannot dup2: %s", strerror(errno));
533                 close(ps->out);
534         }
535
536         if (ps->err != STDERR_FILENO) {
537                 /*
538                  * Redirect the child's stderr to the err fd.
539                  */
540                 if (dup2(ps->err, STDERR_FILENO) == -1)
541                         Punt("Cannot dup2: %s", strerror(errno));
542                 close(ps->err);
543         }
544
545         if (ps->merge_errors) {
546                 /*
547                  * Send stderr to parent process too. 
548                  */
549                 if (dup2(STDOUT_FILENO, STDERR_FILENO) == -1)
550                         Punt("Cannot dup2: %s", strerror(errno));
551         }
552
553         /*
554          * The file descriptors for stdin, stdout, or stderr might
555          * have been marked close-on-exec.  Clear the flag on all
556          * of them.
557          */
558         fcntl(STDIN_FILENO, F_SETFD,
559             fcntl(STDIN_FILENO, F_GETFD) & (~FD_CLOEXEC));
560         fcntl(STDOUT_FILENO, F_SETFD,
561             fcntl(STDOUT_FILENO, F_GETFD) & (~FD_CLOEXEC));
562         fcntl(STDERR_FILENO, F_SETFD,
563             fcntl(STDERR_FILENO, F_GETFD) & (~FD_CLOEXEC));
564
565         if (ps->pgroup) {
566 #ifdef USE_PGRP
567                 /*
568                  * Become a process group leader, so we can kill it and all
569                  * its descendants in one fell swoop, by killing its process
570                  * family, but not commit suicide.
571                  */
572 #if defined(SYSV)
573                 setsid();
574 #else
575                 setpgid(0, getpid());
576 #endif
577 #endif /* USE_PGRP */
578         }
579
580         if (ps->searchpath) {
581                 execvp(ps->argv[0], ps->argv);
582
583                 write(STDERR_FILENO, ps->argv[0], strlen(ps->argv[0]));
584                 write(STDERR_FILENO, ":", 1);
585                 write(STDERR_FILENO, strerror(errno), strlen(strerror(errno)));
586                 write(STDERR_FILENO, "\n", 1);
587         } else {
588                 execv(shellPath, ps->argv);
589
590                 write(STDERR_FILENO,
591                       "Could not execute shell\n",
592                       sizeof("Could not execute shell"));
593         }
594
595         /*
596          * Since we are the child process, exit without flushing buffers.
597          */
598         _exit(1);
599 }
600
601 /**
602  * Wait for child process to terminate.
603  */
604 static int
605 ProcWait(ProcStuff *ps)
606 {
607         pid_t   pid;
608         int     status;
609
610         /*
611          * Wait for the process to exit.
612          */
613         for (;;) {
614                 pid = wait(&status);
615                 if (pid == -1 && errno != EINTR) {
616                         Fatal("error in wait: %d", pid);
617                         /* NOTREACHED */
618                 }
619                 if (pid == ps->child_pid) {
620                         break;
621                 }
622                 if (interrupted) {
623                         break;
624                 }
625         }
626
627         return (status);
628 }
629
630 /**
631  * JobCatchSignal
632  *      Got a signal. Set global variables and hope that someone will
633  *      handle it.
634  */
635 static void
636 JobCatchSig(int signo)
637 {
638
639         interrupted = signo;
640 }
641
642 /**
643  * JobPassSig --
644  *      Pass a signal on to all local jobs if
645  *      USE_PGRP is defined, then die ourselves.
646  *
647  * Side Effects:
648  *      We die by the same signal.
649  */
650 static void
651 JobPassSig(int signo)
652 {
653         Job     *job;
654         sigset_t nmask, omask;
655         struct sigaction act;
656
657         sigemptyset(&nmask);
658         sigaddset(&nmask, signo);
659         sigprocmask(SIG_SETMASK, &nmask, &omask);
660
661         DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
662         TAILQ_FOREACH(job, &jobs, link) {
663                 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
664                     signo, (intmax_t)job->pid));
665                 KILL(job->pid, signo);
666         }
667
668         /*
669          * Deal with proper cleanup based on the signal received. We only run
670          * the .INTERRUPT target if the signal was in fact an interrupt.
671          * The other three termination signals are more of a "get out *now*"
672          * command.
673          */
674         if (signo == SIGINT) {
675                 JobInterrupt(TRUE, signo);
676         } else if (signo == SIGHUP || signo == SIGTERM || signo == SIGQUIT) {
677                 JobInterrupt(FALSE, signo);
678         }
679
680         /*
681          * Leave gracefully if SIGQUIT, rather than core dumping.
682          */
683         if (signo == SIGQUIT) {
684                 signo = SIGINT;
685         }
686
687         /*
688          * Send ourselves the signal now we've given the message to everyone
689          * else. Note we block everything else possible while we're getting
690          * the signal. This ensures that all our jobs get continued when we
691          * wake up before we take any other signal.
692          * XXX this comment seems wrong.
693          */
694         act.sa_handler = SIG_DFL;
695         sigemptyset(&act.sa_mask);
696         act.sa_flags = 0;
697         sigaction(signo, &act, NULL);
698
699         DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
700             ~0 & ~(1 << (signo - 1))));
701         signal(signo, SIG_DFL);
702
703         KILL(getpid(), signo);
704
705         signo = SIGCONT;
706         TAILQ_FOREACH(job, &jobs, link) {
707                 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
708                     signo, (intmax_t)job->pid));
709                 KILL(job->pid, signo);
710         }
711
712         sigprocmask(SIG_SETMASK, &omask, NULL);
713         sigprocmask(SIG_SETMASK, &omask, NULL);
714         act.sa_handler = JobPassSig;
715         sigaction(signo, &act, NULL);
716 }
717
718 /**
719  * JobPrintCommand  --
720  *      Put out another command for the given job. If the command starts
721  *      with an @ or a - we process it specially. In the former case,
722  *      so long as the -s and -n flags weren't given to make, we stick
723  *      a shell-specific echoOff command in the script. In the latter,
724  *      we ignore errors for the entire job, unless the shell has error
725  *      control.
726  *      If the command is just "..." we take all future commands for this
727  *      job to be commands to be executed once the entire graph has been
728  *      made and return non-zero to signal that the end of the commands
729  *      was reached. These commands are later attached to the postCommands
730  *      node and executed by Job_Finish when all things are done.
731  *      This function is called from JobStart via LST_FOREACH.
732  *
733  * Results:
734  *      Always 0, unless the command was "..."
735  *
736  * Side Effects:
737  *      If the command begins with a '-' and the shell has no error control,
738  *      the JOB_IGNERR flag is set in the job descriptor.
739  *      If the command is "..." and we're not ignoring such things,
740  *      tailCmds is set to the successor node of the cmd.
741  *      numCommands is incremented if the command is actually printed.
742  */
743 static int
744 JobPrintCommand(char *cmd, Job *job)
745 {
746         Boolean noSpecials;     /* true if we shouldn't worry about
747                                  * inserting special commands into
748                                  * the input stream. */
749         Boolean shutUp = FALSE; /* true if we put a no echo command
750                                  * into the command file */
751         Boolean errOff = FALSE; /* true if we turned error checking
752                                  * off before printing the command
753                                  * and need to turn it back on */
754         const char *cmdTemplate;/* Template to use when printing the command */
755         char    *cmdStart;      /* Start of expanded command */
756         LstNode *cmdNode;       /* Node for replacing the command */
757
758         noSpecials = (noExecute && !(job->node->type & OP_MAKE));
759
760         if (strcmp(cmd, "...") == 0) {
761                 job->node->type |= OP_SAVE_CMDS;
762                 if ((job->flags & JOB_IGNDOTS) == 0) {
763                         job->tailCmds =
764                             Lst_Succ(Lst_Member(&job->node->commands, cmd));
765                         return (1);
766                 }
767                 return (0);
768         }
769
770 #define DBPRINTF(fmt, arg)                      \
771         DEBUGF(JOB, (fmt, arg));                \
772         fprintf(job->cmdFILE, fmt, arg);        \
773         fflush(job->cmdFILE);
774
775         numCommands += 1;
776
777         /*
778          * For debugging, we replace each command with the result of expanding
779          * the variables in the command.
780          */
781         cmdNode = Lst_Member(&job->node->commands, cmd);
782
783         cmd = Buf_Peel(Var_Subst(cmd, job->node, FALSE));
784         cmdStart = cmd;
785
786         Lst_Replace(cmdNode, cmdStart);
787
788         cmdTemplate = "%s\n";
789
790         /*
791          * Check for leading @', -' or +'s to control echoing, error checking,
792          * and execution on -n.
793          */
794         while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
795                 switch (*cmd) {
796
797                   case '@':
798                         shutUp = DEBUG(LOUD) ? FALSE : TRUE;
799                         break;
800
801                   case '-':
802                         errOff = TRUE;
803                         break;
804
805                   case '+':
806                         if (noSpecials) {
807                                 /*
808                                  * We're not actually exececuting anything...
809                                  * but this one needs to be - use compat mode
810                                  * just for it.
811                                  */
812                                 Compat_RunCommand(cmd, job->node);
813                                 return (0);
814                         }
815                         break;
816                 }
817                 cmd++;
818         }
819
820         while (isspace((unsigned char)*cmd))
821                 cmd++;
822
823         if (shutUp) {
824                 if (!(job->flags & JOB_SILENT) && !noSpecials &&
825                     commandShell->hasEchoCtl) {
826                         DBPRINTF("%s\n", commandShell->echoOff);
827                 } else {
828                         shutUp = FALSE;
829                 }
830         }
831
832         if (errOff) {
833                 if (!(job->flags & JOB_IGNERR) && !noSpecials) {
834                         if (commandShell->hasErrCtl) {
835                                 /*
836                                  * We don't want the error-control commands
837                                  * showing up either, so we turn off echoing
838                                  * while executing them. We could put another
839                                  * field in the shell structure to tell
840                                  * JobDoOutput to look for this string too,
841                                  * but why make it any more complex than
842                                  * it already is?
843                                  */
844                                 if (!(job->flags & JOB_SILENT) && !shutUp &&
845                                     commandShell->hasEchoCtl) {
846                                         DBPRINTF("%s\n", commandShell->echoOff);
847                                         DBPRINTF("%s\n", commandShell->ignErr);
848                                         DBPRINTF("%s\n", commandShell->echoOn);
849                                 } else {
850                                         DBPRINTF("%s\n", commandShell->ignErr);
851                                 }
852                         } else if (commandShell->ignErr &&
853                             *commandShell->ignErr != '\0') {
854                                 /*
855                                  * The shell has no error control, so we need to
856                                  * be weird to get it to ignore any errors from
857                                  * the command. If echoing is turned on, we turn
858                                  * it off and use the errCheck template to echo
859                                  * the command. Leave echoing off so the user
860                                  * doesn't see the weirdness we go through to
861                                  * ignore errors. Set cmdTemplate to use the
862                                  * weirdness instead of the simple "%s\n"
863                                  * template.
864                                  */
865                                 if (!(job->flags & JOB_SILENT) && !shutUp &&
866                                     commandShell->hasEchoCtl) {
867                                         DBPRINTF("%s\n", commandShell->echoOff);
868                                         DBPRINTF(commandShell->errCheck, cmd);
869                                         shutUp = TRUE;
870                                 }
871                                 cmdTemplate = commandShell->ignErr;
872                                 /*
873                                  * The error ignoration (hee hee) is already
874                                  * taken care of by the ignErr template, so
875                                  * pretend error checking is still on.
876                                 */
877                                 errOff = FALSE;
878                         } else {
879                                 errOff = FALSE;
880                         }
881                 } else {
882                         errOff = FALSE;
883                 }
884         }
885
886         DBPRINTF(cmdTemplate, cmd);
887
888         if (errOff) {
889                 /*
890                  * If echoing is already off, there's no point in issuing the
891                  * echoOff command. Otherwise we issue it and pretend it was on
892                  * for the whole command...
893                  */
894                 if (!shutUp && !(job->flags & JOB_SILENT) &&
895                     commandShell->hasEchoCtl) {
896                         DBPRINTF("%s\n", commandShell->echoOff);
897                         shutUp = TRUE;
898                 }
899                 DBPRINTF("%s\n", commandShell->errCheck);
900         }
901         if (shutUp) {
902                 DBPRINTF("%s\n", commandShell->echoOn);
903         }
904         return (0);
905 }
906
907 /**
908  * JobClose --
909  *      Called to close both input and output pipes when a job is finished.
910  *
911  * Side Effects:
912  *      The file descriptors associated with the job are closed.
913  */
914 static void
915 JobClose(Job *job)
916 {
917
918         if (usePipes) {
919 #if !defined(USE_KQUEUE)
920                 FD_CLR(job->inPipe, &outputs);
921 #endif
922                 if (job->outPipe != job->inPipe) {
923                         close(job->outPipe);
924                 }
925                 JobDoOutput(job, TRUE);
926                 close(job->inPipe);
927         } else {
928                 close(job->outFd);
929                 JobDoOutput(job, TRUE);
930         }
931 }
932
933 /**
934  * JobFinish  --
935  *      Do final processing for the given job including updating
936  *      parents and starting new jobs as available/necessary. Note
937  *      that we pay no attention to the JOB_IGNERR flag here.
938  *      This is because when we're called because of a noexecute flag
939  *      or something, jstat.w_status is 0 and when called from
940  *      Job_CatchChildren, the status is zeroed if it s/b ignored.
941  *
942  * Side Effects:
943  *      Some nodes may be put on the toBeMade queue.
944  *      Final commands for the job are placed on postCommands.
945  *
946  *      If we got an error and are aborting (aborting == ABORT_ERROR) and
947  *      the job list is now empty, we are done for the day.
948  *      If we recognized an error (errors !=0), we set the aborting flag
949  *      to ABORT_ERROR so no more jobs will be started.
950  */
951 static void
952 JobFinish(Job *job, int *status)
953 {
954         Boolean done;
955         LstNode *ln;
956
957         if (WIFEXITED(*status)) {
958                 int     job_status = WEXITSTATUS(*status);
959
960                 JobClose(job);
961                 /*
962                  * Deal with ignored errors in -B mode. We need to
963                  * print a message telling of the ignored error as
964                  * well as setting status.w_status to 0 so the next
965                  * command gets run. To do this, we set done to be
966                  * TRUE if in -B mode and the job exited non-zero.
967                  */
968                 if (job_status == 0) {
969                         done = FALSE;
970                 } else {
971                         if (job->flags & JOB_IGNERR) {
972                                 done = TRUE;
973                         } else {
974                                 /*
975                                  * If it exited non-zero and either we're
976                                  * doing things our way or we're not ignoring
977                                  * errors, the job is finished. Similarly, if
978                                  * the shell died because of a signal the job
979                                  * is also finished. In these cases, finish
980                                  * out the job's output before printing the
981                                  * exit status...
982                                  */
983                                 done = TRUE;
984                                 if (job->cmdFILE != NULL &&
985                                     job->cmdFILE != stdout) {
986                                         fclose(job->cmdFILE);
987                                 }
988
989                         }
990                 }
991         } else if (WIFSIGNALED(*status)) {
992                 if (WTERMSIG(*status) == SIGCONT) {
993                         /*
994                          * No need to close things down or anything.
995                          */
996                         done = FALSE;
997                 } else {
998                         /*
999                          * If it exited non-zero and either we're
1000                          * doing things our way or we're not ignoring
1001                          * errors, the job is finished. Similarly, if
1002                          * the shell died because of a signal the job
1003                          * is also finished. In these cases, finish
1004                          * out the job's output before printing the
1005                          * exit status...
1006                          */
1007                         JobClose(job);
1008                         if (job->cmdFILE != NULL &&
1009                             job->cmdFILE != stdout) {
1010                                 fclose(job->cmdFILE);
1011                         }
1012                         done = TRUE;
1013                 }
1014         } else {
1015                 /*
1016                  * No need to close things down or anything.
1017                  */
1018                 done = FALSE;
1019         }
1020
1021         if (done || WIFSTOPPED(*status) ||
1022             (WIFSIGNALED(*status) && WTERMSIG(*status) == SIGCONT) ||
1023             DEBUG(JOB)) {
1024                 FILE    *out;
1025
1026                 if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
1027                         /*
1028                          * If output is going to a file and this job is ignoring
1029                          * errors, arrange to have the exit status sent to the
1030                          * output file as well.
1031                          */
1032                         out = fdopen(job->outFd, "w");
1033                         if (out == NULL)
1034                                 Punt("Cannot fdopen");
1035                 } else {
1036                         out = stdout;
1037                 }
1038
1039                 if (WIFEXITED(*status)) {
1040                         DEBUGF(JOB, ("Process %jd exited.\n",
1041                             (intmax_t)job->pid));
1042                         if (WEXITSTATUS(*status) != 0) {
1043                                 if (usePipes && job->node != lastNode) {
1044                                         MESSAGE(out, job->node);
1045                                         lastNode = job->node;
1046                                 }
1047                                 fprintf(out, "*** Error code %d%s\n",
1048                                     WEXITSTATUS(*status),
1049                                     (job->flags & JOB_IGNERR) ?
1050                                     "(ignored)" : "");
1051
1052                                 if (job->flags & JOB_IGNERR) {
1053                                         *status = 0;
1054                                 }
1055                         } else if (DEBUG(JOB)) {
1056                                 if (usePipes && job->node != lastNode) {
1057                                         MESSAGE(out, job->node);
1058                                         lastNode = job->node;
1059                                 }
1060                                 fprintf(out, "*** Completed successfully\n");
1061                         }
1062
1063                 } else if (WIFSTOPPED(*status)) {
1064                         DEBUGF(JOB, ("Process %jd stopped.\n",
1065                             (intmax_t)job->pid));
1066                         if (usePipes && job->node != lastNode) {
1067                                 MESSAGE(out, job->node);
1068                                 lastNode = job->node;
1069                         }
1070                         fprintf(out, "*** Stopped -- signal %d\n",
1071                         WSTOPSIG(*status));
1072                         job->flags |= JOB_RESUME;
1073                         TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1074                         fflush(out);
1075                         return;
1076
1077                 } else if (WTERMSIG(*status) == SIGCONT) {
1078                         /*
1079                          * If the beastie has continued, shift the Job from
1080                          * the stopped list to the running one (or re-stop it
1081                          * if concurrency is exceeded) and go and get another
1082                          * child.
1083                          */
1084                         if (job->flags & (JOB_RESUME | JOB_RESTART)) {
1085                                 if (usePipes && job->node != lastNode) {
1086                                         MESSAGE(out, job->node);
1087                                         lastNode = job->node;
1088                                 }
1089                                 fprintf(out, "*** Continued\n");
1090                         }
1091                         if (!(job->flags & JOB_CONTINUING)) {
1092                                 DEBUGF(JOB, ("Warning: process %jd was not "
1093                                     "continuing.\n", (intmax_t)job->pid));
1094 #ifdef notdef
1095                                 /*
1096                                  * We don't really want to restart a job from
1097                                  * scratch just because it continued, especially
1098                                  * not without killing the continuing process!
1099                                  *  That's why this is ifdef'ed out.
1100                                  * FD - 9/17/90
1101                                  */
1102                                 JobRestart(job);
1103 #endif
1104                         }
1105                         job->flags &= ~JOB_CONTINUING;
1106                         TAILQ_INSERT_TAIL(&jobs, job, link);
1107                         nJobs += 1;
1108                         DEBUGF(JOB, ("Process %jd is continuing locally.\n",
1109                             (intmax_t)job->pid));
1110                         if (nJobs == maxJobs) {
1111                                 jobFull = TRUE;
1112                                 DEBUGF(JOB, ("Job queue is full.\n"));
1113                         }
1114                         fflush(out);
1115                         return;
1116
1117                 } else {
1118                         if (usePipes && job->node != lastNode) {
1119                                 MESSAGE(out, job->node);
1120                                 lastNode = job->node;
1121                         }
1122                         fprintf(out, "*** Signal %d\n", WTERMSIG(*status));
1123                 }
1124
1125                 fflush(out);
1126         }
1127
1128         /*
1129          * Now handle the -B-mode stuff. If the beast still isn't finished,
1130          * try and restart the job on the next command. If JobStart says it's
1131          * ok, it's ok. If there's an error, this puppy is done.
1132          */
1133         if (compatMake && WIFEXITED(*status) &&
1134             Lst_Succ(job->node->compat_command) != NULL) {
1135                 switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
1136                   case JOB_RUNNING:
1137                         done = FALSE;
1138                         break;
1139                   case JOB_ERROR:
1140                         done = TRUE;
1141                         W_SETEXITSTATUS(status, 1);
1142                         break;
1143                   case JOB_FINISHED:
1144                         /*
1145                          * If we got back a JOB_FINISHED code, JobStart has
1146                          * already called Make_Update and freed the job
1147                          * descriptor. We set done to false here to avoid fake
1148                          * cycles and double frees. JobStart needs to do the
1149                          * update so we can proceed up the graph when given
1150                          * the -n flag..
1151                          */
1152                         done = FALSE;
1153                         break;
1154                   default:
1155                         break;
1156                 }
1157         } else {
1158                 done = TRUE;
1159         }
1160
1161         if (done && aborting != ABORT_ERROR &&
1162             aborting != ABORT_INTERRUPT && *status == 0) {
1163                 /*
1164                  * As long as we aren't aborting and the job didn't return a
1165                  * non-zero status that we shouldn't ignore, we call
1166                  * Make_Update to update the parents. In addition, any saved
1167                  * commands for the node are placed on the .END target.
1168                  */
1169                 for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
1170                         Lst_AtEnd(&postCommands->commands,
1171                             Buf_Peel(
1172                                 Var_Subst(Lst_Datum(ln), job->node, FALSE)));
1173                 }
1174
1175                 job->node->made = MADE;
1176                 Make_Update(job->node);
1177                 free(job);
1178
1179         } else if (*status != 0) {
1180                 errors += 1;
1181                 free(job);
1182         }
1183
1184         JobRestartJobs();
1185
1186         /*
1187          * Set aborting if any error.
1188          */
1189         if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
1190                 /*
1191                  * If we found any errors in this batch of children and the -k
1192                  * flag wasn't given, we set the aborting flag so no more jobs
1193                  * get started.
1194                  */
1195                 aborting = ABORT_ERROR;
1196         }
1197
1198         if (aborting == ABORT_ERROR && Job_Empty()) {
1199                 /*
1200                  * If we are aborting and the job table is now empty, we finish.
1201                  */
1202                 Finish(errors);
1203         }
1204 }
1205
1206 /**
1207  * Job_Touch
1208  *      Touch the given target. Called by JobStart when the -t flag was
1209  *      given.  Prints messages unless told to be silent.
1210  *
1211  * Side Effects:
1212  *      The data modification of the file is changed. In addition, if the
1213  *      file did not exist, it is created.
1214  */
1215 void
1216 Job_Touch(GNode *gn, Boolean silent)
1217 {
1218         int     streamID;       /* ID of stream opened to do the touch */
1219         struct utimbuf times;   /* Times for utime() call */
1220
1221         if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
1222                 /*
1223                  * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
1224                  * targets and, as such, shouldn't really be created.
1225                  */
1226                 return;
1227         }
1228
1229         if (!silent) {
1230                 fprintf(stdout, "touch %s\n", gn->name);
1231                 fflush(stdout);
1232         }
1233
1234         if (noExecute) {
1235                 return;
1236         }
1237
1238         if (gn->type & OP_ARCHV) {
1239                 Arch_Touch(gn);
1240         } else if (gn->type & OP_LIB) {
1241                 Arch_TouchLib(gn);
1242         } else {
1243                 char    *file = gn->path ? gn->path : gn->name;
1244
1245                 times.actime = times.modtime = now;
1246                 if (utime(file, &times) < 0) {
1247                         streamID = open(file, O_RDWR | O_CREAT, 0666);
1248
1249                         if (streamID >= 0) {
1250                                 char    c;
1251
1252                                 /*
1253                                  * Read and write a byte to the file to change
1254                                  * the modification time, then close the file.
1255                                  */
1256                                 if (read(streamID, &c, 1) == 1) {
1257                                         lseek(streamID, (off_t)0, SEEK_SET);
1258                                         write(streamID, &c, 1);
1259                                 }
1260
1261                                 close(streamID);
1262                         } else {
1263                                 fprintf(stdout, "*** couldn't touch %s: %s",
1264                                     file, strerror(errno));
1265                                 fflush(stdout);
1266                         }
1267                 }
1268         }
1269 }
1270
1271 /**
1272  * Job_CheckCommands
1273  *      Make sure the given node has all the commands it needs.
1274  *
1275  * Results:
1276  *      TRUE if the commands list is/was ok.
1277  *
1278  * Side Effects:
1279  *      The node will have commands from the .DEFAULT rule added to it
1280  *      if it needs them.
1281  */
1282 Boolean
1283 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1284 {
1285
1286         if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
1287             (gn->type & OP_LIB) == 0) {
1288                 /*
1289                  * No commands. Look for .DEFAULT rule from which we might infer
1290                  * commands.
1291                  */
1292                 if (DEFAULT != NULL && !Lst_IsEmpty(&DEFAULT->commands)) {
1293                         char *p1;
1294                         /*
1295                          * Make only looks for a .DEFAULT if the node was
1296                          * never the target of an operator, so that's what we
1297                          * do too. If a .DEFAULT was given, we substitute its
1298                          * commands for gn's commands and set the IMPSRC
1299                          * variable to be the target's name The DEFAULT node
1300                          * acts like a transformation rule, in that gn also
1301                          * inherits any attributes or sources attached to
1302                          * .DEFAULT itself.
1303                          */
1304                         Make_HandleUse(DEFAULT, gn);
1305                         Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn);
1306                         free(p1);
1307
1308                 } else if (Dir_MTime(gn) == 0) {
1309                         /*
1310                          * The node wasn't the target of an operator we have
1311                          * no .DEFAULT rule to go on and the target doesn't
1312                          * already exist. There's nothing more we can do for
1313                          * this branch. If the -k flag wasn't given, we stop
1314                          * in our tracks, otherwise we just don't update
1315                          * this node's parents so they never get examined.
1316                          */
1317                         static const char msg[] =
1318                             "make: don't know how to make";
1319
1320                         if (gn->type & OP_OPTIONAL) {
1321                                 fprintf(stdout, "%s %s(ignored)\n",
1322                                     msg, gn->name);
1323                                 fflush(stdout);
1324                         } else if (keepgoing) {
1325                                 fprintf(stdout, "%s %s(continuing)\n",
1326                                     msg, gn->name);
1327                                 fflush(stdout);
1328                                 return (FALSE);
1329                         } else {
1330 #if OLD_JOKE
1331                                 if (strcmp(gn->name,"love") == 0)
1332                                         (*abortProc)("Not war.");
1333                                 else
1334 #endif
1335                                         (*abortProc)("%s %s. Stop",
1336                                             msg, gn->name);
1337                                 return (FALSE);
1338                         }
1339                 }
1340         }
1341         return (TRUE);
1342 }
1343
1344 /**
1345  * JobExec
1346  *      Execute the shell for the given job. Called from JobStart and
1347  *      JobRestart.
1348  *
1349  * Side Effects:
1350  *      A shell is executed, outputs is altered and the Job structure added
1351  *      to the job table.
1352  */
1353 static void
1354 JobExec(Job *job, char **argv)
1355 {
1356         ProcStuff       ps;
1357
1358         if (DEBUG(JOB)) {
1359                 int       i;
1360
1361                 DEBUGF(JOB, ("Running %s\n", job->node->name));
1362                 DEBUGF(JOB, ("\tCommand: "));
1363                 for (i = 0; argv[i] != NULL; i++) {
1364                         DEBUGF(JOB, ("%s ", argv[i]));
1365                 }
1366                 DEBUGF(JOB, ("\n"));
1367         }
1368
1369         /*
1370          * Some jobs produce no output and it's disconcerting to have
1371          * no feedback of their running (since they produce no output, the
1372          * banner with their name in it never appears). This is an attempt to
1373          * provide that feedback, even if nothing follows it.
1374          */
1375         if (lastNode != job->node && (job->flags & JOB_FIRST) &&
1376             !(job->flags & JOB_SILENT)) {
1377                 MESSAGE(stdout, job->node);
1378                 lastNode = job->node;
1379         }
1380
1381         ps.in = FILENO(job->cmdFILE);
1382         if (usePipes) {
1383                 /*
1384                  * Set up the child's output to be routed through the
1385                  * pipe we've created for it.
1386                  */
1387                 ps.out = job->outPipe;
1388         } else {
1389                 /*
1390                  * We're capturing output in a file, so we duplicate
1391                  * the descriptor to the temporary file into the
1392                  * standard output.
1393                  */
1394                 ps.out = job->outFd;
1395         }
1396         ps.err = STDERR_FILENO;
1397
1398         ps.merge_errors = 1;
1399         ps.pgroup = 1;
1400         ps.searchpath = 0;
1401
1402         ps.argv = argv;
1403
1404         /*
1405          * Fork.  Warning since we are doing vfork() instead of fork(),
1406          * do not allocate memory in the child process!
1407          */
1408         if ((ps.child_pid = vfork()) == -1) {
1409                 Punt("Cannot fork");
1410
1411         } else if (ps.child_pid == 0) {
1412                 /*
1413                  * Child
1414                  */
1415                 if (fifoFd >= 0)
1416                         close(fifoFd);
1417
1418                 ProcExec(&ps);
1419                 /* NOTREACHED */
1420
1421         } else {
1422                 /*
1423                  * Parent
1424                  */
1425                 job->pid = ps.child_pid;
1426
1427                 if (usePipes && (job->flags & JOB_FIRST)) {
1428                         /*
1429                          * The first time a job is run for a node, we set the
1430                          * current position in the buffer to the beginning and
1431                          * mark another stream to watch in the outputs mask.
1432                          */
1433 #ifdef USE_KQUEUE
1434                         struct kevent   kev[2];
1435 #endif
1436                         job->curPos = 0;
1437
1438 #if defined(USE_KQUEUE)
1439                         EV_SET(&kev[0], job->inPipe, EVFILT_READ, EV_ADD, 0, 0, job);
1440                         EV_SET(&kev[1], job->pid, EVFILT_PROC,
1441                             EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
1442                         if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1443                                 /*
1444                                  * kevent() will fail if the job is already
1445                                  * finished
1446                                  */
1447                                 if (errno != EINTR && errno != EBADF && errno != ESRCH)
1448                                         Punt("kevent: %s", strerror(errno));
1449                         }
1450 #else
1451                         FD_SET(job->inPipe, &outputs);
1452 #endif /* USE_KQUEUE */
1453                 }
1454
1455                 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1456                         fclose(job->cmdFILE);
1457                         job->cmdFILE = NULL;
1458                 }
1459
1460                 /*
1461                  * Now the job is actually running, add it to the table.
1462                  */
1463                 nJobs += 1;
1464                 TAILQ_INSERT_TAIL(&jobs, job, link);
1465                 if (nJobs == maxJobs) {
1466                         jobFull = TRUE;
1467                 }
1468         }
1469 }
1470
1471 /**
1472  * JobMakeArgv
1473  *      Create the argv needed to execute the shell for a given job.
1474  */
1475 static void
1476 JobMakeArgv(Job *job, char **argv)
1477 {
1478         int             argc;
1479         static char     args[10];       /* For merged arguments */
1480
1481         argv[0] = shellName;
1482         argc = 1;
1483
1484         if ((commandShell->exit && *commandShell->exit != '-') ||
1485             (commandShell->echo && *commandShell->echo != '-')) {
1486                 /*
1487                  * At least one of the flags doesn't have a minus before it, so
1488                  * merge them together. Have to do this because the *(&(@*#*&#$#
1489                  * Bourne shell thinks its second argument is a file to source.
1490                  * Grrrr. Note the ten-character limitation on the combined
1491                  * arguments.
1492                  */
1493                 sprintf(args, "-%s%s", (job->flags & JOB_IGNERR) ? "" :
1494                     commandShell->exit ? commandShell->exit : "",
1495                     (job->flags & JOB_SILENT) ? "" :
1496                     commandShell->echo ? commandShell->echo : "");
1497
1498                 if (args[1]) {
1499                         argv[argc] = args;
1500                         argc++;
1501                 }
1502         } else {
1503                 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1504                         argv[argc] = commandShell->exit;
1505                         argc++;
1506                 }
1507                 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1508                         argv[argc] = commandShell->echo;
1509                         argc++;
1510                 }
1511         }
1512         argv[argc] = NULL;
1513 }
1514
1515 /**
1516  * JobRestart
1517  *      Restart a job that stopped for some reason. The job must be neither
1518  *      on the jobs nor on the stoppedJobs list.
1519  *
1520  * Side Effects:
1521  *      jobFull will be set if the job couldn't be run.
1522  */
1523 static void
1524 JobRestart(Job *job)
1525 {
1526
1527         if (job->flags & JOB_RESTART) {
1528                 /*
1529                  * Set up the control arguments to the shell. This is based on
1530                  * the flags set earlier for this job. If the JOB_IGNERR flag
1531                  * is clear, the 'exit' flag of the commandShell is used to
1532                  * cause it to exit upon receiving an error. If the JOB_SILENT
1533                  * flag is clear, the 'echo' flag of the commandShell is used
1534                  * to get it to start echoing as soon as it starts
1535                  * processing commands.
1536                  */
1537                 char    *argv[4];
1538
1539                 JobMakeArgv(job, argv);
1540
1541                 DEBUGF(JOB, ("Restarting %s...", job->node->name));
1542                 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL)) {
1543                         /*
1544                          * Not allowed to run -- put it back on the hold
1545                          * queue and mark the table full
1546                          */
1547                         DEBUGF(JOB, ("holding\n"));
1548                         TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1549                         jobFull = TRUE;
1550                         DEBUGF(JOB, ("Job queue is full.\n"));
1551                         return;
1552                 } else {
1553                         /*
1554                          * Job may be run locally.
1555                          */
1556                         DEBUGF(JOB, ("running locally\n"));
1557                 }
1558                 JobExec(job, argv);
1559
1560         } else {
1561                 /*
1562                  * The job has stopped and needs to be restarted.
1563                  * Why it stopped, we don't know...
1564                  */
1565                 DEBUGF(JOB, ("Resuming %s...", job->node->name));
1566                 if ((nJobs < maxJobs || ((job->flags & JOB_SPECIAL) &&
1567                     maxJobs == 0)) && nJobs != maxJobs) {
1568                         /*
1569                          * If we haven't reached the concurrency limit already
1570                          * (or the job must be run and maxJobs is 0), it's ok
1571                          * to resume it.
1572                          */
1573                         Boolean error;
1574                         int status;
1575
1576                         error = (KILL(job->pid, SIGCONT) != 0);
1577
1578                         if (!error) {
1579                                 /*
1580                                  * Make sure the user knows we've continued
1581                                  * the beast and actually put the thing in the
1582                                  * job table.
1583                                  */
1584                                 job->flags |= JOB_CONTINUING;
1585                                 status = 0;
1586                                 W_SETTERMSIG(&status, SIGCONT);
1587                                 JobFinish(job, &status);
1588
1589                                 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1590                                 DEBUGF(JOB, ("done\n"));
1591                         } else {
1592                                 Error("couldn't resume %s: %s",
1593                                 job->node->name, strerror(errno));
1594                                 status = 0;
1595                                 W_SETEXITSTATUS(&status, 1);
1596                                 JobFinish(job, &status);
1597                         }
1598                 } else {
1599                         /*
1600                         * Job cannot be restarted. Mark the table as full and
1601                         * place the job back on the list of stopped jobs.
1602                         */
1603                         DEBUGF(JOB, ("table full\n"));
1604                         TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1605                         jobFull = TRUE;
1606                         DEBUGF(JOB, ("Job queue is full.\n"));
1607                 }
1608         }
1609 }
1610
1611 /**
1612  * JobStart
1613  *      Start a target-creation process going for the target described
1614  *      by the graph node gn.
1615  *
1616  * Results:
1617  *      JOB_ERROR if there was an error in the commands, JOB_FINISHED
1618  *      if there isn't actually anything left to do for the job and
1619  *      JOB_RUNNING if the job has been started.
1620  *
1621  * Side Effects:
1622  *      A new Job node is created and added to the list of running
1623  *      jobs. PMake is forked and a child shell created.
1624  */
1625 static int
1626 JobStart(GNode *gn, int flags, Job *previous)
1627 {
1628         Job     *job;           /* new job descriptor */
1629         char    *argv[4];       /* Argument vector to shell */
1630         Boolean cmdsOK;         /* true if the nodes commands were all right */
1631         Boolean noExec;         /* Set true if we decide not to run the job */
1632         int     tfd;            /* File descriptor for temp file */
1633         LstNode *ln;
1634         char    tfile[sizeof(TMPPAT)];
1635
1636         if (interrupted) {
1637                 JobPassSig(interrupted);
1638                 return (JOB_ERROR);
1639         }
1640         if (previous != NULL) {
1641                 previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1642                 job = previous;
1643         } else {
1644                 job = emalloc(sizeof(Job));
1645                 flags |= JOB_FIRST;
1646         }
1647
1648         job->node = gn;
1649         job->tailCmds = NULL;
1650
1651         /*
1652          * Set the initial value of the flags for this job based on the global
1653          * ones and the node's attributes... Any flags supplied by the caller
1654          * are also added to the field.
1655          */
1656         job->flags = 0;
1657         if (Targ_Ignore(gn)) {
1658                 job->flags |= JOB_IGNERR;
1659         }
1660         if (Targ_Silent(gn)) {
1661                 job->flags |= JOB_SILENT;
1662         }
1663         job->flags |= flags;
1664
1665         /*
1666          * Check the commands now so any attributes from .DEFAULT have a chance
1667          * to migrate to the node.
1668          */
1669         if (!compatMake && (job->flags & JOB_FIRST)) {
1670                 cmdsOK = Job_CheckCommands(gn, Error);
1671         } else {
1672                 cmdsOK = TRUE;
1673         }
1674
1675         /*
1676          * If the -n flag wasn't given, we open up OUR (not the child's)
1677          * temporary file to stuff commands in it. The thing is rd/wr so we
1678          * don't need to reopen it to feed it to the shell. If the -n flag
1679          * *was* given, we just set the file to be stdout. Cute, huh?
1680          */
1681         if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1682                 /*
1683                  * We're serious here, but if the commands were bogus, we're
1684                  * also dead...
1685                  */
1686                 if (!cmdsOK) {
1687                         DieHorribly();
1688                 }
1689
1690                 strcpy(tfile, TMPPAT);
1691                 if ((tfd = mkstemp(tfile)) == -1)
1692                         Punt("Cannot create temp file: %s", strerror(errno));
1693                 job->cmdFILE = fdopen(tfd, "w+");
1694                 eunlink(tfile);
1695                 if (job->cmdFILE == NULL) {
1696                         close(tfd);
1697                         Punt("Could not open %s", tfile);
1698                 }
1699                 fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1700                 /*
1701                  * Send the commands to the command file, flush all its
1702                  * buffers then rewind and remove the thing.
1703                  */
1704                 noExec = FALSE;
1705
1706                 /*
1707                  * Used to be backwards; replace when start doing multiple
1708                  * commands per shell.
1709                  */
1710                 if (compatMake) {
1711                         /*
1712                          * Be compatible: If this is the first time for this
1713                          * node, verify its commands are ok and open the
1714                          * commands list for sequential access by later
1715                          * invocations of JobStart. Once that is done, we take
1716                          * the next command off the list and print it to the
1717                          * command file. If the command was an ellipsis, note
1718                          * that there's nothing more to execute.
1719                          */
1720                         if (job->flags & JOB_FIRST)
1721                                 gn->compat_command = Lst_First(&gn->commands);
1722                         else
1723                                 gn->compat_command =
1724                                     Lst_Succ(gn->compat_command);
1725
1726                         if (gn->compat_command == NULL ||
1727                             JobPrintCommand(Lst_Datum(gn->compat_command), job))
1728                                 noExec = TRUE;
1729
1730                         if (noExec && !(job->flags & JOB_FIRST)) {
1731                                 /*
1732                                  * If we're not going to execute anything, the
1733                                  * job is done and we need to close down the
1734                                  * various file descriptors we've opened for
1735                                  * output, then call JobDoOutput to catch the
1736                                  * final characters or send the file to the
1737                                  * screen... Note that the i/o streams are only
1738                                  * open if this isn't the first job. Note also
1739                                  * that this could not be done in
1740                                  * Job_CatchChildren b/c it wasn't clear if
1741                                  * there were more commands to execute or not...
1742                                  */
1743                                 JobClose(job);
1744                         }
1745                 } else {
1746                         /*
1747                          * We can do all the commands at once. hooray for sanity
1748                          */
1749                         numCommands = 0;
1750                         LST_FOREACH(ln, &gn->commands) {
1751                                 if (JobPrintCommand(Lst_Datum(ln), job))
1752                                         break;
1753                         }
1754
1755                         /*
1756                          * If we didn't print out any commands to the shell
1757                          * script, there's not much point in executing the
1758                          * shell, is there?
1759                          */
1760                         if (numCommands == 0) {
1761                                 noExec = TRUE;
1762                         }
1763                 }
1764
1765         } else if (noExecute) {
1766                 /*
1767                  * Not executing anything -- just print all the commands to
1768                  * stdout in one fell swoop. This will still set up
1769                  * job->tailCmds correctly.
1770                  */
1771                 if (lastNode != gn) {
1772                         MESSAGE(stdout, gn);
1773                         lastNode = gn;
1774                 }
1775                 job->cmdFILE = stdout;
1776
1777                 /*
1778                  * Only print the commands if they're ok, but don't die if
1779                  * they're not -- just let the user know they're bad and keep
1780                  * going. It doesn't do any harm in this case and may do
1781                  * some good.
1782                  */
1783                 if (cmdsOK) {
1784                         LST_FOREACH(ln, &gn->commands) {
1785                                 if (JobPrintCommand(Lst_Datum(ln), job))
1786                                         break;
1787                         }
1788                 }
1789                 /*
1790                 * Don't execute the shell, thank you.
1791                 */
1792                 noExec = TRUE;
1793
1794         } else {
1795                 /*
1796                  * Just touch the target and note that no shell should be
1797                  * executed. Set cmdFILE to stdout to make life easier. Check
1798                  * the commands, too, but don't die if they're no good -- it
1799                  * does no harm to keep working up the graph.
1800                  */
1801                 job->cmdFILE = stdout;
1802                 Job_Touch(gn, job->flags & JOB_SILENT);
1803                 noExec = TRUE;
1804         }
1805
1806         /*
1807          * If we're not supposed to execute a shell, don't.
1808          */
1809         if (noExec) {
1810                 /*
1811                  * Unlink and close the command file if we opened one
1812                  */
1813                 if (job->cmdFILE != stdout) {
1814                         if (job->cmdFILE != NULL)
1815                                 fclose(job->cmdFILE);
1816                 } else {
1817                         fflush(stdout);
1818                 }
1819
1820                 /*
1821                  * We only want to work our way up the graph if we aren't here
1822                  * because the commands for the job were no good.
1823                 */
1824                 if (cmdsOK) {
1825                         if (aborting == 0) {
1826                                 for (ln = job->tailCmds; ln != NULL;
1827                                     ln = LST_NEXT(ln)) {
1828                                         Lst_AtEnd(&postCommands->commands,
1829                                             Buf_Peel(Var_Subst(Lst_Datum(ln),
1830                                             job->node, FALSE)));
1831                                 }
1832                                 job->node->made = MADE;
1833                                 Make_Update(job->node);
1834                         }
1835                         free(job);
1836                         return(JOB_FINISHED);
1837                 } else {
1838                         free(job);
1839                         return(JOB_ERROR);
1840                 }
1841         } else {
1842                 fflush(job->cmdFILE);
1843         }
1844
1845         /*
1846          * Set up the control arguments to the shell. This is based on the flags
1847          * set earlier for this job.
1848          */
1849         JobMakeArgv(job, argv);
1850
1851         /*
1852          * If we're using pipes to catch output, create the pipe by which we'll
1853          * get the shell's output. If we're using files, print out that we're
1854          * starting a job and then set up its temporary-file name.
1855          */
1856         if (!compatMake || (job->flags & JOB_FIRST)) {
1857                 if (usePipes) {
1858                         int fd[2];
1859
1860                         if (pipe(fd) == -1)
1861                                 Punt("Cannot create pipe: %s", strerror(errno));
1862                         job->inPipe = fd[0];
1863                         job->outPipe = fd[1];
1864                         fcntl(job->inPipe, F_SETFD, 1);
1865                         fcntl(job->outPipe, F_SETFD, 1);
1866                 } else {
1867                         fprintf(stdout, "Remaking `%s'\n", gn->name);
1868                         fflush(stdout);
1869                         strcpy(job->outFile, TMPPAT);
1870                         if ((job->outFd = mkstemp(job->outFile)) == -1)
1871                                 Punt("cannot create temp file: %s",
1872                                     strerror(errno));
1873                         fcntl(job->outFd, F_SETFD, 1);
1874                 }
1875         }
1876
1877         if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL) && maxJobs != 0) {
1878                 /*
1879                  * We've hit the limit of concurrency, so put the job on hold
1880                  * until some other job finishes. Note that the special jobs
1881                  * (.BEGIN, .INTERRUPT and .END) may be run even when the
1882                  * limit has been reached (e.g. when maxJobs == 0).
1883                  */
1884                 jobFull = TRUE;
1885
1886                 DEBUGF(JOB, ("Can only run job locally.\n"));
1887                 job->flags |= JOB_RESTART;
1888                 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1889         } else {
1890                 if (nJobs >= maxJobs) {
1891                         /*
1892                          * If we're running this job as a special case
1893                          * (see above), at least say the table is full.
1894                          */
1895                         jobFull = TRUE;
1896                         DEBUGF(JOB, ("Local job queue is full.\n"));
1897                 }
1898                 JobExec(job, argv);
1899         }
1900         return (JOB_RUNNING);
1901 }
1902
1903 static char *
1904 JobOutput(Job *job, char *cp, char *endp, int msg)
1905 {
1906         char *ecp;
1907
1908         if (commandShell->noPrint) {
1909                 ecp = strstr(cp, commandShell->noPrint);
1910                 while (ecp != NULL) {
1911                         if (cp != ecp) {
1912                                 *ecp = '\0';
1913                                 if (msg && job->node != lastNode) {
1914                                         MESSAGE(stdout, job->node);
1915                                         lastNode = job->node;
1916                                 }
1917                                 /*
1918                                  * The only way there wouldn't be a newline
1919                                  * after this line is if it were the last in
1920                                  * the buffer. However, since the non-printable
1921                                  * comes after it, there must be a newline, so
1922                                  * we don't print one.
1923                                  */
1924                                 fprintf(stdout, "%s", cp);
1925                                 fflush(stdout);
1926                         }
1927                         cp = ecp + strlen(commandShell->noPrint);
1928                         if (cp != endp) {
1929                                 /*
1930                                  * Still more to print, look again after
1931                                  * skipping the whitespace following the
1932                                  * non-printable command....
1933                                  */
1934                                 cp++;
1935                                 while (*cp == ' ' || *cp == '\t' ||
1936                                     *cp == '\n') {
1937                                         cp++;
1938                                 }
1939                                 ecp = strstr(cp, commandShell->noPrint);
1940                         } else {
1941                                 return (cp);
1942                         }
1943                 }
1944         }
1945         return (cp);
1946 }
1947
1948 /**
1949  * JobDoOutput
1950  *      This function is called at different times depending on
1951  *      whether the user has specified that output is to be collected
1952  *      via pipes or temporary files. In the former case, we are called
1953  *      whenever there is something to read on the pipe. We collect more
1954  *      output from the given job and store it in the job's outBuf. If
1955  *      this makes up a line, we print it tagged by the job's identifier,
1956  *      as necessary.
1957  *      If output has been collected in a temporary file, we open the
1958  *      file and read it line by line, transfering it to our own
1959  *      output channel until the file is empty. At which point we
1960  *      remove the temporary file.
1961  *      In both cases, however, we keep our figurative eye out for the
1962  *      'noPrint' line for the shell from which the output came. If
1963  *      we recognize a line, we don't print it. If the command is not
1964  *      alone on the line (the character after it is not \0 or \n), we
1965  *      do print whatever follows it.
1966  *
1967  * Side Effects:
1968  *      curPos may be shifted as may the contents of outBuf.
1969  */
1970 static void
1971 JobDoOutput(Job *job, Boolean finish)
1972 {
1973         Boolean gotNL = FALSE;  /* true if got a newline */
1974         Boolean fbuf;           /* true if our buffer filled up */
1975         int     nr;             /* number of bytes read */
1976         int     i;              /* auxiliary index into outBuf */
1977         int     max;            /* limit for i (end of current data) */
1978         int     nRead;          /* (Temporary) number of bytes read */
1979         FILE    *oFILE;         /* Stream pointer to shell's output file */
1980         char    inLine[132];
1981
1982         if (usePipes) {
1983                 /*
1984                  * Read as many bytes as will fit in the buffer.
1985                  */
1986   end_loop:
1987                 gotNL = FALSE;
1988                 fbuf = FALSE;
1989
1990                 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1991                     JOB_BUFSIZE - job->curPos);
1992                 /*
1993                  * Check for interrupt here too, because the above read may
1994                  * block when the child process is stopped. In this case the
1995                  * interrupt will unblock it (we don't use SA_RESTART).
1996                  */
1997                 if (interrupted)
1998                         JobPassSig(interrupted);
1999
2000                 if (nRead < 0) {
2001                         DEBUGF(JOB, ("JobDoOutput(piperead)"));
2002                         nr = 0;
2003                 } else {
2004                         nr = nRead;
2005                 }
2006
2007                 /*
2008                  * If we hit the end-of-file (the job is dead), we must flush
2009                  * its remaining output, so pretend we read a newline if
2010                  * there's any output remaining in the buffer.
2011                  * Also clear the 'finish' flag so we stop looping.
2012                  */
2013                 if (nr == 0 && job->curPos != 0) {
2014                         job->outBuf[job->curPos] = '\n';
2015                         nr = 1;
2016                         finish = FALSE;
2017                 } else if (nr == 0) {
2018                         finish = FALSE;
2019                 }
2020
2021                 /*
2022                  * Look for the last newline in the bytes we just got. If there
2023                  * is one, break out of the loop with 'i' as its index and
2024                  * gotNL set TRUE.
2025                 */
2026                 max = job->curPos + nr;
2027                 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
2028                         if (job->outBuf[i] == '\n') {
2029                                 gotNL = TRUE;
2030                                 break;
2031                         } else if (job->outBuf[i] == '\0') {
2032                                 /*
2033                                  * Why?
2034                                  */
2035                                 job->outBuf[i] = ' ';
2036                         }
2037                 }
2038
2039                 if (!gotNL) {
2040                         job->curPos += nr;
2041                         if (job->curPos == JOB_BUFSIZE) {
2042                                 /*
2043                                  * If we've run out of buffer space, we have
2044                                  * no choice but to print the stuff. sigh.
2045                                  */
2046                                 fbuf = TRUE;
2047                                 i = job->curPos;
2048                         }
2049                 }
2050                 if (gotNL || fbuf) {
2051                         /*
2052                          * Need to send the output to the screen. Null terminate
2053                          * it first, overwriting the newline character if there
2054                          * was one. So long as the line isn't one we should
2055                          * filter (according to the shell description), we print
2056                          * the line, preceded by a target banner if this target
2057                          * isn't the same as the one for which we last printed
2058                          * something. The rest of the data in the buffer are
2059                          * then shifted down to the start of the buffer and
2060                          * curPos is set accordingly.
2061                          */
2062                         job->outBuf[i] = '\0';
2063                         if (i >= job->curPos) {
2064                                 char *cp;
2065
2066                                 cp = JobOutput(job, job->outBuf,
2067                                     &job->outBuf[i], FALSE);
2068
2069                                 /*
2070                                  * There's still more in that buffer. This time,
2071                                  * though, we know there's no newline at the
2072                                  * end, so we add one of our own free will.
2073                                  */
2074                                 if (*cp != '\0') {
2075                                         if (job->node != lastNode) {
2076                                                 MESSAGE(stdout, job->node);
2077                                                 lastNode = job->node;
2078                                         }
2079                                         fprintf(stdout, "%s%s", cp,
2080                                             gotNL ? "\n" : "");
2081                                         fflush(stdout);
2082                                 }
2083                         }
2084                         if (i < max - 1) {
2085                                 /* shift the remaining characters down */
2086                                 memcpy(job->outBuf, &job->outBuf[i + 1],
2087                                     max - (i + 1));
2088                                 job->curPos = max - (i + 1);
2089
2090                         } else {
2091                                 /*
2092                                  * We have written everything out, so we just
2093                                  * start over from the start of the buffer.
2094                                  * No copying. No nothing.
2095                                  */
2096                                 job->curPos = 0;
2097                         }
2098                 }
2099                 if (finish) {
2100                         /*
2101                          * If the finish flag is true, we must loop until we hit
2102                          * end-of-file on the pipe. This is guaranteed to happen
2103                          * eventually since the other end of the pipe is now
2104                          * closed (we closed it explicitly and the child has
2105                          * exited). When we do get an EOF, finish will be set
2106                          * FALSE and we'll fall through and out.
2107                          */
2108                         goto end_loop;
2109                 }
2110
2111         } else {
2112                 /*
2113                  * We've been called to retrieve the output of the job from the
2114                  * temporary file where it's been squirreled away. This consists
2115                  * of opening the file, reading the output line by line, being
2116                  * sure not to print the noPrint line for the shell we used,
2117                  * then close and remove the temporary file. Very simple.
2118                  *
2119                  * Change to read in blocks and do FindSubString type things
2120                  * as for pipes? That would allow for "@echo -n..."
2121                  */
2122                 oFILE = fopen(job->outFile, "r");
2123                 if (oFILE != NULL) {
2124                         fprintf(stdout, "Results of making %s:\n",
2125                             job->node->name);
2126                         fflush(stdout);
2127
2128                         while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2129                                 char    *cp, *endp, *oendp;
2130
2131                                 cp = inLine;
2132                                 oendp = endp = inLine + strlen(inLine);
2133                                 if (endp[-1] == '\n') {
2134                                         *--endp = '\0';
2135                                 }
2136                                 cp = JobOutput(job, inLine, endp, FALSE);
2137
2138                                 /*
2139                                  * There's still more in that buffer. This time,
2140                                  * though, we know there's no newline at the
2141                                  * end, so we add one of our own free will.
2142                                  */
2143                                 fprintf(stdout, "%s", cp);
2144                                 fflush(stdout);
2145                                 if (endp != oendp) {
2146                                         fprintf(stdout, "\n");
2147                                         fflush(stdout);
2148                                 }
2149                         }
2150                         fclose(oFILE);
2151                         eunlink(job->outFile);
2152                 }
2153         }
2154 }
2155
2156 /**
2157  * Job_CatchChildren
2158  *      Handle the exit of a child. Called from Make_Make.
2159  *
2160  * Side Effects:
2161  *      The job descriptor is removed from the list of children.
2162  *
2163  * Notes:
2164  *      We do waits, blocking or not, according to the wisdom of our
2165  *      caller, until there are no more children to report. For each
2166  *      job, call JobFinish to finish things off. This will take care of
2167  *      putting jobs on the stoppedJobs queue.
2168  */
2169 void
2170 Job_CatchChildren(Boolean block)
2171 {
2172         pid_t   pid;    /* pid of dead child */
2173         Job     *job;   /* job descriptor for dead child */
2174         int     status; /* Exit/termination status */
2175
2176         /*
2177          * Don't even bother if we know there's no one around.
2178          */
2179         if (nJobs == 0) {
2180                 return;
2181         }
2182
2183         for (;;) {
2184                 pid = waitpid((pid_t)-1, &status,
2185                     (block ? 0 : WNOHANG) | WUNTRACED);
2186                 if (pid <= 0)
2187                         break;
2188
2189                 DEBUGF(JOB, ("Process %jd exited or stopped.\n",
2190                     (intmax_t)pid));
2191
2192                 TAILQ_FOREACH(job, &jobs, link) {
2193                         if (job->pid == pid)
2194                                 break;
2195                 }
2196
2197                 if (job == NULL) {
2198                         if (WIFSIGNALED(status) &&
2199                             (WTERMSIG(status) == SIGCONT)) {
2200                                 TAILQ_FOREACH(job, &jobs, link) {
2201                                         if (job->pid == pid)
2202                                                 break;
2203                                 }
2204                                 if (job == NULL) {
2205                                         Error("Resumed child (%jd) "
2206                                             "not in table", (intmax_t)pid);
2207                                         continue;
2208                                 }
2209                                 TAILQ_REMOVE(&stoppedJobs, job, link);
2210                         } else {
2211                                 Error("Child (%jd) not in table?",
2212                                     (intmax_t)pid);
2213                                 continue;
2214                         }
2215                 } else {
2216                         TAILQ_REMOVE(&jobs, job, link);
2217                         nJobs -= 1;
2218                         if (fifoFd >= 0 && maxJobs > 1) {
2219                                 write(fifoFd, "+", 1);
2220                                 maxJobs--;
2221                                 if (nJobs >= maxJobs)
2222                                         jobFull = TRUE;
2223                                 else
2224                                         jobFull = FALSE;
2225                         } else {
2226                                 DEBUGF(JOB, ("Job queue is no longer full.\n"));
2227                                 jobFull = FALSE;
2228                         }
2229                 }
2230
2231                 JobFinish(job, &status);
2232         }
2233         if (interrupted)
2234                 JobPassSig(interrupted);
2235 }
2236
2237 /**
2238  * Job_CatchOutput
2239  *      Catch the output from our children, if we're using
2240  *      pipes do so. Otherwise just block time until we get a
2241  *      signal(most likely a SIGCHLD) since there's no point in
2242  *      just spinning when there's nothing to do and the reaping
2243  *      of a child can wait for a while.
2244  *
2245  * Side Effects:
2246  *      Output is read from pipes if we're piping.
2247  * -----------------------------------------------------------------------
2248  */
2249 void
2250 #ifdef USE_KQUEUE
2251 Job_CatchOutput(int flag __unused)
2252 #else
2253 Job_CatchOutput(int flag)
2254 #endif
2255 {
2256         int             nfds;
2257 #ifdef USE_KQUEUE
2258 #define KEV_SIZE        4
2259         struct kevent   kev[KEV_SIZE];
2260         int             i;
2261 #else
2262         struct timeval  timeout;
2263         fd_set          readfds;
2264         Job             *job;
2265 #endif
2266
2267         fflush(stdout);
2268
2269         if (usePipes) {
2270 #ifdef USE_KQUEUE
2271                 if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
2272                         if (errno != EINTR)
2273                                 Punt("kevent: %s", strerror(errno));
2274                         if (interrupted)
2275                                 JobPassSig(interrupted);
2276                 } else {
2277                         for (i = 0; i < nfds; i++) {
2278                                 if (kev[i].flags & EV_ERROR) {
2279                                         warnc(kev[i].data, "kevent");
2280                                         continue;
2281                                 }
2282                                 switch (kev[i].filter) {
2283                                   case EVFILT_READ:
2284                                         JobDoOutput(kev[i].udata, FALSE);
2285                                         break;
2286                                   case EVFILT_PROC:
2287                                         /*
2288                                          * Just wake up and let
2289                                          * Job_CatchChildren() collect the
2290                                          * terminated job.
2291                                          */
2292                                         break;
2293                                 }
2294                         }
2295                 }
2296 #else
2297                 readfds = outputs;
2298                 timeout.tv_sec = SEL_SEC;
2299                 timeout.tv_usec = SEL_USEC;
2300                 if (flag && jobFull && fifoFd >= 0)
2301                         FD_SET(fifoFd, &readfds);
2302
2303                 nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
2304                     (fd_set *)NULL, &timeout);
2305                 if (nfds <= 0) {
2306                         if (interrupted)
2307                                 JobPassSig(interrupted);
2308                         return;
2309                 }
2310                 if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2311                         if (--nfds <= 0)
2312                                 return;
2313                 }
2314                 job = TAILQ_FIRST(&jobs);
2315                 while (nfds != 0 && job != NULL) {
2316                         if (FD_ISSET(job->inPipe, &readfds)) {
2317                                 JobDoOutput(job, FALSE);
2318                                 nfds--;
2319                         }
2320                         job = TAILQ_NEXT(job, link);
2321                 }
2322 #endif /* !USE_KQUEUE */
2323         }
2324 }
2325
2326 /**
2327  * Job_Make
2328  *      Start the creation of a target. Basically a front-end for
2329  *      JobStart used by the Make module.
2330  *
2331  * Side Effects:
2332  *      Another job is started.
2333  */
2334 void
2335 Job_Make(GNode *gn)
2336 {
2337
2338         JobStart(gn, 0, NULL);
2339 }
2340
2341 /**
2342  * JobCopyShell
2343  *      Make a new copy of the shell structure including a copy of the strings
2344  *      in it. This also defaults some fields in case they are NULL.
2345  *
2346  * Returns:
2347  *      The function returns a pointer to the new shell structure.
2348  */
2349 static struct Shell *
2350 JobCopyShell(const struct Shell *osh)
2351 {
2352         struct Shell *nsh;
2353
2354         nsh = emalloc(sizeof(*nsh));
2355         nsh->name = estrdup(osh->name);
2356
2357         if (osh->echoOff != NULL)
2358                 nsh->echoOff = estrdup(osh->echoOff);
2359         else
2360                 nsh->echoOff = NULL;
2361         if (osh->echoOn != NULL)
2362                 nsh->echoOn = estrdup(osh->echoOn);
2363         else
2364                 nsh->echoOn = NULL;
2365         nsh->hasEchoCtl = osh->hasEchoCtl;
2366
2367         if (osh->noPrint != NULL)
2368                 nsh->noPrint = estrdup(osh->noPrint);
2369         else
2370                 nsh->noPrint = NULL;
2371
2372         nsh->hasErrCtl = osh->hasErrCtl;
2373         if (osh->errCheck == NULL)
2374                 nsh->errCheck = estrdup("");
2375         else
2376                 nsh->errCheck = estrdup(osh->errCheck);
2377         if (osh->ignErr == NULL)
2378                 nsh->ignErr = estrdup("%s");
2379         else
2380                 nsh->ignErr = estrdup(osh->ignErr);
2381
2382         if (osh->echo == NULL)
2383                 nsh->echo = estrdup("");
2384         else
2385                 nsh->echo = estrdup(osh->echo);
2386
2387         if (osh->exit == NULL)
2388                 nsh->exit = estrdup("");
2389         else
2390                 nsh->exit = estrdup(osh->exit);
2391
2392         return (nsh);
2393 }
2394
2395 /**
2396  * JobFreeShell
2397  *      Free a shell structure and all associated strings.
2398  */
2399 static void
2400 JobFreeShell(struct Shell *sh)
2401 {
2402
2403         if (sh != NULL) {
2404                 free(sh->name);
2405                 free(sh->echoOff);
2406                 free(sh->echoOn);
2407                 free(sh->noPrint);
2408                 free(sh->errCheck);
2409                 free(sh->ignErr);
2410                 free(sh->echo);
2411                 free(sh->exit);
2412                 free(sh);
2413         }
2414 }
2415
2416 void
2417 Shell_Init(void)
2418 {
2419
2420         if (commandShell == NULL)
2421                 commandShell = JobMatchShell(shells[DEFSHELL].name);
2422
2423         if (shellPath == NULL) {
2424                 /*
2425                  * The user didn't specify a shell to use, so we are using the
2426                  * default one... Both the absolute path and the last component
2427                  * must be set. The last component is taken from the 'name'
2428                  * field of the default shell description pointed-to by
2429                  * commandShell. All default shells are located in
2430                  * PATH_DEFSHELLDIR.
2431                  */
2432                 shellName = commandShell->name;
2433                 shellPath = str_concat(PATH_DEFSHELLDIR, shellName,
2434                     STR_ADDSLASH);
2435         }
2436 }
2437
2438 /**
2439  * Job_Init
2440  *      Initialize the process module, given a maximum number of jobs.
2441  *
2442  * Side Effects:
2443  *      lists and counters are initialized
2444  */
2445 void
2446 Job_Init(int maxproc)
2447 {
2448         GNode           *begin; /* node for commands to do at the very start */
2449         const char      *env;
2450         struct sigaction sa;
2451
2452         fifoFd = -1;
2453         env = getenv("MAKE_JOBS_FIFO");
2454
2455         if (env == NULL && maxproc > 1) {
2456                 /*
2457                  * We did not find the environment variable so we are the
2458                  * leader. Create the fifo, open it, write one char per
2459                  * allowed job into the pipe.
2460                  */
2461                 mktemp(fifoName);
2462                 if (!mkfifo(fifoName, 0600)) {
2463                         fifoFd = open(fifoName, O_RDWR | O_NONBLOCK, 0);
2464                         if (fifoFd >= 0) {
2465                                 fifoMaster = 1;
2466                                 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2467                                 env = fifoName;
2468                                 setenv("MAKE_JOBS_FIFO", env, 1);
2469                                 while (maxproc-- > 0) {
2470                                         write(fifoFd, "+", 1);
2471                                 }
2472                                 /* The master make does not get a magic token */
2473                                 jobFull = TRUE;
2474                                 maxJobs = 0;
2475                         } else {
2476                                 unlink(fifoName);
2477                                 env = NULL;
2478                         }
2479                 }
2480
2481         } else if (env != NULL) {
2482                 /*
2483                  * We had the environment variable so we are a slave.
2484                  * Open fifo and give ourselves a magic token which represents
2485                  * the token our parent make has grabbed to start his make
2486                  * process. Otherwise the sub-makes would gobble up tokens and
2487                  * the proper number of tokens to specify to -j would depend
2488                  * on the depth of the tree and the order of execution.
2489                  */
2490                 fifoFd = open(env, O_RDWR, 0);
2491                 if (fifoFd >= 0) {
2492                         fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2493                         maxJobs = 1;
2494                         jobFull = FALSE;
2495                 }
2496         }
2497         if (fifoFd <= 0) {
2498                 maxJobs = maxproc;
2499                 jobFull = FALSE;
2500         } else {
2501         }
2502         nJobs = 0;
2503
2504         aborting = 0;
2505         errors = 0;
2506
2507         lastNode = NULL;
2508
2509         if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2510                 /*
2511                  * If only one job can run at a time, there's no need for a
2512                  * banner, no is there?
2513                  */
2514                 targFmt = "";
2515         } else {
2516                 targFmt = TARG_FMT;
2517         }
2518
2519         Shell_Init();
2520
2521         /*
2522          * Catch the four signals that POSIX specifies if they aren't ignored.
2523          * JobCatchSignal will just set global variables and hope someone
2524          * else is going to handle the interrupt.
2525          */
2526         sa.sa_handler = JobCatchSig;
2527         sigemptyset(&sa.sa_mask);
2528         sa.sa_flags = 0;
2529
2530         if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2531                 sigaction(SIGINT, &sa, NULL);
2532         }
2533         if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2534                 sigaction(SIGHUP, &sa, NULL);
2535         }
2536         if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2537                 sigaction(SIGQUIT, &sa, NULL);
2538         }
2539         if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2540                 sigaction(SIGTERM, &sa, NULL);
2541         }
2542         /*
2543          * There are additional signals that need to be caught and passed if
2544          * either the export system wants to be told directly of signals or if
2545          * we're giving each job its own process group (since then it won't get
2546          * signals from the terminal driver as we own the terminal)
2547          */
2548 #if defined(USE_PGRP)
2549         if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2550                 sigaction(SIGTSTP, &sa, NULL);
2551         }
2552         if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2553                 sigaction(SIGTTOU, &sa, NULL);
2554         }
2555         if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2556                 sigaction(SIGTTIN, &sa, NULL);
2557         }
2558         if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2559                 sigaction(SIGWINCH, &sa, NULL);
2560         }
2561 #endif
2562
2563 #ifdef USE_KQUEUE
2564         if ((kqfd = kqueue()) == -1) {
2565                 Punt("kqueue: %s", strerror(errno));
2566         }
2567 #endif
2568
2569         begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2570
2571         if (begin != NULL) {
2572                 JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2573                 while (nJobs) {
2574                         Job_CatchOutput(0);
2575                         Job_CatchChildren(!usePipes);
2576                 }
2577         }
2578         postCommands = Targ_FindNode(".END", TARG_CREATE);
2579 }
2580
2581 /**
2582  * Job_Full
2583  *      See if the job table is full. It is considered full if it is OR
2584  *      if we are in the process of aborting OR if we have
2585  *      reached/exceeded our local quota. This prevents any more jobs
2586  *      from starting up.
2587  *
2588  * Results:
2589  *      TRUE if the job table is full, FALSE otherwise
2590  */
2591 Boolean
2592 Job_Full(void)
2593 {
2594         char c;
2595         int i;
2596
2597         if (aborting)
2598                 return (aborting);
2599         if (fifoFd >= 0 && jobFull) {
2600                 i = read(fifoFd, &c, 1);
2601                 if (i > 0) {
2602                         maxJobs++;
2603                         jobFull = FALSE;
2604                 }
2605         }
2606         return (jobFull);
2607 }
2608
2609 /**
2610  * Job_Empty
2611  *      See if the job table is empty.  Because the local concurrency may
2612  *      be set to 0, it is possible for the job table to become empty,
2613  *      while the list of stoppedJobs remains non-empty. In such a case,
2614  *      we want to restart as many jobs as we can.
2615  *
2616  * Results:
2617  *      TRUE if it is. FALSE if it ain't.
2618  */
2619 Boolean
2620 Job_Empty(void)
2621 {
2622         if (nJobs == 0) {
2623                 if (!TAILQ_EMPTY(&stoppedJobs) && !aborting) {
2624                         /*
2625                          * The job table is obviously not full if it has no
2626                          * jobs in it...Try and restart the stopped jobs.
2627                          */
2628                         jobFull = FALSE;
2629                         JobRestartJobs();
2630                         return (FALSE);
2631                 } else {
2632                         return (TRUE);
2633                 }
2634         } else {
2635                 return (FALSE);
2636         }
2637 }
2638
2639 /**
2640  * JobMatchShell
2641  *      Find a matching shell in 'shells' given its final component.
2642  *
2643  * Results:
2644  *      A pointer to a freshly allocated Shell structure with a copy
2645  *      of the static structure or NULL if no shell with the given name
2646  *      is found.
2647  */
2648 static struct Shell *
2649 JobMatchShell(const char *name)
2650 {
2651         const struct CShell     *sh;          /* Pointer into shells table */
2652         struct Shell            *nsh;
2653
2654         for (sh = shells; sh < shells + __arysize(shells); sh++)
2655                 if (strcmp(sh->name, name) == 0)
2656                         break;
2657
2658         if (sh == shells + __arysize(shells))
2659                 return (NULL);
2660
2661         /* make a copy */
2662         nsh = emalloc(sizeof(*nsh));
2663
2664         nsh->name = estrdup(sh->name);
2665         nsh->echoOff = estrdup(sh->echoOff);
2666         nsh->echoOn = estrdup(sh->echoOn);
2667         nsh->hasEchoCtl = sh->hasEchoCtl;
2668         nsh->noPrint = estrdup(sh->noPrint);
2669         nsh->hasErrCtl = sh->hasErrCtl;
2670         nsh->errCheck = estrdup(sh->errCheck);
2671         nsh->ignErr = estrdup(sh->ignErr);
2672         nsh->echo = estrdup(sh->echo);
2673         nsh->exit = estrdup(sh->exit);
2674
2675         return (nsh);
2676 }
2677
2678 /**
2679  * Job_ParseShell
2680  *      Parse a shell specification and set up commandShell, shellPath
2681  *      and shellName appropriately.
2682  *
2683  * Results:
2684  *      FAILURE if the specification was incorrect.
2685  *
2686  * Side Effects:
2687  *      commandShell points to a Shell structure (either predefined or
2688  *      created from the shell spec), shellPath is the full path of the
2689  *      shell described by commandShell, while shellName is just the
2690  *      final component of shellPath.
2691  *
2692  * Notes:
2693  *      A shell specification consists of a .SHELL target, with dependency
2694  *      operator, followed by a series of blank-separated words. Double
2695  *      quotes can be used to use blanks in words. A backslash escapes
2696  *      anything (most notably a double-quote and a space) and
2697  *      provides the functionality it does in C. Each word consists of
2698  *      keyword and value separated by an equal sign. There should be no
2699  *      unnecessary spaces in the word. The keywords are as follows:
2700  *          name            Name of shell.
2701  *          path            Location of shell. Overrides "name" if given
2702  *          quiet           Command to turn off echoing.
2703  *          echo            Command to turn echoing on
2704  *          filter          Result of turning off echoing that shouldn't be
2705  *                          printed.
2706  *          echoFlag        Flag to turn echoing on at the start
2707  *          errFlag         Flag to turn error checking on at the start
2708  *          hasErrCtl       True if shell has error checking control
2709  *          check           Command to turn on error checking if hasErrCtl
2710  *                          is TRUE or template of command to echo a command
2711  *                          for which error checking is off if hasErrCtl is
2712  *                          FALSE.
2713  *          ignore          Command to turn off error checking if hasErrCtl
2714  *                          is TRUE or template of command to execute a
2715  *                          command so as to ignore any errors it returns if
2716  *                          hasErrCtl is FALSE.
2717  */
2718 ReturnStatus
2719 Job_ParseShell(char *line)
2720 {
2721         char    **words;
2722         int     wordCount;
2723         char    **argv;
2724         int     argc;
2725         char    *path;
2726         char    *eq;
2727         Boolean fullSpec = FALSE;
2728         struct Shell    newShell;
2729         struct Shell    *sh;
2730
2731         while (isspace((unsigned char)*line)) {
2732                 line++;
2733         }
2734         words = brk_string(line, &wordCount, TRUE);
2735
2736         memset(&newShell, 0, sizeof(newShell));
2737         path = NULL;
2738
2739         /*
2740          * Parse the specification by keyword but skip the first word - it
2741          * is not set by brk_string.
2742          */
2743         wordCount--;
2744         words++;
2745
2746         for (argc = wordCount, argv = words; argc != 0; argc--, argv++) {
2747                 /*
2748                  * Split keyword and value
2749                  */
2750                 if ((eq = strchr(*argv, '=')) == NULL) {
2751                         Parse_Error(PARSE_FATAL, "missing '=' in shell "
2752                             "specification keyword '%s'", *argv);
2753                         return (FAILURE);
2754                 }
2755                 *eq++ = '\0';
2756
2757                 if (strcmp(*argv, "path") == 0) {
2758                         path = eq;
2759                 } else if (strcmp(*argv, "name") == 0) {
2760                         newShell.name = eq;
2761                 } else if (strcmp(*argv, "quiet") == 0) {
2762                         newShell.echoOff = eq;
2763                         fullSpec = TRUE;
2764                 } else if (strcmp(*argv, "echo") == 0) {
2765                         newShell.echoOn = eq;
2766                         fullSpec = TRUE;
2767                 } else if (strcmp(*argv, "filter") == 0) {
2768                         newShell.noPrint = eq;
2769                         fullSpec = TRUE;
2770                 } else if (strcmp(*argv, "echoFlag") == 0) {
2771                         newShell.echo = eq;
2772                         fullSpec = TRUE;
2773                 } else if (strcmp(*argv, "errFlag") == 0) {
2774                         newShell.exit = eq;
2775                         fullSpec = TRUE;
2776                 } else if (strcmp(*argv, "hasErrCtl") == 0) {
2777                         newShell.hasErrCtl = (*eq == 'Y' || *eq == 'y' ||
2778                             *eq == 'T' || *eq == 't');
2779                         fullSpec = TRUE;
2780                 } else if (strcmp(*argv, "check") == 0) {
2781                         newShell.errCheck = eq;
2782                         fullSpec = TRUE;
2783                 } else if (strcmp(*argv, "ignore") == 0) {
2784                         newShell.ignErr = eq;
2785                         fullSpec = TRUE;
2786                 } else {
2787                         Parse_Error(PARSE_FATAL, "unknown keyword in shell "
2788                             "specification '%s'", *argv);
2789                         return (FAILURE);
2790                 }
2791         }
2792
2793         /*
2794          * Some checks (could be more)
2795          */
2796         if (fullSpec) {
2797                 if ((newShell.echoOn != NULL) ^ (newShell.echoOff != NULL))
2798                         Parse_Error(PARSE_FATAL, "Shell must have either both "
2799                             "echoOff and echoOn or none of them");
2800
2801                 if (newShell.echoOn != NULL && newShell.echoOff)
2802                         newShell.hasEchoCtl = TRUE;
2803         }
2804
2805         if (path == NULL) {
2806                 /*
2807                  * If no path was given, the user wants one of the pre-defined
2808                  * shells, yes? So we find the one s/he wants with the help of
2809                  * JobMatchShell and set things up the right way. shellPath
2810                  * will be set up by Job_Init.
2811                  */
2812                 if (newShell.name == NULL) {
2813                         Parse_Error(PARSE_FATAL,
2814                             "Neither path nor name specified");
2815                         return (FAILURE);
2816                 }
2817                 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2818                         Parse_Error(PARSE_FATAL, "%s: no matching shell",
2819                             newShell.name);
2820                         return (FAILURE);
2821                 }
2822
2823         } else {
2824                 /*
2825                  * The user provided a path. If s/he gave nothing else
2826                  * (fullSpec is FALSE), try and find a matching shell in the
2827                  * ones we know of. Else we just take the specification at its
2828                  * word and copy it to a new location. In either case, we need
2829                  * to record the path the user gave for the shell.
2830                  */
2831                 free(shellPath);
2832                 shellPath = estrdup(path);
2833                 if (newShell.name == NULL) {
2834                         /* get the base name as the name */
2835                         path = strrchr(path, '/');
2836                         if (path == NULL) {
2837                                 path = shellPath;
2838                         } else {
2839                                 path += 1;
2840                         }
2841                         newShell.name = path;
2842                 }
2843
2844                 if (!fullSpec) {
2845                         if ((sh = JobMatchShell(newShell.name)) == NULL) {
2846                                 Parse_Error(PARSE_FATAL,
2847                                     "%s: no matching shell", newShell.name);
2848                                 return (FAILURE);
2849                         }
2850                 } else {
2851                         sh = JobCopyShell(&newShell);
2852                 }
2853         }
2854
2855         /* set the new shell */
2856         JobFreeShell(commandShell);
2857         commandShell = sh;
2858
2859         shellName = commandShell->name;
2860
2861         return (SUCCESS);
2862 }
2863
2864 /**
2865  * JobInterrupt
2866  *      Handle the receipt of an interrupt.
2867  *
2868  * Side Effects:
2869  *      All children are killed. Another job will be started if the
2870  *      .INTERRUPT target was given.
2871  */
2872 static void
2873 JobInterrupt(int runINTERRUPT, int signo)
2874 {
2875         Job     *job;           /* job descriptor in that element */
2876         GNode   *interrupt;     /* the node describing the .INTERRUPT target */
2877
2878         aborting = ABORT_INTERRUPT;
2879
2880         TAILQ_FOREACH(job, &jobs, link) {
2881                 if (!Targ_Precious(job->node)) {
2882                         char *file = (job->node->path == NULL ?
2883                             job->node->name : job->node->path);
2884
2885                         if (!noExecute && eunlink(file) != -1) {
2886                                 Error("*** %s removed", file);
2887                         }
2888                 }
2889                 if (job->pid) {
2890                         DEBUGF(JOB, ("JobInterrupt passing signal to child "
2891                             "%jd.\n", (intmax_t)job->pid));
2892                         KILL(job->pid, signo);
2893                 }
2894         }
2895
2896         if (runINTERRUPT && !touchFlag) {
2897                 /*
2898                  * clear the interrupted flag because we would get an
2899                  * infinite loop otherwise.
2900                  */
2901                 interrupted = 0;
2902
2903                 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2904                 if (interrupt != NULL) {
2905                         ignoreErrors = FALSE;
2906
2907                         JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
2908                         while (nJobs) {
2909                                 Job_CatchOutput(0);
2910                                 Job_CatchChildren(!usePipes);
2911                         }
2912                 }
2913         }
2914 }
2915
2916 /**
2917  * Job_Finish
2918  *      Do final processing such as the running of the commands
2919  *      attached to the .END target.
2920  *
2921  * Results:
2922  *      Number of errors reported.
2923  */
2924 int
2925 Job_Finish(void)
2926 {
2927
2928         if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
2929                 if (errors) {
2930                         Error("Errors reported so .END ignored");
2931                 } else {
2932                         JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
2933
2934                         while (nJobs) {
2935                                 Job_CatchOutput(0);
2936                                 Job_CatchChildren(!usePipes);
2937                         }
2938                 }
2939         }
2940         if (fifoFd >= 0) {
2941                 close(fifoFd);
2942                 fifoFd = -1;
2943                 if (fifoMaster)
2944                         unlink(fifoName);
2945         }
2946         return (errors);
2947 }
2948
2949 /**
2950  * Job_Wait
2951  *      Waits for all running jobs to finish and returns. Sets 'aborting'
2952  *      to ABORT_WAIT to prevent other jobs from starting.
2953  *
2954  * Side Effects:
2955  *      Currently running jobs finish.
2956  */
2957 void
2958 Job_Wait(void)
2959 {
2960
2961         aborting = ABORT_WAIT;
2962         while (nJobs != 0) {
2963                 Job_CatchOutput(0);
2964                 Job_CatchChildren(!usePipes);
2965         }
2966         aborting = 0;
2967 }
2968
2969 /**
2970  * Job_AbortAll
2971  *      Abort all currently running jobs without handling output or anything.
2972  *      This function is to be called only in the event of a major
2973  *      error. Most definitely NOT to be called from JobInterrupt.
2974  *
2975  * Side Effects:
2976  *      All children are killed, not just the firstborn
2977  */
2978 void
2979 Job_AbortAll(void)
2980 {
2981         Job     *job;   /* the job descriptor in that element */
2982         int     foo;
2983
2984         aborting = ABORT_ERROR;
2985
2986         if (nJobs) {
2987                 TAILQ_FOREACH(job, &jobs, link) {
2988                         /*
2989                          * kill the child process with increasingly drastic
2990                          * signals to make darn sure it's dead.
2991                          */
2992                         KILL(job->pid, SIGINT);
2993                         KILL(job->pid, SIGKILL);
2994                 }
2995         }
2996
2997         /*
2998          * Catch as many children as want to report in at first, then give up
2999          */
3000         while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
3001                 ;
3002 }
3003
3004 /**
3005  * JobRestartJobs
3006  *      Tries to restart stopped jobs if there are slots available.
3007  *      Note that this tries to restart them regardless of pending errors.
3008  *      It's not good to leave stopped jobs lying around!
3009  *
3010  * Side Effects:
3011  *      Resumes(and possibly migrates) jobs.
3012  */
3013 static void
3014 JobRestartJobs(void)
3015 {
3016         Job *job;
3017
3018         while (!jobFull && (job = TAILQ_FIRST(&stoppedJobs)) != NULL) {
3019                 DEBUGF(JOB, ("Job queue is not full. "
3020                     "Restarting a stopped job.\n"));
3021                 TAILQ_REMOVE(&stoppedJobs, job, link);
3022                 JobRestart(job);
3023         }
3024 }
3025
3026 /**
3027  * Cmd_Exec
3028  *      Execute the command in cmd, and return the output of that command
3029  *      in a string.
3030  *
3031  * Results:
3032  *      A string containing the output of the command, or the empty string
3033  *      If error is not NULL, it contains the reason for the command failure
3034  *      Any output sent to stderr in the child process is passed to stderr,
3035  *      and not captured in the string.
3036  *
3037  * Side Effects:
3038  *      The string must be freed by the caller.
3039  */
3040 Buffer *
3041 Cmd_Exec(const char *cmd, const char **error)
3042 {
3043         int     fds[2]; /* Pipe streams */
3044         int     status; /* command exit status */
3045         Buffer  *buf;   /* buffer to store the result */
3046         ssize_t rcnt;
3047         ProcStuff       ps;
3048
3049         *error = NULL;
3050         buf = Buf_Init(0);
3051
3052         if (shellPath == NULL)
3053                 Shell_Init();
3054         /*
3055          * Open a pipe for fetching its output
3056          */
3057         if (pipe(fds) == -1) {
3058                 *error = "Couldn't create pipe for \"%s\"";
3059                 return (buf);
3060         }
3061
3062         /* Set close-on-exec on read side of pipe. */
3063         fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC);
3064
3065         ps.in = STDIN_FILENO;
3066         ps.out = fds[1];
3067         ps.err = STDERR_FILENO;
3068
3069         ps.merge_errors = 0;
3070         ps.pgroup = 0;
3071         ps.searchpath = 0;
3072
3073         /* Set up arguments for shell */
3074         ps.argv = emalloc(4 * sizeof(char *));
3075         ps.argv[0] = strdup(shellName);
3076         ps.argv[1] = strdup("-c");
3077         ps.argv[2] = strdup(cmd);
3078         ps.argv[3] = NULL;
3079
3080         /*
3081          * Fork.  Warning since we are doing vfork() instead of fork(),
3082          * do not allocate memory in the child process!
3083          */
3084         if ((ps.child_pid = vfork()) == -1) {
3085                 *error = "Couldn't exec \"%s\"";
3086
3087         } else if (ps.child_pid == 0) {
3088                 /*
3089                  * Child
3090                  */
3091                 ProcExec(&ps);
3092                 /* NOTREACHED */
3093
3094         } else {
3095                 free(ps.argv[2]);
3096                 free(ps.argv[1]);
3097                 free(ps.argv[0]);
3098                 free(ps.argv);
3099
3100                 close(fds[1]); /* No need for the writing half of the pipe. */
3101
3102                 do {
3103                         char    result[BUFSIZ];
3104
3105                         rcnt = read(fds[0], result, sizeof(result));
3106                         if (rcnt != -1)
3107                                 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
3108                 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
3109
3110                 if (rcnt == -1)
3111                         *error = "Error reading shell's output for \"%s\"";
3112
3113                 /*
3114                  * Close the input side of the pipe.
3115                  */
3116                 close(fds[0]);
3117
3118                 status = ProcWait(&ps);
3119                 if (status)
3120                         *error = "\"%s\" returned non-zero status";
3121
3122                 Buf_StripNewlines(buf);
3123
3124         }
3125         return (buf);
3126 }
3127
3128 static void
3129 CompatInit(void)
3130 {
3131         const char      *cp;    /* Pointer to string of shell meta-characters */
3132
3133         for (cp = "#=|^(){};&<>*?[]:$`\\\n"; *cp != '\0'; cp++) {
3134                 meta[(unsigned char)*cp] = 1;
3135         }
3136         /*
3137          * The null character serves as a sentinel in the string.
3138          */
3139         meta[0] = 1;
3140 }
3141
3142 /*
3143  * Interrupt handler - set flag and defer handling to the main code
3144  */
3145 static void
3146 CompatCatchSig(int signo)
3147 {
3148
3149         interrupted = signo;
3150 }
3151
3152 /*-
3153  *-----------------------------------------------------------------------
3154  * CompatInterrupt --
3155  *      Interrupt the creation of the current target and remove it if
3156  *      it ain't precious.
3157  *
3158  * Results:
3159  *      None.
3160  *
3161  * Side Effects:
3162  *      The target is removed and the process exits. If .INTERRUPT exists,
3163  *      its commands are run first WITH INTERRUPTS IGNORED..
3164  *
3165  *-----------------------------------------------------------------------
3166  */
3167 static void
3168 CompatInterrupt(int signo)
3169 {
3170         GNode           *gn;
3171         sigset_t        nmask, omask;
3172         LstNode         *ln;
3173
3174         sigemptyset(&nmask);
3175         sigaddset(&nmask, SIGINT);
3176         sigaddset(&nmask, SIGTERM);
3177         sigaddset(&nmask, SIGHUP);
3178         sigaddset(&nmask, SIGQUIT);
3179         sigprocmask(SIG_SETMASK, &nmask, &omask);
3180
3181         /* prevent recursion in evaluation of .INTERRUPT */
3182         interrupted = 0;
3183
3184         if (curTarg != NULL && !Targ_Precious(curTarg)) {
3185                 char      *p1;
3186                 char      *file = Var_Value(TARGET, curTarg, &p1);
3187
3188                 if (!noExecute && eunlink(file) != -1) {
3189                         printf("*** %s removed\n", file);
3190                 }
3191                 free(p1);
3192         }
3193
3194         /*
3195          * Run .INTERRUPT only if hit with interrupt signal
3196          */
3197         if (signo == SIGINT) {
3198                 gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
3199                 if (gn != NULL) {
3200                         LST_FOREACH(ln, &gn->commands) {
3201                                 if (Compat_RunCommand(Lst_Datum(ln), gn))
3202                                         break;
3203                         }
3204                 }
3205         }
3206
3207         sigprocmask(SIG_SETMASK, &omask, NULL);
3208
3209         if (signo == SIGQUIT)
3210                 exit(signo);
3211         signal(signo, SIG_DFL);
3212         kill(getpid(), signo);
3213 }
3214
3215 /*-
3216  *-----------------------------------------------------------------------
3217  * Compat_RunCommand --
3218  *      Execute the next command for a target. If the command returns an
3219  *      error, the node's made field is set to ERROR and creation stops.
3220  *      The node from which the command came is also given.
3221  *
3222  * Results:
3223  *      0 if the command succeeded, 1 if an error occurred.
3224  *
3225  * Side Effects:
3226  *      The node's 'made' field may be set to ERROR.
3227  *
3228  *-----------------------------------------------------------------------
3229  */
3230 int
3231 Compat_RunCommand(char *cmd, GNode *gn)
3232 {
3233         char    *cmdStart;      /* Start of expanded command */
3234         char    *cp;
3235         Boolean silent;         /* Don't print command */
3236         Boolean doit;           /* Execute even in -n */
3237         Boolean errCheck;       /* Check errors */
3238         int     reason;         /* Reason for child's death */
3239         int     status;         /* Description of child's death */
3240         LstNode *cmdNode;       /* Node where current command is located */
3241         char    **av;           /* Argument vector for thing to exec */
3242         char    *cmd_save;      /* saved cmd */
3243         ProcStuff       ps;
3244
3245         silent = gn->type & OP_SILENT;
3246         errCheck = !(gn->type & OP_IGNORE);
3247         doit = FALSE;
3248
3249         cmdNode = Lst_Member(&gn->commands, cmd);
3250         cmdStart = Buf_Peel(Var_Subst(cmd, gn, FALSE));
3251
3252         /*
3253          * brk_string will return an argv with a NULL in av[0], thus causing
3254          * execvp() to choke and die horribly. Besides, how can we execute a
3255          * null command? In any case, we warn the user that the command
3256          * expanded to nothing (is this the right thing to do?).
3257          */
3258         if (*cmdStart == '\0') {
3259                 free(cmdStart);
3260                 Error("%s expands to empty string", cmd);
3261                 return (0);
3262         } else {
3263                 cmd = cmdStart;
3264         }
3265         Lst_Replace(cmdNode, cmdStart);
3266
3267         if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
3268                 Lst_AtEnd(&ENDNode->commands, cmdStart);
3269                 return (0);
3270         } else if (strcmp(cmdStart, "...") == 0) {
3271                 gn->type |= OP_SAVE_CMDS;
3272                 return (0);
3273         }
3274
3275         while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
3276                 switch (*cmd) {
3277
3278                   case '@':
3279                         silent = DEBUG(LOUD) ? FALSE : TRUE;
3280                         break;
3281
3282                   case '-':
3283                         errCheck = FALSE;
3284                         break;
3285
3286                 case '+':
3287                         doit = TRUE;
3288                         if (!meta[0])           /* we came here from jobs */
3289                                 CompatInit();
3290                         break;
3291                 }
3292                 cmd++;
3293         }
3294
3295         while (isspace((unsigned char)*cmd))
3296                 cmd++;
3297
3298         /*
3299          * Print the command before echoing if we're not supposed to be quiet
3300          * for this one. We also print the command if -n given, but not if '+'.
3301          */
3302         if (!silent || (noExecute && !doit)) {
3303                 printf("%s\n", cmd);
3304                 fflush(stdout);
3305         }
3306
3307         /*
3308          * If we're not supposed to execute any commands, this is as far as
3309          * we go...
3310          */
3311         if (!doit && noExecute) {
3312                 return (0);
3313         }
3314
3315         /*
3316          * Search for meta characters in the command. If there are no meta
3317          * characters, there's no need to execute a shell to execute the
3318          * command.
3319          */
3320         for (cp = cmd; !meta[(unsigned char)*cp]; cp++)
3321                 continue;
3322
3323         if (*cp != '\0') {
3324                 /*
3325                  * If *cp isn't the null character, we hit a "meta" character
3326                  * and need to pass the command off to the shell.
3327                  */
3328                 av = NULL;
3329
3330         } else {
3331                 const char **p;
3332                 const char *sh_builtin[] = {
3333                         "alias", "cd", "eval", "exec",
3334                         "exit", "read", "set", "ulimit",
3335                         "unalias", "umask", "unset", "wait",
3336                         ":", NULL
3337                 };
3338
3339                 /*
3340                  * Break the command into words to form an argument
3341                  * vector we can execute. brk_string sticks our name
3342                  * in av[0], so we have to skip over it...
3343                  */
3344                 av = brk_string(cmd, NULL, TRUE);
3345                 av += 1;
3346
3347                 for (p = sh_builtin; *p != 0; p++) {
3348                         if (strcmp(av[0], *p) == 0) {
3349                                 /*
3350                                  * This command must be passed by the shell
3351                                  * for other reasons.. or.. possibly not at
3352                                  * all.
3353                                  */
3354                                 av = NULL;
3355                                 break;
3356                         }
3357                 }
3358         }
3359
3360         ps.in = STDIN_FILENO;
3361         ps.out = STDOUT_FILENO;
3362         ps.err = STDERR_FILENO;
3363
3364         ps.merge_errors = 0;
3365         ps.pgroup = 0;
3366         ps.searchpath = 1;
3367
3368         if (av == NULL) {
3369                 /*
3370                  * We give the shell the -e flag as well as -c if it's
3371                  * supposed to exit when it hits an error.
3372                  */
3373                 ps.argv = emalloc(4 * sizeof(char *));
3374                 ps.argv[0] = strdup(shellName);
3375                 ps.argv[1] = strdup(errCheck ? "-ec" : "-c");
3376                 ps.argv[2] = strdup(cmd);
3377                 ps.argv[3] = NULL;
3378         } else {
3379                 ps.argv = av;
3380         }
3381
3382         /*
3383          * Fork and execute the single command. If the fork fails, we abort.
3384          * Warning since we are doing vfork() instead of fork(),
3385          * do not allocate memory in the child process!
3386          */
3387         if ((ps.child_pid = vfork()) == -1) {
3388                 Fatal("Could not fork");
3389
3390         } else if (ps.child_pid == 0) {
3391                 /*
3392                  * Child
3393                  */
3394                 ProcExec(&ps);
3395                 /* NOTREACHED */
3396
3397         } else {
3398                 if (av == NULL) {
3399                         free(ps.argv[2]);
3400                         free(ps.argv[1]);
3401                         free(ps.argv[0]);
3402                         free(ps.argv);
3403                 }
3404
3405                 /*
3406                  * we need to print out the command associated with this
3407                  * Gnode in Targ_PrintCmd from Targ_PrintGraph when debugging
3408                  * at level g2, in main(), Fatal() and DieHorribly(),
3409                  * therefore do not free it when debugging.
3410                  */
3411                 if (!DEBUG(GRAPH2)) {
3412                         free(cmdStart);
3413                         Lst_Replace(cmdNode, cmd_save);
3414                 }
3415
3416                 /*
3417                  * The child is off and running. Now all we can do is wait...
3418                  */
3419                 reason = ProcWait(&ps);
3420
3421                 if (interrupted)
3422                         CompatInterrupt(interrupted);
3423
3424                 /*
3425                  * Deocde and report the reason child exited, then
3426                  * indicate how we handled it.
3427                  */
3428                 if (WIFEXITED(reason)) {
3429                         status = WEXITSTATUS(reason);
3430                         if (status == 0) {
3431                                 return (0);
3432                         } else {
3433                                 printf("*** Error code %d", status);
3434                         }
3435                 } else if (WIFSTOPPED(reason)) {
3436                         status = WSTOPSIG(reason);
3437                 } else {
3438                         status = WTERMSIG(reason);
3439                         printf("*** Signal %d", status);
3440                 }
3441
3442                 if (errCheck) {
3443                         gn->made = ERROR;
3444                         if (keepgoing) {
3445                                 /*
3446                                  * Abort the current
3447                                  * target, but let
3448                                  * others continue.
3449                                  */
3450                                 printf(" (continuing)\n");
3451                         }
3452                         return (status);
3453                 } else {
3454                         /*
3455                          * Continue executing
3456                          * commands for this target.
3457                          * If we return 0, this will
3458                          * happen...
3459                          */
3460                         printf(" (ignored)\n");
3461                         return (0);
3462                 }
3463         }
3464 }
3465
3466 /*-
3467  *-----------------------------------------------------------------------
3468  * CompatMake --
3469  *      Make a target, given the parent, to abort if necessary.
3470  *
3471  * Side Effects:
3472  *      If an error is detected and not being ignored, the process exits.
3473  *
3474  *-----------------------------------------------------------------------
3475  */
3476 static int
3477 CompatMake(GNode *gn, GNode *pgn)
3478 {
3479         LstNode *ln;
3480
3481         if (gn->type & OP_USE) {
3482                 Make_HandleUse(gn, pgn);
3483
3484         } else if (gn->made == UNMADE) {
3485                 /*
3486                  * First mark ourselves to be made, then apply whatever
3487                  * transformations the suffix module thinks are necessary.
3488                  * Once that's done, we can descend and make all our children.
3489                  * If any of them has an error but the -k flag was given, our
3490                  * 'make' field will be set FALSE again. This is our signal to
3491                  * not attempt to do anything but abort our parent as well.
3492                  */
3493                 gn->make = TRUE;
3494                 gn->made = BEINGMADE;
3495                 Suff_FindDeps(gn);
3496                 LST_FOREACH(ln, &gn->children)
3497                         CompatMake(Lst_Datum(ln), gn);
3498                 if (!gn->make) {
3499                         gn->made = ABORTED;
3500                         pgn->make = FALSE;
3501                         return (0);
3502                 }
3503
3504                 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3505                         char *p1;
3506                         Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
3507                         free(p1);
3508                 }
3509
3510                 /*
3511                  * All the children were made ok. Now cmtime contains the
3512                  * modification time of the newest child, we need to find out
3513                  * if we exist and when we were modified last. The criteria for
3514                  * datedness are defined by the Make_OODate function.
3515                  */
3516                 DEBUGF(MAKE, ("Examining %s...", gn->name));
3517                 if (!Make_OODate(gn)) {
3518                         gn->made = UPTODATE;
3519                         DEBUGF(MAKE, ("up-to-date.\n"));
3520                         return (0);
3521                 } else {
3522                         DEBUGF(MAKE, ("out-of-date.\n"));
3523                 }
3524
3525                 /*
3526                  * If the user is just seeing if something is out-of-date,
3527                  * exit now to tell him/her "yes".
3528                  */
3529                 if (queryFlag) {
3530                         exit(1);
3531                 }
3532
3533                 /*
3534                  * We need to be re-made. We also have to make sure we've got
3535                  * a $? variable. To be nice, we also define the $> variable
3536                  * using Make_DoAllVar().
3537                  */
3538                 Make_DoAllVar(gn);
3539
3540                 /*
3541                  * Alter our type to tell if errors should be ignored or things
3542                  * should not be printed so Compat_RunCommand knows what to do.
3543                  */
3544                 if (Targ_Ignore(gn)) {
3545                         gn->type |= OP_IGNORE;
3546                 }
3547                 if (Targ_Silent(gn)) {
3548                         gn->type |= OP_SILENT;
3549                 }
3550
3551                 if (Job_CheckCommands(gn, Fatal)) {
3552                         /*
3553                          * Our commands are ok, but we still have to worry
3554                          * about the -t flag...
3555                          */
3556                         if (!touchFlag) {
3557                                 curTarg = gn;
3558                                 LST_FOREACH(ln, &gn->commands) {
3559                                         if (Compat_RunCommand(Lst_Datum(ln),
3560                                             gn))
3561                                                 break;
3562                                 }
3563                                 curTarg = NULL;
3564                         } else {
3565                                 Job_Touch(gn, gn->type & OP_SILENT);
3566                         }
3567                 } else {
3568                         gn->made = ERROR;
3569                 }
3570
3571                 if (gn->made != ERROR) {
3572                         /*
3573                          * If the node was made successfully, mark it so, update
3574                          * its modification time and timestamp all its parents.
3575                          * Note that for .ZEROTIME targets, the timestamping
3576                          * isn't done. This is to keep its state from affecting
3577                          * that of its parent.
3578                          */
3579                         gn->made = MADE;
3580 #ifndef RECHECK
3581                         /*
3582                          * We can't re-stat the thing, but we can at least take
3583                          * care of rules where a target depends on a source that
3584                          * actually creates the target, but only if it has
3585                          * changed, e.g.
3586                          *
3587                          * parse.h : parse.o
3588                          *
3589                          * parse.o : parse.y
3590                          *      yacc -d parse.y
3591                          *      cc -c y.tab.c
3592                          *      mv y.tab.o parse.o
3593                          *      cmp -s y.tab.h parse.h || mv y.tab.h parse.h
3594                          *
3595                          * In this case, if the definitions produced by yacc
3596                          * haven't changed from before, parse.h won't have been
3597                          * updated and gn->mtime will reflect the current
3598                          * modification time for parse.h. This is something of a
3599                          * kludge, I admit, but it's a useful one..
3600                          *
3601                          * XXX: People like to use a rule like
3602                          *
3603                          * FRC:
3604                          *
3605                          * To force things that depend on FRC to be made, so we
3606                          * have to check for gn->children being empty as well...
3607                          */
3608                         if (!Lst_IsEmpty(&gn->commands) ||
3609                             Lst_IsEmpty(&gn->children)) {
3610                                 gn->mtime = now;
3611                         }
3612 #else
3613                         /*
3614                          * This is what Make does and it's actually a good
3615                          * thing, as it allows rules like
3616                          *
3617                          *      cmp -s y.tab.h parse.h || cp y.tab.h parse.h
3618                          *
3619                          * to function as intended. Unfortunately, thanks to
3620                          * the stateless nature of NFS (and the speed of this
3621                          * program), there are times when the modification time
3622                          * of a file created on a remote machine will not be
3623                          * modified before the stat() implied by the Dir_MTime
3624                          * occurs, thus leading us to believe that the file
3625                          * is unchanged, wreaking havoc with files that depend
3626                          * on this one.
3627                          *
3628                          * I have decided it is better to make too much than to
3629                          * make too little, so this stuff is commented out
3630                          * unless you're sure it's ok.
3631                          * -- ardeb 1/12/88
3632                          */
3633                         if (noExecute || Dir_MTime(gn) == 0) {
3634                                 gn->mtime = now;
3635                         }
3636                         if (gn->cmtime > gn->mtime)
3637                                 gn->mtime = gn->cmtime;
3638                         DEBUGF(MAKE, ("update time: %s\n",
3639                             Targ_FmtTime(gn->mtime)));
3640 #endif
3641                         if (!(gn->type & OP_EXEC)) {
3642                                 pgn->childMade = TRUE;
3643                                 Make_TimeStamp(pgn, gn);
3644                         }
3645
3646                 } else if (keepgoing) {
3647                         pgn->make = FALSE;
3648
3649                 } else {
3650                         char *p1;
3651
3652                         printf("\n\nStop in %s.\n",
3653                             Var_Value(".CURDIR", gn, &p1));
3654                         free(p1);
3655                         exit(1);
3656                 }
3657         } else if (gn->made == ERROR) {
3658                 /*
3659                  * Already had an error when making this beastie. Tell the
3660                  * parent to abort.
3661                  */
3662                 pgn->make = FALSE;
3663         } else {
3664                 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3665                         char *p1;
3666                         Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
3667                         free(p1);
3668                 }
3669                 switch(gn->made) {
3670                   case BEINGMADE:
3671                         Error("Graph cycles through %s\n", gn->name);
3672                         gn->made = ERROR;
3673                         pgn->make = FALSE;
3674                         break;
3675                   case MADE:
3676                         if ((gn->type & OP_EXEC) == 0) {
3677                             pgn->childMade = TRUE;
3678                             Make_TimeStamp(pgn, gn);
3679                         }
3680                         break;
3681                   case UPTODATE:
3682                         if ((gn->type & OP_EXEC) == 0) {
3683                             Make_TimeStamp(pgn, gn);
3684                         }
3685                         break;
3686                   default:
3687                         break;
3688                 }
3689         }
3690
3691         return (0);
3692 }
3693
3694 /*-
3695  *-----------------------------------------------------------------------
3696  * Compat_Run --
3697  *      Start making again, given a list of target nodes.
3698  *
3699  * Results:
3700  *      None.
3701  *
3702  * Side Effects:
3703  *      Guess what?
3704  *
3705  *-----------------------------------------------------------------------
3706  */
3707 void
3708 Compat_Run(Lst *targs)
3709 {
3710         GNode   *gn = NULL;     /* Current root target */
3711         int     error_cnt;              /* Number of targets not remade due to errors */
3712         LstNode *ln;
3713
3714         CompatInit();
3715         Shell_Init();           /* Set up shell. */
3716
3717         if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
3718                 signal(SIGINT, CompatCatchSig);
3719         }
3720         if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
3721                 signal(SIGTERM, CompatCatchSig);
3722         }
3723         if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
3724                 signal(SIGHUP, CompatCatchSig);
3725         }
3726         if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
3727                 signal(SIGQUIT, CompatCatchSig);
3728         }
3729
3730         ENDNode = Targ_FindNode(".END", TARG_CREATE);
3731         /*
3732          * If the user has defined a .BEGIN target, execute the commands
3733          * attached to it.
3734         */
3735         if (!queryFlag) {
3736                 gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
3737                 if (gn != NULL) {
3738                         LST_FOREACH(ln, &gn->commands) {
3739                                 if (Compat_RunCommand(Lst_Datum(ln), gn))
3740                                         break;
3741                         }
3742                         if (gn->made == ERROR) {
3743                                 printf("\n\nStop.\n");
3744                                 exit(1);
3745                         }
3746                 }
3747         }
3748
3749         /*
3750          * For each entry in the list of targets to create, call CompatMake on
3751          * it to create the thing. CompatMake will leave the 'made' field of gn
3752          * in one of several states:
3753          *      UPTODATE  gn was already up-to-date
3754          *      MADE      gn was recreated successfully
3755          *      ERROR     An error occurred while gn was being created
3756          *      ABORTED   gn was not remade because one of its inferiors
3757          *                could not be made due to errors.
3758          */
3759         error_cnt = 0;
3760         while (!Lst_IsEmpty(targs)) {
3761                 gn = Lst_DeQueue(targs);
3762                 CompatMake(gn, gn);
3763
3764                 if (gn->made == UPTODATE) {
3765                         printf("`%s' is up to date.\n", gn->name);
3766                 } else if (gn->made == ABORTED) {
3767                         printf("`%s' not remade because of errors.\n",
3768                             gn->name);
3769                         error_cnt += 1;
3770                 }
3771         }
3772
3773         /*
3774          * If the user has defined a .END target, run its commands.
3775          */
3776         if (error_cnt == 0) {
3777                 LST_FOREACH(ln, &ENDNode->commands) {
3778                         if (Compat_RunCommand(Lst_Datum(ln), gn))
3779                                 break;
3780                 }
3781         }
3782 }