cleanup middle 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.83 2005/04/28 18:47:27 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 (WIFEXITED(*status)) {
1022                 if (done || DEBUG(JOB)) {
1023                         FILE   *out;
1024
1025                         if (compatMake &&
1026                             !usePipes &&
1027                             (job->flags & JOB_IGNERR)) {
1028                                 /*
1029                                  * If output is going to a file and this job
1030                                  * is ignoring errors, arrange to have the
1031                                  * exit status sent to the output file as
1032                                  * well.
1033                                  */
1034                                 out = fdopen(job->outFd, "w");
1035                                 if (out == NULL)
1036                                         Punt("Cannot fdopen");
1037                         } else {
1038                                 out = stdout;
1039                         }
1040
1041                         DEBUGF(JOB, ("Process %jd exited.\n",
1042                             (intmax_t)job->pid));
1043
1044                         if (WEXITSTATUS(*status) == 0) {
1045                                 if (DEBUG(JOB)) {
1046                                         if (usePipes && job->node != lastNode) {
1047                                                 MESSAGE(out, job->node);
1048                                                 lastNode = job->node;
1049                                         }
1050                                         fprintf(out,
1051                                             "*** Completed successfully\n");
1052                                 }
1053                         } else {
1054                                 if (usePipes && job->node != lastNode) {
1055                                         MESSAGE(out, job->node);
1056                                         lastNode = job->node;
1057                                 }
1058                                 fprintf(out, "*** Error code %d%s\n",
1059                                         WEXITSTATUS(*status),
1060                                         (job->flags & JOB_IGNERR) ?
1061                                         "(ignored)" : "");
1062
1063                                 if (job->flags & JOB_IGNERR) {
1064                                         *status = 0;
1065                                 }
1066                         }
1067
1068                         fflush(out);
1069                 }
1070         } else if (WIFSIGNALED(*status)) {
1071                 if (done || DEBUG(JOB) || (WTERMSIG(*status) == SIGCONT)) {
1072                         FILE   *out;
1073
1074                         if (compatMake &&
1075                             !usePipes &&
1076                             (job->flags & JOB_IGNERR)) {
1077                                 /*
1078                                  * If output is going to a file and this job
1079                                  * is ignoring errors, arrange to have the
1080                                  * exit status sent to the output file as
1081                                  * well.
1082                                  */
1083                                 out = fdopen(job->outFd, "w");
1084                                 if (out == NULL)
1085                                         Punt("Cannot fdopen");
1086                         } else {
1087                                 out = stdout;
1088                         }
1089
1090                         if (WTERMSIG(*status) == SIGCONT) {
1091                                 /*
1092                                  * If the beastie has continued, shift the
1093                                  * Job from the stopped list to the running
1094                                  * one (or re-stop it if concurrency is
1095                                  * exceeded) and go and get another child.
1096                                  */
1097                                 if (job->flags & (JOB_RESUME | JOB_RESTART)) {
1098                                         if (usePipes && job->node != lastNode) {
1099                                                 MESSAGE(out, job->node);
1100                                                 lastNode = job->node;
1101                                         }
1102                                         fprintf(out, "*** Continued\n");
1103                                 }
1104                                 if (!(job->flags & JOB_CONTINUING)) {
1105                                         DEBUGF(JOB, ("Warning: process %jd was not "
1106                                                      "continuing.\n", (intmax_t) job->pid));
1107 #ifdef notdef
1108                                         /*
1109                                          * We don't really want to restart a
1110                                          * job from scratch just because it
1111                                          * continued, especially not without
1112                                          * killing the continuing process!
1113                                          * That's why this is ifdef'ed out.
1114                                          * FD - 9/17/90
1115                                          */
1116                                         JobRestart(job);
1117 #endif
1118                                 }
1119                                 job->flags &= ~JOB_CONTINUING;
1120                                 TAILQ_INSERT_TAIL(&jobs, job, link);
1121                                 nJobs += 1;
1122                                 DEBUGF(JOB, ("Process %jd is continuing locally.\n",
1123                                              (intmax_t) job->pid));
1124                                 if (nJobs == maxJobs) {
1125                                         jobFull = TRUE;
1126                                         DEBUGF(JOB, ("Job queue is full.\n"));
1127                                 }
1128                                 fflush(out);
1129                                 return;
1130
1131                         } else {
1132                                 if (usePipes && job->node != lastNode) {
1133                                         MESSAGE(out, job->node);
1134                                         lastNode = job->node;
1135                                 }
1136                                 fprintf(out,
1137                                     "*** Signal %d\n", WTERMSIG(*status));
1138                                 fflush(out);
1139                         }
1140                 }
1141         } else {
1142                 /* STOPPED */
1143                 FILE   *out;
1144
1145                 if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
1146                         /*
1147                          * If output is going to a file and this job
1148                          * is ignoring errors, arrange to have the
1149                          * exit status sent to the output file as
1150                          * well.
1151                          */
1152                         out = fdopen(job->outFd, "w");
1153                         if (out == NULL)
1154                                 Punt("Cannot fdopen");
1155                 } else {
1156                         out = stdout;
1157                 }
1158
1159                 DEBUGF(JOB, ("Process %jd stopped.\n", (intmax_t) job->pid));
1160                 if (usePipes && job->node != lastNode) {
1161                         MESSAGE(out, job->node);
1162                         lastNode = job->node;
1163                 }
1164                 fprintf(out, "*** Stopped -- signal %d\n", WSTOPSIG(*status));
1165                 job->flags |= JOB_RESUME;
1166                 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1167                 fflush(out);
1168                 return;
1169         }
1170
1171         /*
1172          * Now handle the -B-mode stuff. If the beast still isn't finished,
1173          * try and restart the job on the next command. If JobStart says it's
1174          * ok, it's ok. If there's an error, this puppy is done.
1175          */
1176         if (compatMake && WIFEXITED(*status) &&
1177             Lst_Succ(job->node->compat_command) != NULL) {
1178                 switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
1179                   case JOB_RUNNING:
1180                         done = FALSE;
1181                         break;
1182                   case JOB_ERROR:
1183                         done = TRUE;
1184                         W_SETEXITSTATUS(status, 1);
1185                         break;
1186                   case JOB_FINISHED:
1187                         /*
1188                          * If we got back a JOB_FINISHED code, JobStart has
1189                          * already called Make_Update and freed the job
1190                          * descriptor. We set done to false here to avoid fake
1191                          * cycles and double frees. JobStart needs to do the
1192                          * update so we can proceed up the graph when given
1193                          * the -n flag..
1194                          */
1195                         done = FALSE;
1196                         break;
1197                   default:
1198                         break;
1199                 }
1200         } else {
1201                 done = TRUE;
1202         }
1203
1204         if (done && aborting != ABORT_ERROR &&
1205             aborting != ABORT_INTERRUPT && *status == 0) {
1206                 /*
1207                  * As long as we aren't aborting and the job didn't return a
1208                  * non-zero status that we shouldn't ignore, we call
1209                  * Make_Update to update the parents. In addition, any saved
1210                  * commands for the node are placed on the .END target.
1211                  */
1212                 for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
1213                         Lst_AtEnd(&postCommands->commands,
1214                             Buf_Peel(
1215                                 Var_Subst(Lst_Datum(ln), job->node, FALSE)));
1216                 }
1217
1218                 job->node->made = MADE;
1219                 Make_Update(job->node);
1220                 free(job);
1221
1222         } else if (*status != 0) {
1223                 errors += 1;
1224                 free(job);
1225         }
1226
1227         JobRestartJobs();
1228
1229         /*
1230          * Set aborting if any error.
1231          */
1232         if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
1233                 /*
1234                  * If we found any errors in this batch of children and the -k
1235                  * flag wasn't given, we set the aborting flag so no more jobs
1236                  * get started.
1237                  */
1238                 aborting = ABORT_ERROR;
1239         }
1240
1241         if (aborting == ABORT_ERROR && Job_Empty()) {
1242                 /*
1243                  * If we are aborting and the job table is now empty, we finish.
1244                  */
1245                 Finish(errors);
1246         }
1247 }
1248
1249 /**
1250  * Job_Touch
1251  *      Touch the given target. Called by JobStart when the -t flag was
1252  *      given.  Prints messages unless told to be silent.
1253  *
1254  * Side Effects:
1255  *      The data modification of the file is changed. In addition, if the
1256  *      file did not exist, it is created.
1257  */
1258 void
1259 Job_Touch(GNode *gn, Boolean silent)
1260 {
1261         int     streamID;       /* ID of stream opened to do the touch */
1262         struct utimbuf times;   /* Times for utime() call */
1263
1264         if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
1265                 /*
1266                  * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
1267                  * targets and, as such, shouldn't really be created.
1268                  */
1269                 return;
1270         }
1271
1272         if (!silent) {
1273                 fprintf(stdout, "touch %s\n", gn->name);
1274                 fflush(stdout);
1275         }
1276
1277         if (noExecute) {
1278                 return;
1279         }
1280
1281         if (gn->type & OP_ARCHV) {
1282                 Arch_Touch(gn);
1283         } else if (gn->type & OP_LIB) {
1284                 Arch_TouchLib(gn);
1285         } else {
1286                 char    *file = gn->path ? gn->path : gn->name;
1287
1288                 times.actime = times.modtime = now;
1289                 if (utime(file, &times) < 0) {
1290                         streamID = open(file, O_RDWR | O_CREAT, 0666);
1291
1292                         if (streamID >= 0) {
1293                                 char    c;
1294
1295                                 /*
1296                                  * Read and write a byte to the file to change
1297                                  * the modification time, then close the file.
1298                                  */
1299                                 if (read(streamID, &c, 1) == 1) {
1300                                         lseek(streamID, (off_t)0, SEEK_SET);
1301                                         write(streamID, &c, 1);
1302                                 }
1303
1304                                 close(streamID);
1305                         } else {
1306                                 fprintf(stdout, "*** couldn't touch %s: %s",
1307                                     file, strerror(errno));
1308                                 fflush(stdout);
1309                         }
1310                 }
1311         }
1312 }
1313
1314 /**
1315  * Job_CheckCommands
1316  *      Make sure the given node has all the commands it needs.
1317  *
1318  * Results:
1319  *      TRUE if the commands list is/was ok.
1320  *
1321  * Side Effects:
1322  *      The node will have commands from the .DEFAULT rule added to it
1323  *      if it needs them.
1324  */
1325 Boolean
1326 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1327 {
1328
1329         if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
1330             (gn->type & OP_LIB) == 0) {
1331                 /*
1332                  * No commands. Look for .DEFAULT rule from which we might infer
1333                  * commands.
1334                  */
1335                 if (DEFAULT != NULL && !Lst_IsEmpty(&DEFAULT->commands)) {
1336                         char *p1;
1337                         /*
1338                          * Make only looks for a .DEFAULT if the node was
1339                          * never the target of an operator, so that's what we
1340                          * do too. If a .DEFAULT was given, we substitute its
1341                          * commands for gn's commands and set the IMPSRC
1342                          * variable to be the target's name The DEFAULT node
1343                          * acts like a transformation rule, in that gn also
1344                          * inherits any attributes or sources attached to
1345                          * .DEFAULT itself.
1346                          */
1347                         Make_HandleUse(DEFAULT, gn);
1348                         Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn);
1349                         free(p1);
1350
1351                 } else if (Dir_MTime(gn) == 0) {
1352                         /*
1353                          * The node wasn't the target of an operator we have
1354                          * no .DEFAULT rule to go on and the target doesn't
1355                          * already exist. There's nothing more we can do for
1356                          * this branch. If the -k flag wasn't given, we stop
1357                          * in our tracks, otherwise we just don't update
1358                          * this node's parents so they never get examined.
1359                          */
1360                         static const char msg[] =
1361                             "make: don't know how to make";
1362
1363                         if (gn->type & OP_OPTIONAL) {
1364                                 fprintf(stdout, "%s %s(ignored)\n",
1365                                     msg, gn->name);
1366                                 fflush(stdout);
1367                         } else if (keepgoing) {
1368                                 fprintf(stdout, "%s %s(continuing)\n",
1369                                     msg, gn->name);
1370                                 fflush(stdout);
1371                                 return (FALSE);
1372                         } else {
1373 #if OLD_JOKE
1374                                 if (strcmp(gn->name,"love") == 0)
1375                                         (*abortProc)("Not war.");
1376                                 else
1377 #endif
1378                                         (*abortProc)("%s %s. Stop",
1379                                             msg, gn->name);
1380                                 return (FALSE);
1381                         }
1382                 }
1383         }
1384         return (TRUE);
1385 }
1386
1387 /**
1388  * JobExec
1389  *      Execute the shell for the given job. Called from JobStart and
1390  *      JobRestart.
1391  *
1392  * Side Effects:
1393  *      A shell is executed, outputs is altered and the Job structure added
1394  *      to the job table.
1395  */
1396 static void
1397 JobExec(Job *job, char **argv)
1398 {
1399         ProcStuff       ps;
1400
1401         if (DEBUG(JOB)) {
1402                 int       i;
1403
1404                 DEBUGF(JOB, ("Running %s\n", job->node->name));
1405                 DEBUGF(JOB, ("\tCommand: "));
1406                 for (i = 0; argv[i] != NULL; i++) {
1407                         DEBUGF(JOB, ("%s ", argv[i]));
1408                 }
1409                 DEBUGF(JOB, ("\n"));
1410         }
1411
1412         /*
1413          * Some jobs produce no output and it's disconcerting to have
1414          * no feedback of their running (since they produce no output, the
1415          * banner with their name in it never appears). This is an attempt to
1416          * provide that feedback, even if nothing follows it.
1417          */
1418         if (lastNode != job->node && (job->flags & JOB_FIRST) &&
1419             !(job->flags & JOB_SILENT)) {
1420                 MESSAGE(stdout, job->node);
1421                 lastNode = job->node;
1422         }
1423
1424         ps.in = FILENO(job->cmdFILE);
1425         if (usePipes) {
1426                 /*
1427                  * Set up the child's output to be routed through the
1428                  * pipe we've created for it.
1429                  */
1430                 ps.out = job->outPipe;
1431         } else {
1432                 /*
1433                  * We're capturing output in a file, so we duplicate
1434                  * the descriptor to the temporary file into the
1435                  * standard output.
1436                  */
1437                 ps.out = job->outFd;
1438         }
1439         ps.err = STDERR_FILENO;
1440
1441         ps.merge_errors = 1;
1442         ps.pgroup = 1;
1443         ps.searchpath = 0;
1444
1445         ps.argv = argv;
1446
1447         /*
1448          * Fork.  Warning since we are doing vfork() instead of fork(),
1449          * do not allocate memory in the child process!
1450          */
1451         if ((ps.child_pid = vfork()) == -1) {
1452                 Punt("Cannot fork");
1453
1454         } else if (ps.child_pid == 0) {
1455                 /*
1456                  * Child
1457                  */
1458                 if (fifoFd >= 0)
1459                         close(fifoFd);
1460
1461                 ProcExec(&ps);
1462                 /* NOTREACHED */
1463
1464         } else {
1465                 /*
1466                  * Parent
1467                  */
1468                 job->pid = ps.child_pid;
1469
1470                 if (usePipes && (job->flags & JOB_FIRST)) {
1471                         /*
1472                          * The first time a job is run for a node, we set the
1473                          * current position in the buffer to the beginning and
1474                          * mark another stream to watch in the outputs mask.
1475                          */
1476 #ifdef USE_KQUEUE
1477                         struct kevent   kev[2];
1478 #endif
1479                         job->curPos = 0;
1480
1481 #if defined(USE_KQUEUE)
1482                         EV_SET(&kev[0], job->inPipe, EVFILT_READ, EV_ADD, 0, 0, job);
1483                         EV_SET(&kev[1], job->pid, EVFILT_PROC,
1484                             EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
1485                         if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1486                                 /*
1487                                  * kevent() will fail if the job is already
1488                                  * finished
1489                                  */
1490                                 if (errno != EINTR && errno != EBADF && errno != ESRCH)
1491                                         Punt("kevent: %s", strerror(errno));
1492                         }
1493 #else
1494                         FD_SET(job->inPipe, &outputs);
1495 #endif /* USE_KQUEUE */
1496                 }
1497
1498                 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1499                         fclose(job->cmdFILE);
1500                         job->cmdFILE = NULL;
1501                 }
1502
1503                 /*
1504                  * Now the job is actually running, add it to the table.
1505                  */
1506                 nJobs += 1;
1507                 TAILQ_INSERT_TAIL(&jobs, job, link);
1508                 if (nJobs == maxJobs) {
1509                         jobFull = TRUE;
1510                 }
1511         }
1512 }
1513
1514 /**
1515  * JobMakeArgv
1516  *      Create the argv needed to execute the shell for a given job.
1517  */
1518 static void
1519 JobMakeArgv(Job *job, char **argv)
1520 {
1521         int             argc;
1522         static char     args[10];       /* For merged arguments */
1523
1524         argv[0] = shellName;
1525         argc = 1;
1526
1527         if ((commandShell->exit && *commandShell->exit != '-') ||
1528             (commandShell->echo && *commandShell->echo != '-')) {
1529                 /*
1530                  * At least one of the flags doesn't have a minus before it, so
1531                  * merge them together. Have to do this because the *(&(@*#*&#$#
1532                  * Bourne shell thinks its second argument is a file to source.
1533                  * Grrrr. Note the ten-character limitation on the combined
1534                  * arguments.
1535                  */
1536                 sprintf(args, "-%s%s", (job->flags & JOB_IGNERR) ? "" :
1537                     commandShell->exit ? commandShell->exit : "",
1538                     (job->flags & JOB_SILENT) ? "" :
1539                     commandShell->echo ? commandShell->echo : "");
1540
1541                 if (args[1]) {
1542                         argv[argc] = args;
1543                         argc++;
1544                 }
1545         } else {
1546                 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1547                         argv[argc] = commandShell->exit;
1548                         argc++;
1549                 }
1550                 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1551                         argv[argc] = commandShell->echo;
1552                         argc++;
1553                 }
1554         }
1555         argv[argc] = NULL;
1556 }
1557
1558 /**
1559  * JobRestart
1560  *      Restart a job that stopped for some reason. The job must be neither
1561  *      on the jobs nor on the stoppedJobs list.
1562  *
1563  * Side Effects:
1564  *      jobFull will be set if the job couldn't be run.
1565  */
1566 static void
1567 JobRestart(Job *job)
1568 {
1569
1570         if (job->flags & JOB_RESTART) {
1571                 /*
1572                  * Set up the control arguments to the shell. This is based on
1573                  * the flags set earlier for this job. If the JOB_IGNERR flag
1574                  * is clear, the 'exit' flag of the commandShell is used to
1575                  * cause it to exit upon receiving an error. If the JOB_SILENT
1576                  * flag is clear, the 'echo' flag of the commandShell is used
1577                  * to get it to start echoing as soon as it starts
1578                  * processing commands.
1579                  */
1580                 char    *argv[4];
1581
1582                 JobMakeArgv(job, argv);
1583
1584                 DEBUGF(JOB, ("Restarting %s...", job->node->name));
1585                 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL)) {
1586                         /*
1587                          * Not allowed to run -- put it back on the hold
1588                          * queue and mark the table full
1589                          */
1590                         DEBUGF(JOB, ("holding\n"));
1591                         TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1592                         jobFull = TRUE;
1593                         DEBUGF(JOB, ("Job queue is full.\n"));
1594                         return;
1595                 } else {
1596                         /*
1597                          * Job may be run locally.
1598                          */
1599                         DEBUGF(JOB, ("running locally\n"));
1600                 }
1601                 JobExec(job, argv);
1602
1603         } else {
1604                 /*
1605                  * The job has stopped and needs to be restarted.
1606                  * Why it stopped, we don't know...
1607                  */
1608                 DEBUGF(JOB, ("Resuming %s...", job->node->name));
1609                 if ((nJobs < maxJobs || ((job->flags & JOB_SPECIAL) &&
1610                     maxJobs == 0)) && nJobs != maxJobs) {
1611                         /*
1612                          * If we haven't reached the concurrency limit already
1613                          * (or the job must be run and maxJobs is 0), it's ok
1614                          * to resume it.
1615                          */
1616                         Boolean error;
1617                         int status;
1618
1619                         error = (KILL(job->pid, SIGCONT) != 0);
1620
1621                         if (!error) {
1622                                 /*
1623                                  * Make sure the user knows we've continued
1624                                  * the beast and actually put the thing in the
1625                                  * job table.
1626                                  */
1627                                 job->flags |= JOB_CONTINUING;
1628                                 status = 0;
1629                                 W_SETTERMSIG(&status, SIGCONT);
1630                                 JobFinish(job, &status);
1631
1632                                 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1633                                 DEBUGF(JOB, ("done\n"));
1634                         } else {
1635                                 Error("couldn't resume %s: %s",
1636                                 job->node->name, strerror(errno));
1637                                 status = 0;
1638                                 W_SETEXITSTATUS(&status, 1);
1639                                 JobFinish(job, &status);
1640                         }
1641                 } else {
1642                         /*
1643                         * Job cannot be restarted. Mark the table as full and
1644                         * place the job back on the list of stopped jobs.
1645                         */
1646                         DEBUGF(JOB, ("table full\n"));
1647                         TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1648                         jobFull = TRUE;
1649                         DEBUGF(JOB, ("Job queue is full.\n"));
1650                 }
1651         }
1652 }
1653
1654 /**
1655  * JobStart
1656  *      Start a target-creation process going for the target described
1657  *      by the graph node gn.
1658  *
1659  * Results:
1660  *      JOB_ERROR if there was an error in the commands, JOB_FINISHED
1661  *      if there isn't actually anything left to do for the job and
1662  *      JOB_RUNNING if the job has been started.
1663  *
1664  * Side Effects:
1665  *      A new Job node is created and added to the list of running
1666  *      jobs. PMake is forked and a child shell created.
1667  */
1668 static int
1669 JobStart(GNode *gn, int flags, Job *previous)
1670 {
1671         Job     *job;           /* new job descriptor */
1672         char    *argv[4];       /* Argument vector to shell */
1673         Boolean cmdsOK;         /* true if the nodes commands were all right */
1674         Boolean noExec;         /* Set true if we decide not to run the job */
1675         int     tfd;            /* File descriptor for temp file */
1676         LstNode *ln;
1677         char    tfile[sizeof(TMPPAT)];
1678
1679         if (interrupted) {
1680                 JobPassSig(interrupted);
1681                 return (JOB_ERROR);
1682         }
1683         if (previous != NULL) {
1684                 previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1685                 job = previous;
1686         } else {
1687                 job = emalloc(sizeof(Job));
1688                 flags |= JOB_FIRST;
1689         }
1690
1691         job->node = gn;
1692         job->tailCmds = NULL;
1693
1694         /*
1695          * Set the initial value of the flags for this job based on the global
1696          * ones and the node's attributes... Any flags supplied by the caller
1697          * are also added to the field.
1698          */
1699         job->flags = 0;
1700         if (Targ_Ignore(gn)) {
1701                 job->flags |= JOB_IGNERR;
1702         }
1703         if (Targ_Silent(gn)) {
1704                 job->flags |= JOB_SILENT;
1705         }
1706         job->flags |= flags;
1707
1708         /*
1709          * Check the commands now so any attributes from .DEFAULT have a chance
1710          * to migrate to the node.
1711          */
1712         if (!compatMake && (job->flags & JOB_FIRST)) {
1713                 cmdsOK = Job_CheckCommands(gn, Error);
1714         } else {
1715                 cmdsOK = TRUE;
1716         }
1717
1718         /*
1719          * If the -n flag wasn't given, we open up OUR (not the child's)
1720          * temporary file to stuff commands in it. The thing is rd/wr so we
1721          * don't need to reopen it to feed it to the shell. If the -n flag
1722          * *was* given, we just set the file to be stdout. Cute, huh?
1723          */
1724         if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1725                 /*
1726                  * We're serious here, but if the commands were bogus, we're
1727                  * also dead...
1728                  */
1729                 if (!cmdsOK) {
1730                         DieHorribly();
1731                 }
1732
1733                 strcpy(tfile, TMPPAT);
1734                 if ((tfd = mkstemp(tfile)) == -1)
1735                         Punt("Cannot create temp file: %s", strerror(errno));
1736                 job->cmdFILE = fdopen(tfd, "w+");
1737                 eunlink(tfile);
1738                 if (job->cmdFILE == NULL) {
1739                         close(tfd);
1740                         Punt("Could not open %s", tfile);
1741                 }
1742                 fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1743                 /*
1744                  * Send the commands to the command file, flush all its
1745                  * buffers then rewind and remove the thing.
1746                  */
1747                 noExec = FALSE;
1748
1749                 /*
1750                  * Used to be backwards; replace when start doing multiple
1751                  * commands per shell.
1752                  */
1753                 if (compatMake) {
1754                         /*
1755                          * Be compatible: If this is the first time for this
1756                          * node, verify its commands are ok and open the
1757                          * commands list for sequential access by later
1758                          * invocations of JobStart. Once that is done, we take
1759                          * the next command off the list and print it to the
1760                          * command file. If the command was an ellipsis, note
1761                          * that there's nothing more to execute.
1762                          */
1763                         if (job->flags & JOB_FIRST)
1764                                 gn->compat_command = Lst_First(&gn->commands);
1765                         else
1766                                 gn->compat_command =
1767                                     Lst_Succ(gn->compat_command);
1768
1769                         if (gn->compat_command == NULL ||
1770                             JobPrintCommand(Lst_Datum(gn->compat_command), job))
1771                                 noExec = TRUE;
1772
1773                         if (noExec && !(job->flags & JOB_FIRST)) {
1774                                 /*
1775                                  * If we're not going to execute anything, the
1776                                  * job is done and we need to close down the
1777                                  * various file descriptors we've opened for
1778                                  * output, then call JobDoOutput to catch the
1779                                  * final characters or send the file to the
1780                                  * screen... Note that the i/o streams are only
1781                                  * open if this isn't the first job. Note also
1782                                  * that this could not be done in
1783                                  * Job_CatchChildren b/c it wasn't clear if
1784                                  * there were more commands to execute or not...
1785                                  */
1786                                 JobClose(job);
1787                         }
1788                 } else {
1789                         /*
1790                          * We can do all the commands at once. hooray for sanity
1791                          */
1792                         numCommands = 0;
1793                         LST_FOREACH(ln, &gn->commands) {
1794                                 if (JobPrintCommand(Lst_Datum(ln), job))
1795                                         break;
1796                         }
1797
1798                         /*
1799                          * If we didn't print out any commands to the shell
1800                          * script, there's not much point in executing the
1801                          * shell, is there?
1802                          */
1803                         if (numCommands == 0) {
1804                                 noExec = TRUE;
1805                         }
1806                 }
1807
1808         } else if (noExecute) {
1809                 /*
1810                  * Not executing anything -- just print all the commands to
1811                  * stdout in one fell swoop. This will still set up
1812                  * job->tailCmds correctly.
1813                  */
1814                 if (lastNode != gn) {
1815                         MESSAGE(stdout, gn);
1816                         lastNode = gn;
1817                 }
1818                 job->cmdFILE = stdout;
1819
1820                 /*
1821                  * Only print the commands if they're ok, but don't die if
1822                  * they're not -- just let the user know they're bad and keep
1823                  * going. It doesn't do any harm in this case and may do
1824                  * some good.
1825                  */
1826                 if (cmdsOK) {
1827                         LST_FOREACH(ln, &gn->commands) {
1828                                 if (JobPrintCommand(Lst_Datum(ln), job))
1829                                         break;
1830                         }
1831                 }
1832                 /*
1833                 * Don't execute the shell, thank you.
1834                 */
1835                 noExec = TRUE;
1836
1837         } else {
1838                 /*
1839                  * Just touch the target and note that no shell should be
1840                  * executed. Set cmdFILE to stdout to make life easier. Check
1841                  * the commands, too, but don't die if they're no good -- it
1842                  * does no harm to keep working up the graph.
1843                  */
1844                 job->cmdFILE = stdout;
1845                 Job_Touch(gn, job->flags & JOB_SILENT);
1846                 noExec = TRUE;
1847         }
1848
1849         /*
1850          * If we're not supposed to execute a shell, don't.
1851          */
1852         if (noExec) {
1853                 /*
1854                  * Unlink and close the command file if we opened one
1855                  */
1856                 if (job->cmdFILE != stdout) {
1857                         if (job->cmdFILE != NULL)
1858                                 fclose(job->cmdFILE);
1859                 } else {
1860                         fflush(stdout);
1861                 }
1862
1863                 /*
1864                  * We only want to work our way up the graph if we aren't here
1865                  * because the commands for the job were no good.
1866                 */
1867                 if (cmdsOK) {
1868                         if (aborting == 0) {
1869                                 for (ln = job->tailCmds; ln != NULL;
1870                                     ln = LST_NEXT(ln)) {
1871                                         Lst_AtEnd(&postCommands->commands,
1872                                             Buf_Peel(Var_Subst(Lst_Datum(ln),
1873                                             job->node, FALSE)));
1874                                 }
1875                                 job->node->made = MADE;
1876                                 Make_Update(job->node);
1877                         }
1878                         free(job);
1879                         return(JOB_FINISHED);
1880                 } else {
1881                         free(job);
1882                         return(JOB_ERROR);
1883                 }
1884         } else {
1885                 fflush(job->cmdFILE);
1886         }
1887
1888         /*
1889          * Set up the control arguments to the shell. This is based on the flags
1890          * set earlier for this job.
1891          */
1892         JobMakeArgv(job, argv);
1893
1894         /*
1895          * If we're using pipes to catch output, create the pipe by which we'll
1896          * get the shell's output. If we're using files, print out that we're
1897          * starting a job and then set up its temporary-file name.
1898          */
1899         if (!compatMake || (job->flags & JOB_FIRST)) {
1900                 if (usePipes) {
1901                         int fd[2];
1902
1903                         if (pipe(fd) == -1)
1904                                 Punt("Cannot create pipe: %s", strerror(errno));
1905                         job->inPipe = fd[0];
1906                         job->outPipe = fd[1];
1907                         fcntl(job->inPipe, F_SETFD, 1);
1908                         fcntl(job->outPipe, F_SETFD, 1);
1909                 } else {
1910                         fprintf(stdout, "Remaking `%s'\n", gn->name);
1911                         fflush(stdout);
1912                         strcpy(job->outFile, TMPPAT);
1913                         if ((job->outFd = mkstemp(job->outFile)) == -1)
1914                                 Punt("cannot create temp file: %s",
1915                                     strerror(errno));
1916                         fcntl(job->outFd, F_SETFD, 1);
1917                 }
1918         }
1919
1920         if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL) && maxJobs != 0) {
1921                 /*
1922                  * We've hit the limit of concurrency, so put the job on hold
1923                  * until some other job finishes. Note that the special jobs
1924                  * (.BEGIN, .INTERRUPT and .END) may be run even when the
1925                  * limit has been reached (e.g. when maxJobs == 0).
1926                  */
1927                 jobFull = TRUE;
1928
1929                 DEBUGF(JOB, ("Can only run job locally.\n"));
1930                 job->flags |= JOB_RESTART;
1931                 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1932         } else {
1933                 if (nJobs >= maxJobs) {
1934                         /*
1935                          * If we're running this job as a special case
1936                          * (see above), at least say the table is full.
1937                          */
1938                         jobFull = TRUE;
1939                         DEBUGF(JOB, ("Local job queue is full.\n"));
1940                 }
1941                 JobExec(job, argv);
1942         }
1943         return (JOB_RUNNING);
1944 }
1945
1946 static char *
1947 JobOutput(Job *job, char *cp, char *endp, int msg)
1948 {
1949         char *ecp;
1950
1951         if (commandShell->noPrint) {
1952                 ecp = strstr(cp, commandShell->noPrint);
1953                 while (ecp != NULL) {
1954                         if (cp != ecp) {
1955                                 *ecp = '\0';
1956                                 if (msg && job->node != lastNode) {
1957                                         MESSAGE(stdout, job->node);
1958                                         lastNode = job->node;
1959                                 }
1960                                 /*
1961                                  * The only way there wouldn't be a newline
1962                                  * after this line is if it were the last in
1963                                  * the buffer. However, since the non-printable
1964                                  * comes after it, there must be a newline, so
1965                                  * we don't print one.
1966                                  */
1967                                 fprintf(stdout, "%s", cp);
1968                                 fflush(stdout);
1969                         }
1970                         cp = ecp + strlen(commandShell->noPrint);
1971                         if (cp != endp) {
1972                                 /*
1973                                  * Still more to print, look again after
1974                                  * skipping the whitespace following the
1975                                  * non-printable command....
1976                                  */
1977                                 cp++;
1978                                 while (*cp == ' ' || *cp == '\t' ||
1979                                     *cp == '\n') {
1980                                         cp++;
1981                                 }
1982                                 ecp = strstr(cp, commandShell->noPrint);
1983                         } else {
1984                                 return (cp);
1985                         }
1986                 }
1987         }
1988         return (cp);
1989 }
1990
1991 /**
1992  * JobDoOutput
1993  *      This function is called at different times depending on
1994  *      whether the user has specified that output is to be collected
1995  *      via pipes or temporary files. In the former case, we are called
1996  *      whenever there is something to read on the pipe. We collect more
1997  *      output from the given job and store it in the job's outBuf. If
1998  *      this makes up a line, we print it tagged by the job's identifier,
1999  *      as necessary.
2000  *      If output has been collected in a temporary file, we open the
2001  *      file and read it line by line, transfering it to our own
2002  *      output channel until the file is empty. At which point we
2003  *      remove the temporary file.
2004  *      In both cases, however, we keep our figurative eye out for the
2005  *      'noPrint' line for the shell from which the output came. If
2006  *      we recognize a line, we don't print it. If the command is not
2007  *      alone on the line (the character after it is not \0 or \n), we
2008  *      do print whatever follows it.
2009  *
2010  * Side Effects:
2011  *      curPos may be shifted as may the contents of outBuf.
2012  */
2013 static void
2014 JobDoOutput(Job *job, Boolean finish)
2015 {
2016         Boolean gotNL = FALSE;  /* true if got a newline */
2017         Boolean fbuf;           /* true if our buffer filled up */
2018         int     nr;             /* number of bytes read */
2019         int     i;              /* auxiliary index into outBuf */
2020         int     max;            /* limit for i (end of current data) */
2021         int     nRead;          /* (Temporary) number of bytes read */
2022         FILE    *oFILE;         /* Stream pointer to shell's output file */
2023         char    inLine[132];
2024
2025         if (usePipes) {
2026                 /*
2027                  * Read as many bytes as will fit in the buffer.
2028                  */
2029   end_loop:
2030                 gotNL = FALSE;
2031                 fbuf = FALSE;
2032
2033                 nRead = read(job->inPipe, &job->outBuf[job->curPos],
2034                     JOB_BUFSIZE - job->curPos);
2035                 /*
2036                  * Check for interrupt here too, because the above read may
2037                  * block when the child process is stopped. In this case the
2038                  * interrupt will unblock it (we don't use SA_RESTART).
2039                  */
2040                 if (interrupted)
2041                         JobPassSig(interrupted);
2042
2043                 if (nRead < 0) {
2044                         DEBUGF(JOB, ("JobDoOutput(piperead)"));
2045                         nr = 0;
2046                 } else {
2047                         nr = nRead;
2048                 }
2049
2050                 /*
2051                  * If we hit the end-of-file (the job is dead), we must flush
2052                  * its remaining output, so pretend we read a newline if
2053                  * there's any output remaining in the buffer.
2054                  * Also clear the 'finish' flag so we stop looping.
2055                  */
2056                 if (nr == 0 && job->curPos != 0) {
2057                         job->outBuf[job->curPos] = '\n';
2058                         nr = 1;
2059                         finish = FALSE;
2060                 } else if (nr == 0) {
2061                         finish = FALSE;
2062                 }
2063
2064                 /*
2065                  * Look for the last newline in the bytes we just got. If there
2066                  * is one, break out of the loop with 'i' as its index and
2067                  * gotNL set TRUE.
2068                 */
2069                 max = job->curPos + nr;
2070                 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
2071                         if (job->outBuf[i] == '\n') {
2072                                 gotNL = TRUE;
2073                                 break;
2074                         } else if (job->outBuf[i] == '\0') {
2075                                 /*
2076                                  * Why?
2077                                  */
2078                                 job->outBuf[i] = ' ';
2079                         }
2080                 }
2081
2082                 if (!gotNL) {
2083                         job->curPos += nr;
2084                         if (job->curPos == JOB_BUFSIZE) {
2085                                 /*
2086                                  * If we've run out of buffer space, we have
2087                                  * no choice but to print the stuff. sigh.
2088                                  */
2089                                 fbuf = TRUE;
2090                                 i = job->curPos;
2091                         }
2092                 }
2093                 if (gotNL || fbuf) {
2094                         /*
2095                          * Need to send the output to the screen. Null terminate
2096                          * it first, overwriting the newline character if there
2097                          * was one. So long as the line isn't one we should
2098                          * filter (according to the shell description), we print
2099                          * the line, preceded by a target banner if this target
2100                          * isn't the same as the one for which we last printed
2101                          * something. The rest of the data in the buffer are
2102                          * then shifted down to the start of the buffer and
2103                          * curPos is set accordingly.
2104                          */
2105                         job->outBuf[i] = '\0';
2106                         if (i >= job->curPos) {
2107                                 char *cp;
2108
2109                                 cp = JobOutput(job, job->outBuf,
2110                                     &job->outBuf[i], FALSE);
2111
2112                                 /*
2113                                  * There's still more in that buffer. This time,
2114                                  * though, we know there's no newline at the
2115                                  * end, so we add one of our own free will.
2116                                  */
2117                                 if (*cp != '\0') {
2118                                         if (job->node != lastNode) {
2119                                                 MESSAGE(stdout, job->node);
2120                                                 lastNode = job->node;
2121                                         }
2122                                         fprintf(stdout, "%s%s", cp,
2123                                             gotNL ? "\n" : "");
2124                                         fflush(stdout);
2125                                 }
2126                         }
2127                         if (i < max - 1) {
2128                                 /* shift the remaining characters down */
2129                                 memcpy(job->outBuf, &job->outBuf[i + 1],
2130                                     max - (i + 1));
2131                                 job->curPos = max - (i + 1);
2132
2133                         } else {
2134                                 /*
2135                                  * We have written everything out, so we just
2136                                  * start over from the start of the buffer.
2137                                  * No copying. No nothing.
2138                                  */
2139                                 job->curPos = 0;
2140                         }
2141                 }
2142                 if (finish) {
2143                         /*
2144                          * If the finish flag is true, we must loop until we hit
2145                          * end-of-file on the pipe. This is guaranteed to happen
2146                          * eventually since the other end of the pipe is now
2147                          * closed (we closed it explicitly and the child has
2148                          * exited). When we do get an EOF, finish will be set
2149                          * FALSE and we'll fall through and out.
2150                          */
2151                         goto end_loop;
2152                 }
2153
2154         } else {
2155                 /*
2156                  * We've been called to retrieve the output of the job from the
2157                  * temporary file where it's been squirreled away. This consists
2158                  * of opening the file, reading the output line by line, being
2159                  * sure not to print the noPrint line for the shell we used,
2160                  * then close and remove the temporary file. Very simple.
2161                  *
2162                  * Change to read in blocks and do FindSubString type things
2163                  * as for pipes? That would allow for "@echo -n..."
2164                  */
2165                 oFILE = fopen(job->outFile, "r");
2166                 if (oFILE != NULL) {
2167                         fprintf(stdout, "Results of making %s:\n",
2168                             job->node->name);
2169                         fflush(stdout);
2170
2171                         while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2172                                 char    *cp, *endp, *oendp;
2173
2174                                 cp = inLine;
2175                                 oendp = endp = inLine + strlen(inLine);
2176                                 if (endp[-1] == '\n') {
2177                                         *--endp = '\0';
2178                                 }
2179                                 cp = JobOutput(job, inLine, endp, FALSE);
2180
2181                                 /*
2182                                  * There's still more in that buffer. This time,
2183                                  * though, we know there's no newline at the
2184                                  * end, so we add one of our own free will.
2185                                  */
2186                                 fprintf(stdout, "%s", cp);
2187                                 fflush(stdout);
2188                                 if (endp != oendp) {
2189                                         fprintf(stdout, "\n");
2190                                         fflush(stdout);
2191                                 }
2192                         }
2193                         fclose(oFILE);
2194                         eunlink(job->outFile);
2195                 }
2196         }
2197 }
2198
2199 /**
2200  * Job_CatchChildren
2201  *      Handle the exit of a child. Called from Make_Make.
2202  *
2203  * Side Effects:
2204  *      The job descriptor is removed from the list of children.
2205  *
2206  * Notes:
2207  *      We do waits, blocking or not, according to the wisdom of our
2208  *      caller, until there are no more children to report. For each
2209  *      job, call JobFinish to finish things off. This will take care of
2210  *      putting jobs on the stoppedJobs queue.
2211  */
2212 void
2213 Job_CatchChildren(Boolean block)
2214 {
2215         pid_t   pid;    /* pid of dead child */
2216         Job     *job;   /* job descriptor for dead child */
2217         int     status; /* Exit/termination status */
2218
2219         /*
2220          * Don't even bother if we know there's no one around.
2221          */
2222         if (nJobs == 0) {
2223                 return;
2224         }
2225
2226         for (;;) {
2227                 pid = waitpid((pid_t)-1, &status,
2228                     (block ? 0 : WNOHANG) | WUNTRACED);
2229                 if (pid <= 0)
2230                         break;
2231
2232                 DEBUGF(JOB, ("Process %jd exited or stopped.\n",
2233                     (intmax_t)pid));
2234
2235                 TAILQ_FOREACH(job, &jobs, link) {
2236                         if (job->pid == pid)
2237                                 break;
2238                 }
2239
2240                 if (job == NULL) {
2241                         if (WIFSIGNALED(status) &&
2242                             (WTERMSIG(status) == SIGCONT)) {
2243                                 TAILQ_FOREACH(job, &jobs, link) {
2244                                         if (job->pid == pid)
2245                                                 break;
2246                                 }
2247                                 if (job == NULL) {
2248                                         Error("Resumed child (%jd) "
2249                                             "not in table", (intmax_t)pid);
2250                                         continue;
2251                                 }
2252                                 TAILQ_REMOVE(&stoppedJobs, job, link);
2253                         } else {
2254                                 Error("Child (%jd) not in table?",
2255                                     (intmax_t)pid);
2256                                 continue;
2257                         }
2258                 } else {
2259                         TAILQ_REMOVE(&jobs, job, link);
2260                         nJobs -= 1;
2261                         if (fifoFd >= 0 && maxJobs > 1) {
2262                                 write(fifoFd, "+", 1);
2263                                 maxJobs--;
2264                                 if (nJobs >= maxJobs)
2265                                         jobFull = TRUE;
2266                                 else
2267                                         jobFull = FALSE;
2268                         } else {
2269                                 DEBUGF(JOB, ("Job queue is no longer full.\n"));
2270                                 jobFull = FALSE;
2271                         }
2272                 }
2273
2274                 JobFinish(job, &status);
2275         }
2276         if (interrupted)
2277                 JobPassSig(interrupted);
2278 }
2279
2280 /**
2281  * Job_CatchOutput
2282  *      Catch the output from our children, if we're using
2283  *      pipes do so. Otherwise just block time until we get a
2284  *      signal(most likely a SIGCHLD) since there's no point in
2285  *      just spinning when there's nothing to do and the reaping
2286  *      of a child can wait for a while.
2287  *
2288  * Side Effects:
2289  *      Output is read from pipes if we're piping.
2290  * -----------------------------------------------------------------------
2291  */
2292 void
2293 #ifdef USE_KQUEUE
2294 Job_CatchOutput(int flag __unused)
2295 #else
2296 Job_CatchOutput(int flag)
2297 #endif
2298 {
2299         int             nfds;
2300 #ifdef USE_KQUEUE
2301 #define KEV_SIZE        4
2302         struct kevent   kev[KEV_SIZE];
2303         int             i;
2304 #else
2305         struct timeval  timeout;
2306         fd_set          readfds;
2307         Job             *job;
2308 #endif
2309
2310         fflush(stdout);
2311
2312         if (usePipes) {
2313 #ifdef USE_KQUEUE
2314                 if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
2315                         if (errno != EINTR)
2316                                 Punt("kevent: %s", strerror(errno));
2317                         if (interrupted)
2318                                 JobPassSig(interrupted);
2319                 } else {
2320                         for (i = 0; i < nfds; i++) {
2321                                 if (kev[i].flags & EV_ERROR) {
2322                                         warnc(kev[i].data, "kevent");
2323                                         continue;
2324                                 }
2325                                 switch (kev[i].filter) {
2326                                   case EVFILT_READ:
2327                                         JobDoOutput(kev[i].udata, FALSE);
2328                                         break;
2329                                   case EVFILT_PROC:
2330                                         /*
2331                                          * Just wake up and let
2332                                          * Job_CatchChildren() collect the
2333                                          * terminated job.
2334                                          */
2335                                         break;
2336                                 }
2337                         }
2338                 }
2339 #else
2340                 readfds = outputs;
2341                 timeout.tv_sec = SEL_SEC;
2342                 timeout.tv_usec = SEL_USEC;
2343                 if (flag && jobFull && fifoFd >= 0)
2344                         FD_SET(fifoFd, &readfds);
2345
2346                 nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
2347                     (fd_set *)NULL, &timeout);
2348                 if (nfds <= 0) {
2349                         if (interrupted)
2350                                 JobPassSig(interrupted);
2351                         return;
2352                 }
2353                 if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2354                         if (--nfds <= 0)
2355                                 return;
2356                 }
2357                 job = TAILQ_FIRST(&jobs);
2358                 while (nfds != 0 && job != NULL) {
2359                         if (FD_ISSET(job->inPipe, &readfds)) {
2360                                 JobDoOutput(job, FALSE);
2361                                 nfds--;
2362                         }
2363                         job = TAILQ_NEXT(job, link);
2364                 }
2365 #endif /* !USE_KQUEUE */
2366         }
2367 }
2368
2369 /**
2370  * Job_Make
2371  *      Start the creation of a target. Basically a front-end for
2372  *      JobStart used by the Make module.
2373  *
2374  * Side Effects:
2375  *      Another job is started.
2376  */
2377 void
2378 Job_Make(GNode *gn)
2379 {
2380
2381         JobStart(gn, 0, NULL);
2382 }
2383
2384 /**
2385  * JobCopyShell
2386  *      Make a new copy of the shell structure including a copy of the strings
2387  *      in it. This also defaults some fields in case they are NULL.
2388  *
2389  * Returns:
2390  *      The function returns a pointer to the new shell structure.
2391  */
2392 static struct Shell *
2393 JobCopyShell(const struct Shell *osh)
2394 {
2395         struct Shell *nsh;
2396
2397         nsh = emalloc(sizeof(*nsh));
2398         nsh->name = estrdup(osh->name);
2399
2400         if (osh->echoOff != NULL)
2401                 nsh->echoOff = estrdup(osh->echoOff);
2402         else
2403                 nsh->echoOff = NULL;
2404         if (osh->echoOn != NULL)
2405                 nsh->echoOn = estrdup(osh->echoOn);
2406         else
2407                 nsh->echoOn = NULL;
2408         nsh->hasEchoCtl = osh->hasEchoCtl;
2409
2410         if (osh->noPrint != NULL)
2411                 nsh->noPrint = estrdup(osh->noPrint);
2412         else
2413                 nsh->noPrint = NULL;
2414
2415         nsh->hasErrCtl = osh->hasErrCtl;
2416         if (osh->errCheck == NULL)
2417                 nsh->errCheck = estrdup("");
2418         else
2419                 nsh->errCheck = estrdup(osh->errCheck);
2420         if (osh->ignErr == NULL)
2421                 nsh->ignErr = estrdup("%s");
2422         else
2423                 nsh->ignErr = estrdup(osh->ignErr);
2424
2425         if (osh->echo == NULL)
2426                 nsh->echo = estrdup("");
2427         else
2428                 nsh->echo = estrdup(osh->echo);
2429
2430         if (osh->exit == NULL)
2431                 nsh->exit = estrdup("");
2432         else
2433                 nsh->exit = estrdup(osh->exit);
2434
2435         return (nsh);
2436 }
2437
2438 /**
2439  * JobFreeShell
2440  *      Free a shell structure and all associated strings.
2441  */
2442 static void
2443 JobFreeShell(struct Shell *sh)
2444 {
2445
2446         if (sh != NULL) {
2447                 free(sh->name);
2448                 free(sh->echoOff);
2449                 free(sh->echoOn);
2450                 free(sh->noPrint);
2451                 free(sh->errCheck);
2452                 free(sh->ignErr);
2453                 free(sh->echo);
2454                 free(sh->exit);
2455                 free(sh);
2456         }
2457 }
2458
2459 void
2460 Shell_Init(void)
2461 {
2462
2463         if (commandShell == NULL)
2464                 commandShell = JobMatchShell(shells[DEFSHELL].name);
2465
2466         if (shellPath == NULL) {
2467                 /*
2468                  * The user didn't specify a shell to use, so we are using the
2469                  * default one... Both the absolute path and the last component
2470                  * must be set. The last component is taken from the 'name'
2471                  * field of the default shell description pointed-to by
2472                  * commandShell. All default shells are located in
2473                  * PATH_DEFSHELLDIR.
2474                  */
2475                 shellName = commandShell->name;
2476                 shellPath = str_concat(PATH_DEFSHELLDIR, shellName,
2477                     STR_ADDSLASH);
2478         }
2479 }
2480
2481 /**
2482  * Job_Init
2483  *      Initialize the process module, given a maximum number of jobs.
2484  *
2485  * Side Effects:
2486  *      lists and counters are initialized
2487  */
2488 void
2489 Job_Init(int maxproc)
2490 {
2491         GNode           *begin; /* node for commands to do at the very start */
2492         const char      *env;
2493         struct sigaction sa;
2494
2495         fifoFd = -1;
2496         env = getenv("MAKE_JOBS_FIFO");
2497
2498         if (env == NULL && maxproc > 1) {
2499                 /*
2500                  * We did not find the environment variable so we are the
2501                  * leader. Create the fifo, open it, write one char per
2502                  * allowed job into the pipe.
2503                  */
2504                 mktemp(fifoName);
2505                 if (!mkfifo(fifoName, 0600)) {
2506                         fifoFd = open(fifoName, O_RDWR | O_NONBLOCK, 0);
2507                         if (fifoFd >= 0) {
2508                                 fifoMaster = 1;
2509                                 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2510                                 env = fifoName;
2511                                 setenv("MAKE_JOBS_FIFO", env, 1);
2512                                 while (maxproc-- > 0) {
2513                                         write(fifoFd, "+", 1);
2514                                 }
2515                                 /* The master make does not get a magic token */
2516                                 jobFull = TRUE;
2517                                 maxJobs = 0;
2518                         } else {
2519                                 unlink(fifoName);
2520                                 env = NULL;
2521                         }
2522                 }
2523
2524         } else if (env != NULL) {
2525                 /*
2526                  * We had the environment variable so we are a slave.
2527                  * Open fifo and give ourselves a magic token which represents
2528                  * the token our parent make has grabbed to start his make
2529                  * process. Otherwise the sub-makes would gobble up tokens and
2530                  * the proper number of tokens to specify to -j would depend
2531                  * on the depth of the tree and the order of execution.
2532                  */
2533                 fifoFd = open(env, O_RDWR, 0);
2534                 if (fifoFd >= 0) {
2535                         fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2536                         maxJobs = 1;
2537                         jobFull = FALSE;
2538                 }
2539         }
2540         if (fifoFd <= 0) {
2541                 maxJobs = maxproc;
2542                 jobFull = FALSE;
2543         } else {
2544         }
2545         nJobs = 0;
2546
2547         aborting = 0;
2548         errors = 0;
2549
2550         lastNode = NULL;
2551
2552         if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2553                 /*
2554                  * If only one job can run at a time, there's no need for a
2555                  * banner, no is there?
2556                  */
2557                 targFmt = "";
2558         } else {
2559                 targFmt = TARG_FMT;
2560         }
2561
2562         Shell_Init();
2563
2564         /*
2565          * Catch the four signals that POSIX specifies if they aren't ignored.
2566          * JobCatchSignal will just set global variables and hope someone
2567          * else is going to handle the interrupt.
2568          */
2569         sa.sa_handler = JobCatchSig;
2570         sigemptyset(&sa.sa_mask);
2571         sa.sa_flags = 0;
2572
2573         if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2574                 sigaction(SIGINT, &sa, NULL);
2575         }
2576         if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2577                 sigaction(SIGHUP, &sa, NULL);
2578         }
2579         if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2580                 sigaction(SIGQUIT, &sa, NULL);
2581         }
2582         if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2583                 sigaction(SIGTERM, &sa, NULL);
2584         }
2585         /*
2586          * There are additional signals that need to be caught and passed if
2587          * either the export system wants to be told directly of signals or if
2588          * we're giving each job its own process group (since then it won't get
2589          * signals from the terminal driver as we own the terminal)
2590          */
2591 #if defined(USE_PGRP)
2592         if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2593                 sigaction(SIGTSTP, &sa, NULL);
2594         }
2595         if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2596                 sigaction(SIGTTOU, &sa, NULL);
2597         }
2598         if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2599                 sigaction(SIGTTIN, &sa, NULL);
2600         }
2601         if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2602                 sigaction(SIGWINCH, &sa, NULL);
2603         }
2604 #endif
2605
2606 #ifdef USE_KQUEUE
2607         if ((kqfd = kqueue()) == -1) {
2608                 Punt("kqueue: %s", strerror(errno));
2609         }
2610 #endif
2611
2612         begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2613
2614         if (begin != NULL) {
2615                 JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2616                 while (nJobs) {
2617                         Job_CatchOutput(0);
2618                         Job_CatchChildren(!usePipes);
2619                 }
2620         }
2621         postCommands = Targ_FindNode(".END", TARG_CREATE);
2622 }
2623
2624 /**
2625  * Job_Full
2626  *      See if the job table is full. It is considered full if it is OR
2627  *      if we are in the process of aborting OR if we have
2628  *      reached/exceeded our local quota. This prevents any more jobs
2629  *      from starting up.
2630  *
2631  * Results:
2632  *      TRUE if the job table is full, FALSE otherwise
2633  */
2634 Boolean
2635 Job_Full(void)
2636 {
2637         char c;
2638         int i;
2639
2640         if (aborting)
2641                 return (aborting);
2642         if (fifoFd >= 0 && jobFull) {
2643                 i = read(fifoFd, &c, 1);
2644                 if (i > 0) {
2645                         maxJobs++;
2646                         jobFull = FALSE;
2647                 }
2648         }
2649         return (jobFull);
2650 }
2651
2652 /**
2653  * Job_Empty
2654  *      See if the job table is empty.  Because the local concurrency may
2655  *      be set to 0, it is possible for the job table to become empty,
2656  *      while the list of stoppedJobs remains non-empty. In such a case,
2657  *      we want to restart as many jobs as we can.
2658  *
2659  * Results:
2660  *      TRUE if it is. FALSE if it ain't.
2661  */
2662 Boolean
2663 Job_Empty(void)
2664 {
2665         if (nJobs == 0) {
2666                 if (!TAILQ_EMPTY(&stoppedJobs) && !aborting) {
2667                         /*
2668                          * The job table is obviously not full if it has no
2669                          * jobs in it...Try and restart the stopped jobs.
2670                          */
2671                         jobFull = FALSE;
2672                         JobRestartJobs();
2673                         return (FALSE);
2674                 } else {
2675                         return (TRUE);
2676                 }
2677         } else {
2678                 return (FALSE);
2679         }
2680 }
2681
2682 /**
2683  * JobMatchShell
2684  *      Find a matching shell in 'shells' given its final component.
2685  *
2686  * Results:
2687  *      A pointer to a freshly allocated Shell structure with a copy
2688  *      of the static structure or NULL if no shell with the given name
2689  *      is found.
2690  */
2691 static struct Shell *
2692 JobMatchShell(const char *name)
2693 {
2694         const struct CShell     *sh;          /* Pointer into shells table */
2695         struct Shell            *nsh;
2696
2697         for (sh = shells; sh < shells + __arysize(shells); sh++)
2698                 if (strcmp(sh->name, name) == 0)
2699                         break;
2700
2701         if (sh == shells + __arysize(shells))
2702                 return (NULL);
2703
2704         /* make a copy */
2705         nsh = emalloc(sizeof(*nsh));
2706
2707         nsh->name = estrdup(sh->name);
2708         nsh->echoOff = estrdup(sh->echoOff);
2709         nsh->echoOn = estrdup(sh->echoOn);
2710         nsh->hasEchoCtl = sh->hasEchoCtl;
2711         nsh->noPrint = estrdup(sh->noPrint);
2712         nsh->hasErrCtl = sh->hasErrCtl;
2713         nsh->errCheck = estrdup(sh->errCheck);
2714         nsh->ignErr = estrdup(sh->ignErr);
2715         nsh->echo = estrdup(sh->echo);
2716         nsh->exit = estrdup(sh->exit);
2717
2718         return (nsh);
2719 }
2720
2721 /**
2722  * Job_ParseShell
2723  *      Parse a shell specification and set up commandShell, shellPath
2724  *      and shellName appropriately.
2725  *
2726  * Results:
2727  *      FAILURE if the specification was incorrect.
2728  *
2729  * Side Effects:
2730  *      commandShell points to a Shell structure (either predefined or
2731  *      created from the shell spec), shellPath is the full path of the
2732  *      shell described by commandShell, while shellName is just the
2733  *      final component of shellPath.
2734  *
2735  * Notes:
2736  *      A shell specification consists of a .SHELL target, with dependency
2737  *      operator, followed by a series of blank-separated words. Double
2738  *      quotes can be used to use blanks in words. A backslash escapes
2739  *      anything (most notably a double-quote and a space) and
2740  *      provides the functionality it does in C. Each word consists of
2741  *      keyword and value separated by an equal sign. There should be no
2742  *      unnecessary spaces in the word. The keywords are as follows:
2743  *          name            Name of shell.
2744  *          path            Location of shell. Overrides "name" if given
2745  *          quiet           Command to turn off echoing.
2746  *          echo            Command to turn echoing on
2747  *          filter          Result of turning off echoing that shouldn't be
2748  *                          printed.
2749  *          echoFlag        Flag to turn echoing on at the start
2750  *          errFlag         Flag to turn error checking on at the start
2751  *          hasErrCtl       True if shell has error checking control
2752  *          check           Command to turn on error checking if hasErrCtl
2753  *                          is TRUE or template of command to echo a command
2754  *                          for which error checking is off if hasErrCtl is
2755  *                          FALSE.
2756  *          ignore          Command to turn off error checking if hasErrCtl
2757  *                          is TRUE or template of command to execute a
2758  *                          command so as to ignore any errors it returns if
2759  *                          hasErrCtl is FALSE.
2760  */
2761 ReturnStatus
2762 Job_ParseShell(char *line)
2763 {
2764         char    **words;
2765         int     wordCount;
2766         char    **argv;
2767         int     argc;
2768         char    *path;
2769         char    *eq;
2770         Boolean fullSpec = FALSE;
2771         struct Shell    newShell;
2772         struct Shell    *sh;
2773
2774         while (isspace((unsigned char)*line)) {
2775                 line++;
2776         }
2777         words = brk_string(line, &wordCount, TRUE);
2778
2779         memset(&newShell, 0, sizeof(newShell));
2780         path = NULL;
2781
2782         /*
2783          * Parse the specification by keyword but skip the first word - it
2784          * is not set by brk_string.
2785          */
2786         wordCount--;
2787         words++;
2788
2789         for (argc = wordCount, argv = words; argc != 0; argc--, argv++) {
2790                 /*
2791                  * Split keyword and value
2792                  */
2793                 if ((eq = strchr(*argv, '=')) == NULL) {
2794                         Parse_Error(PARSE_FATAL, "missing '=' in shell "
2795                             "specification keyword '%s'", *argv);
2796                         return (FAILURE);
2797                 }
2798                 *eq++ = '\0';
2799
2800                 if (strcmp(*argv, "path") == 0) {
2801                         path = eq;
2802                 } else if (strcmp(*argv, "name") == 0) {
2803                         newShell.name = eq;
2804                 } else if (strcmp(*argv, "quiet") == 0) {
2805                         newShell.echoOff = eq;
2806                         fullSpec = TRUE;
2807                 } else if (strcmp(*argv, "echo") == 0) {
2808                         newShell.echoOn = eq;
2809                         fullSpec = TRUE;
2810                 } else if (strcmp(*argv, "filter") == 0) {
2811                         newShell.noPrint = eq;
2812                         fullSpec = TRUE;
2813                 } else if (strcmp(*argv, "echoFlag") == 0) {
2814                         newShell.echo = eq;
2815                         fullSpec = TRUE;
2816                 } else if (strcmp(*argv, "errFlag") == 0) {
2817                         newShell.exit = eq;
2818                         fullSpec = TRUE;
2819                 } else if (strcmp(*argv, "hasErrCtl") == 0) {
2820                         newShell.hasErrCtl = (*eq == 'Y' || *eq == 'y' ||
2821                             *eq == 'T' || *eq == 't');
2822                         fullSpec = TRUE;
2823                 } else if (strcmp(*argv, "check") == 0) {
2824                         newShell.errCheck = eq;
2825                         fullSpec = TRUE;
2826                 } else if (strcmp(*argv, "ignore") == 0) {
2827                         newShell.ignErr = eq;
2828                         fullSpec = TRUE;
2829                 } else {
2830                         Parse_Error(PARSE_FATAL, "unknown keyword in shell "
2831                             "specification '%s'", *argv);
2832                         return (FAILURE);
2833                 }
2834         }
2835
2836         /*
2837          * Some checks (could be more)
2838          */
2839         if (fullSpec) {
2840                 if ((newShell.echoOn != NULL) ^ (newShell.echoOff != NULL))
2841                         Parse_Error(PARSE_FATAL, "Shell must have either both "
2842                             "echoOff and echoOn or none of them");
2843
2844                 if (newShell.echoOn != NULL && newShell.echoOff)
2845                         newShell.hasEchoCtl = TRUE;
2846         }
2847
2848         if (path == NULL) {
2849                 /*
2850                  * If no path was given, the user wants one of the pre-defined
2851                  * shells, yes? So we find the one s/he wants with the help of
2852                  * JobMatchShell and set things up the right way. shellPath
2853                  * will be set up by Job_Init.
2854                  */
2855                 if (newShell.name == NULL) {
2856                         Parse_Error(PARSE_FATAL,
2857                             "Neither path nor name specified");
2858                         return (FAILURE);
2859                 }
2860                 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2861                         Parse_Error(PARSE_FATAL, "%s: no matching shell",
2862                             newShell.name);
2863                         return (FAILURE);
2864                 }
2865
2866         } else {
2867                 /*
2868                  * The user provided a path. If s/he gave nothing else
2869                  * (fullSpec is FALSE), try and find a matching shell in the
2870                  * ones we know of. Else we just take the specification at its
2871                  * word and copy it to a new location. In either case, we need
2872                  * to record the path the user gave for the shell.
2873                  */
2874                 free(shellPath);
2875                 shellPath = estrdup(path);
2876                 if (newShell.name == NULL) {
2877                         /* get the base name as the name */
2878                         path = strrchr(path, '/');
2879                         if (path == NULL) {
2880                                 path = shellPath;
2881                         } else {
2882                                 path += 1;
2883                         }
2884                         newShell.name = path;
2885                 }
2886
2887                 if (!fullSpec) {
2888                         if ((sh = JobMatchShell(newShell.name)) == NULL) {
2889                                 Parse_Error(PARSE_FATAL,
2890                                     "%s: no matching shell", newShell.name);
2891                                 return (FAILURE);
2892                         }
2893                 } else {
2894                         sh = JobCopyShell(&newShell);
2895                 }
2896         }
2897
2898         /* set the new shell */
2899         JobFreeShell(commandShell);
2900         commandShell = sh;
2901
2902         shellName = commandShell->name;
2903
2904         return (SUCCESS);
2905 }
2906
2907 /**
2908  * JobInterrupt
2909  *      Handle the receipt of an interrupt.
2910  *
2911  * Side Effects:
2912  *      All children are killed. Another job will be started if the
2913  *      .INTERRUPT target was given.
2914  */
2915 static void
2916 JobInterrupt(int runINTERRUPT, int signo)
2917 {
2918         Job     *job;           /* job descriptor in that element */
2919         GNode   *interrupt;     /* the node describing the .INTERRUPT target */
2920
2921         aborting = ABORT_INTERRUPT;
2922
2923         TAILQ_FOREACH(job, &jobs, link) {
2924                 if (!Targ_Precious(job->node)) {
2925                         char *file = (job->node->path == NULL ?
2926                             job->node->name : job->node->path);
2927
2928                         if (!noExecute && eunlink(file) != -1) {
2929                                 Error("*** %s removed", file);
2930                         }
2931                 }
2932                 if (job->pid) {
2933                         DEBUGF(JOB, ("JobInterrupt passing signal to child "
2934                             "%jd.\n", (intmax_t)job->pid));
2935                         KILL(job->pid, signo);
2936                 }
2937         }
2938
2939         if (runINTERRUPT && !touchFlag) {
2940                 /*
2941                  * clear the interrupted flag because we would get an
2942                  * infinite loop otherwise.
2943                  */
2944                 interrupted = 0;
2945
2946                 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2947                 if (interrupt != NULL) {
2948                         ignoreErrors = FALSE;
2949
2950                         JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
2951                         while (nJobs) {
2952                                 Job_CatchOutput(0);
2953                                 Job_CatchChildren(!usePipes);
2954                         }
2955                 }
2956         }
2957 }
2958
2959 /**
2960  * Job_Finish
2961  *      Do final processing such as the running of the commands
2962  *      attached to the .END target.
2963  *
2964  * Results:
2965  *      Number of errors reported.
2966  */
2967 int
2968 Job_Finish(void)
2969 {
2970
2971         if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
2972                 if (errors) {
2973                         Error("Errors reported so .END ignored");
2974                 } else {
2975                         JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
2976
2977                         while (nJobs) {
2978                                 Job_CatchOutput(0);
2979                                 Job_CatchChildren(!usePipes);
2980                         }
2981                 }
2982         }
2983         if (fifoFd >= 0) {
2984                 close(fifoFd);
2985                 fifoFd = -1;
2986                 if (fifoMaster)
2987                         unlink(fifoName);
2988         }
2989         return (errors);
2990 }
2991
2992 /**
2993  * Job_Wait
2994  *      Waits for all running jobs to finish and returns. Sets 'aborting'
2995  *      to ABORT_WAIT to prevent other jobs from starting.
2996  *
2997  * Side Effects:
2998  *      Currently running jobs finish.
2999  */
3000 void
3001 Job_Wait(void)
3002 {
3003
3004         aborting = ABORT_WAIT;
3005         while (nJobs != 0) {
3006                 Job_CatchOutput(0);
3007                 Job_CatchChildren(!usePipes);
3008         }
3009         aborting = 0;
3010 }
3011
3012 /**
3013  * Job_AbortAll
3014  *      Abort all currently running jobs without handling output or anything.
3015  *      This function is to be called only in the event of a major
3016  *      error. Most definitely NOT to be called from JobInterrupt.
3017  *
3018  * Side Effects:
3019  *      All children are killed, not just the firstborn
3020  */
3021 void
3022 Job_AbortAll(void)
3023 {
3024         Job     *job;   /* the job descriptor in that element */
3025         int     foo;
3026
3027         aborting = ABORT_ERROR;
3028
3029         if (nJobs) {
3030                 TAILQ_FOREACH(job, &jobs, link) {
3031                         /*
3032                          * kill the child process with increasingly drastic
3033                          * signals to make darn sure it's dead.
3034                          */
3035                         KILL(job->pid, SIGINT);
3036                         KILL(job->pid, SIGKILL);
3037                 }
3038         }
3039
3040         /*
3041          * Catch as many children as want to report in at first, then give up
3042          */
3043         while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
3044                 ;
3045 }
3046
3047 /**
3048  * JobRestartJobs
3049  *      Tries to restart stopped jobs if there are slots available.
3050  *      Note that this tries to restart them regardless of pending errors.
3051  *      It's not good to leave stopped jobs lying around!
3052  *
3053  * Side Effects:
3054  *      Resumes(and possibly migrates) jobs.
3055  */
3056 static void
3057 JobRestartJobs(void)
3058 {
3059         Job *job;
3060
3061         while (!jobFull && (job = TAILQ_FIRST(&stoppedJobs)) != NULL) {
3062                 DEBUGF(JOB, ("Job queue is not full. "
3063                     "Restarting a stopped job.\n"));
3064                 TAILQ_REMOVE(&stoppedJobs, job, link);
3065                 JobRestart(job);
3066         }
3067 }
3068
3069 /**
3070  * Cmd_Exec
3071  *      Execute the command in cmd, and return the output of that command
3072  *      in a string.
3073  *
3074  * Results:
3075  *      A string containing the output of the command, or the empty string
3076  *      If error is not NULL, it contains the reason for the command failure
3077  *      Any output sent to stderr in the child process is passed to stderr,
3078  *      and not captured in the string.
3079  *
3080  * Side Effects:
3081  *      The string must be freed by the caller.
3082  */
3083 Buffer *
3084 Cmd_Exec(const char *cmd, const char **error)
3085 {
3086         int     fds[2]; /* Pipe streams */
3087         int     status; /* command exit status */
3088         Buffer  *buf;   /* buffer to store the result */
3089         ssize_t rcnt;
3090         ProcStuff       ps;
3091
3092         *error = NULL;
3093         buf = Buf_Init(0);
3094
3095         if (shellPath == NULL)
3096                 Shell_Init();
3097         /*
3098          * Open a pipe for fetching its output
3099          */
3100         if (pipe(fds) == -1) {
3101                 *error = "Couldn't create pipe for \"%s\"";
3102                 return (buf);
3103         }
3104
3105         /* Set close-on-exec on read side of pipe. */
3106         fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC);
3107
3108         ps.in = STDIN_FILENO;
3109         ps.out = fds[1];
3110         ps.err = STDERR_FILENO;
3111
3112         ps.merge_errors = 0;
3113         ps.pgroup = 0;
3114         ps.searchpath = 0;
3115
3116         /* Set up arguments for shell */
3117         ps.argv = emalloc(4 * sizeof(char *));
3118         ps.argv[0] = strdup(shellName);
3119         ps.argv[1] = strdup("-c");
3120         ps.argv[2] = strdup(cmd);
3121         ps.argv[3] = NULL;
3122
3123         /*
3124          * Fork.  Warning since we are doing vfork() instead of fork(),
3125          * do not allocate memory in the child process!
3126          */
3127         if ((ps.child_pid = vfork()) == -1) {
3128                 *error = "Couldn't exec \"%s\"";
3129
3130         } else if (ps.child_pid == 0) {
3131                 /*
3132                  * Child
3133                  */
3134                 ProcExec(&ps);
3135                 /* NOTREACHED */
3136
3137         } else {
3138                 free(ps.argv[2]);
3139                 free(ps.argv[1]);
3140                 free(ps.argv[0]);
3141                 free(ps.argv);
3142
3143                 close(fds[1]); /* No need for the writing half of the pipe. */
3144
3145                 do {
3146                         char    result[BUFSIZ];
3147
3148                         rcnt = read(fds[0], result, sizeof(result));
3149                         if (rcnt != -1)
3150                                 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
3151                 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
3152
3153                 if (rcnt == -1)
3154                         *error = "Error reading shell's output for \"%s\"";
3155
3156                 /*
3157                  * Close the input side of the pipe.
3158                  */
3159                 close(fds[0]);
3160
3161                 status = ProcWait(&ps);
3162                 if (status)
3163                         *error = "\"%s\" returned non-zero status";
3164
3165                 Buf_StripNewlines(buf);
3166
3167         }
3168         return (buf);
3169 }
3170
3171 static void
3172 CompatInit(void)
3173 {
3174         const char      *cp;    /* Pointer to string of shell meta-characters */
3175
3176         for (cp = "#=|^(){};&<>*?[]:$`\\\n"; *cp != '\0'; cp++) {
3177                 meta[(unsigned char)*cp] = 1;
3178         }
3179         /*
3180          * The null character serves as a sentinel in the string.
3181          */
3182         meta[0] = 1;
3183 }
3184
3185 /*
3186  * Interrupt handler - set flag and defer handling to the main code
3187  */
3188 static void
3189 CompatCatchSig(int signo)
3190 {
3191
3192         interrupted = signo;
3193 }
3194
3195 /*-
3196  *-----------------------------------------------------------------------
3197  * CompatInterrupt --
3198  *      Interrupt the creation of the current target and remove it if
3199  *      it ain't precious.
3200  *
3201  * Results:
3202  *      None.
3203  *
3204  * Side Effects:
3205  *      The target is removed and the process exits. If .INTERRUPT exists,
3206  *      its commands are run first WITH INTERRUPTS IGNORED..
3207  *
3208  *-----------------------------------------------------------------------
3209  */
3210 static void
3211 CompatInterrupt(int signo)
3212 {
3213         GNode           *gn;
3214         sigset_t        nmask, omask;
3215         LstNode         *ln;
3216
3217         sigemptyset(&nmask);
3218         sigaddset(&nmask, SIGINT);
3219         sigaddset(&nmask, SIGTERM);
3220         sigaddset(&nmask, SIGHUP);
3221         sigaddset(&nmask, SIGQUIT);
3222         sigprocmask(SIG_SETMASK, &nmask, &omask);
3223
3224         /* prevent recursion in evaluation of .INTERRUPT */
3225         interrupted = 0;
3226
3227         if (curTarg != NULL && !Targ_Precious(curTarg)) {
3228                 char      *p1;
3229                 char      *file = Var_Value(TARGET, curTarg, &p1);
3230
3231                 if (!noExecute && eunlink(file) != -1) {
3232                         printf("*** %s removed\n", file);
3233                 }
3234                 free(p1);
3235         }
3236
3237         /*
3238          * Run .INTERRUPT only if hit with interrupt signal
3239          */
3240         if (signo == SIGINT) {
3241                 gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
3242                 if (gn != NULL) {
3243                         LST_FOREACH(ln, &gn->commands) {
3244                                 if (Compat_RunCommand(Lst_Datum(ln), gn))
3245                                         break;
3246                         }
3247                 }
3248         }
3249
3250         sigprocmask(SIG_SETMASK, &omask, NULL);
3251
3252         if (signo == SIGQUIT)
3253                 exit(signo);
3254         signal(signo, SIG_DFL);
3255         kill(getpid(), signo);
3256 }
3257
3258 /*-
3259  *-----------------------------------------------------------------------
3260  * Compat_RunCommand --
3261  *      Execute the next command for a target. If the command returns an
3262  *      error, the node's made field is set to ERROR and creation stops.
3263  *      The node from which the command came is also given.
3264  *
3265  * Results:
3266  *      0 if the command succeeded, 1 if an error occurred.
3267  *
3268  * Side Effects:
3269  *      The node's 'made' field may be set to ERROR.
3270  *
3271  *-----------------------------------------------------------------------
3272  */
3273 int
3274 Compat_RunCommand(char *cmd, GNode *gn)
3275 {
3276         char    *cmdStart;      /* Start of expanded command */
3277         char    *cp;
3278         Boolean silent;         /* Don't print command */
3279         Boolean doit;           /* Execute even in -n */
3280         Boolean errCheck;       /* Check errors */
3281         int     reason;         /* Reason for child's death */
3282         int     status;         /* Description of child's death */
3283         LstNode *cmdNode;       /* Node where current command is located */
3284         char    **av;           /* Argument vector for thing to exec */
3285         char    *cmd_save;      /* saved cmd */
3286         ProcStuff       ps;
3287
3288         silent = gn->type & OP_SILENT;
3289         errCheck = !(gn->type & OP_IGNORE);
3290         doit = FALSE;
3291
3292         cmdNode = Lst_Member(&gn->commands, cmd);
3293         cmdStart = Buf_Peel(Var_Subst(cmd, gn, FALSE));
3294
3295         /*
3296          * brk_string will return an argv with a NULL in av[0], thus causing
3297          * execvp() to choke and die horribly. Besides, how can we execute a
3298          * null command? In any case, we warn the user that the command
3299          * expanded to nothing (is this the right thing to do?).
3300          */
3301         if (*cmdStart == '\0') {
3302                 free(cmdStart);
3303                 Error("%s expands to empty string", cmd);
3304                 return (0);
3305         } else {
3306                 cmd = cmdStart;
3307         }
3308         Lst_Replace(cmdNode, cmdStart);
3309
3310         if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
3311                 Lst_AtEnd(&ENDNode->commands, cmdStart);
3312                 return (0);
3313         } else if (strcmp(cmdStart, "...") == 0) {
3314                 gn->type |= OP_SAVE_CMDS;
3315                 return (0);
3316         }
3317
3318         while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
3319                 switch (*cmd) {
3320
3321                   case '@':
3322                         silent = DEBUG(LOUD) ? FALSE : TRUE;
3323                         break;
3324
3325                   case '-':
3326                         errCheck = FALSE;
3327                         break;
3328
3329                 case '+':
3330                         doit = TRUE;
3331                         if (!meta[0])           /* we came here from jobs */
3332                                 CompatInit();
3333                         break;
3334                 }
3335                 cmd++;
3336         }
3337
3338         while (isspace((unsigned char)*cmd))
3339                 cmd++;
3340
3341         /*
3342          * Print the command before echoing if we're not supposed to be quiet
3343          * for this one. We also print the command if -n given, but not if '+'.
3344          */
3345         if (!silent || (noExecute && !doit)) {
3346                 printf("%s\n", cmd);
3347                 fflush(stdout);
3348         }
3349
3350         /*
3351          * If we're not supposed to execute any commands, this is as far as
3352          * we go...
3353          */
3354         if (!doit && noExecute) {
3355                 return (0);
3356         }
3357
3358         /*
3359          * Search for meta characters in the command. If there are no meta
3360          * characters, there's no need to execute a shell to execute the
3361          * command.
3362          */
3363         for (cp = cmd; !meta[(unsigned char)*cp]; cp++)
3364                 continue;
3365
3366         if (*cp != '\0') {
3367                 /*
3368                  * If *cp isn't the null character, we hit a "meta" character
3369                  * and need to pass the command off to the shell.
3370                  */
3371                 av = NULL;
3372
3373         } else {
3374                 const char **p;
3375                 const char *sh_builtin[] = {
3376                         "alias", "cd", "eval", "exec",
3377                         "exit", "read", "set", "ulimit",
3378                         "unalias", "umask", "unset", "wait",
3379                         ":", NULL
3380                 };
3381
3382                 /*
3383                  * Break the command into words to form an argument
3384                  * vector we can execute. brk_string sticks our name
3385                  * in av[0], so we have to skip over it...
3386                  */
3387                 av = brk_string(cmd, NULL, TRUE);
3388                 av += 1;
3389
3390                 for (p = sh_builtin; *p != 0; p++) {
3391                         if (strcmp(av[0], *p) == 0) {
3392                                 /*
3393                                  * This command must be passed by the shell
3394                                  * for other reasons.. or.. possibly not at
3395                                  * all.
3396                                  */
3397                                 av = NULL;
3398                                 break;
3399                         }
3400                 }
3401         }
3402
3403         ps.in = STDIN_FILENO;
3404         ps.out = STDOUT_FILENO;
3405         ps.err = STDERR_FILENO;
3406
3407         ps.merge_errors = 0;
3408         ps.pgroup = 0;
3409         ps.searchpath = 1;
3410
3411         if (av == NULL) {
3412                 /*
3413                  * We give the shell the -e flag as well as -c if it's
3414                  * supposed to exit when it hits an error.
3415                  */
3416                 ps.argv = emalloc(4 * sizeof(char *));
3417                 ps.argv[0] = strdup(shellName);
3418                 ps.argv[1] = strdup(errCheck ? "-ec" : "-c");
3419                 ps.argv[2] = strdup(cmd);
3420                 ps.argv[3] = NULL;
3421         } else {
3422                 ps.argv = av;
3423         }
3424
3425         /*
3426          * Fork and execute the single command. If the fork fails, we abort.
3427          * Warning since we are doing vfork() instead of fork(),
3428          * do not allocate memory in the child process!
3429          */
3430         if ((ps.child_pid = vfork()) == -1) {
3431                 Fatal("Could not fork");
3432
3433         } else if (ps.child_pid == 0) {
3434                 /*
3435                  * Child
3436                  */
3437                 ProcExec(&ps);
3438                 /* NOTREACHED */
3439
3440         } else {
3441                 if (av == NULL) {
3442                         free(ps.argv[2]);
3443                         free(ps.argv[1]);
3444                         free(ps.argv[0]);
3445                         free(ps.argv);
3446                 }
3447
3448                 /*
3449                  * we need to print out the command associated with this
3450                  * Gnode in Targ_PrintCmd from Targ_PrintGraph when debugging
3451                  * at level g2, in main(), Fatal() and DieHorribly(),
3452                  * therefore do not free it when debugging.
3453                  */
3454                 if (!DEBUG(GRAPH2)) {
3455                         free(cmdStart);
3456                         Lst_Replace(cmdNode, cmd_save);
3457                 }
3458
3459                 /*
3460                  * The child is off and running. Now all we can do is wait...
3461                  */
3462                 reason = ProcWait(&ps);
3463
3464                 if (interrupted)
3465                         CompatInterrupt(interrupted);
3466
3467                 /*
3468                  * Deocde and report the reason child exited, then
3469                  * indicate how we handled it.
3470                  */
3471                 if (WIFEXITED(reason)) {
3472                         status = WEXITSTATUS(reason);
3473                         if (status == 0) {
3474                                 return (0);
3475                         } else {
3476                                 printf("*** Error code %d", status);
3477                         }
3478                 } else if (WIFSTOPPED(reason)) {
3479                         status = WSTOPSIG(reason);
3480                 } else {
3481                         status = WTERMSIG(reason);
3482                         printf("*** Signal %d", status);
3483                 }
3484
3485                 if (errCheck) {
3486                         gn->made = ERROR;
3487                         if (keepgoing) {
3488                                 /*
3489                                  * Abort the current
3490                                  * target, but let
3491                                  * others continue.
3492                                  */
3493                                 printf(" (continuing)\n");
3494                         }
3495                         return (status);
3496                 } else {
3497                         /*
3498                          * Continue executing
3499                          * commands for this target.
3500                          * If we return 0, this will
3501                          * happen...
3502                          */
3503                         printf(" (ignored)\n");
3504                         return (0);
3505                 }
3506         }
3507 }
3508
3509 /*-
3510  *-----------------------------------------------------------------------
3511  * CompatMake --
3512  *      Make a target, given the parent, to abort if necessary.
3513  *
3514  * Side Effects:
3515  *      If an error is detected and not being ignored, the process exits.
3516  *
3517  *-----------------------------------------------------------------------
3518  */
3519 static int
3520 CompatMake(GNode *gn, GNode *pgn)
3521 {
3522         LstNode *ln;
3523
3524         if (gn->type & OP_USE) {
3525                 Make_HandleUse(gn, pgn);
3526
3527         } else if (gn->made == UNMADE) {
3528                 /*
3529                  * First mark ourselves to be made, then apply whatever
3530                  * transformations the suffix module thinks are necessary.
3531                  * Once that's done, we can descend and make all our children.
3532                  * If any of them has an error but the -k flag was given, our
3533                  * 'make' field will be set FALSE again. This is our signal to
3534                  * not attempt to do anything but abort our parent as well.
3535                  */
3536                 gn->make = TRUE;
3537                 gn->made = BEINGMADE;
3538                 Suff_FindDeps(gn);
3539                 LST_FOREACH(ln, &gn->children)
3540                         CompatMake(Lst_Datum(ln), gn);
3541                 if (!gn->make) {
3542                         gn->made = ABORTED;
3543                         pgn->make = FALSE;
3544                         return (0);
3545                 }
3546
3547                 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3548                         char *p1;
3549                         Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
3550                         free(p1);
3551                 }
3552
3553                 /*
3554                  * All the children were made ok. Now cmtime contains the
3555                  * modification time of the newest child, we need to find out
3556                  * if we exist and when we were modified last. The criteria for
3557                  * datedness are defined by the Make_OODate function.
3558                  */
3559                 DEBUGF(MAKE, ("Examining %s...", gn->name));
3560                 if (!Make_OODate(gn)) {
3561                         gn->made = UPTODATE;
3562                         DEBUGF(MAKE, ("up-to-date.\n"));
3563                         return (0);
3564                 } else {
3565                         DEBUGF(MAKE, ("out-of-date.\n"));
3566                 }
3567
3568                 /*
3569                  * If the user is just seeing if something is out-of-date,
3570                  * exit now to tell him/her "yes".
3571                  */
3572                 if (queryFlag) {
3573                         exit(1);
3574                 }
3575
3576                 /*
3577                  * We need to be re-made. We also have to make sure we've got
3578                  * a $? variable. To be nice, we also define the $> variable
3579                  * using Make_DoAllVar().
3580                  */
3581                 Make_DoAllVar(gn);
3582
3583                 /*
3584                  * Alter our type to tell if errors should be ignored or things
3585                  * should not be printed so Compat_RunCommand knows what to do.
3586                  */
3587                 if (Targ_Ignore(gn)) {
3588                         gn->type |= OP_IGNORE;
3589                 }
3590                 if (Targ_Silent(gn)) {
3591                         gn->type |= OP_SILENT;
3592                 }
3593
3594                 if (Job_CheckCommands(gn, Fatal)) {
3595                         /*
3596                          * Our commands are ok, but we still have to worry
3597                          * about the -t flag...
3598                          */
3599                         if (!touchFlag) {
3600                                 curTarg = gn;
3601                                 LST_FOREACH(ln, &gn->commands) {
3602                                         if (Compat_RunCommand(Lst_Datum(ln),
3603                                             gn))
3604                                                 break;
3605                                 }
3606                                 curTarg = NULL;
3607                         } else {
3608                                 Job_Touch(gn, gn->type & OP_SILENT);
3609                         }
3610                 } else {
3611                         gn->made = ERROR;
3612                 }
3613
3614                 if (gn->made != ERROR) {
3615                         /*
3616                          * If the node was made successfully, mark it so, update
3617                          * its modification time and timestamp all its parents.
3618                          * Note that for .ZEROTIME targets, the timestamping
3619                          * isn't done. This is to keep its state from affecting
3620                          * that of its parent.
3621                          */
3622                         gn->made = MADE;
3623 #ifndef RECHECK
3624                         /*
3625                          * We can't re-stat the thing, but we can at least take
3626                          * care of rules where a target depends on a source that
3627                          * actually creates the target, but only if it has
3628                          * changed, e.g.
3629                          *
3630                          * parse.h : parse.o
3631                          *
3632                          * parse.o : parse.y
3633                          *      yacc -d parse.y
3634                          *      cc -c y.tab.c
3635                          *      mv y.tab.o parse.o
3636                          *      cmp -s y.tab.h parse.h || mv y.tab.h parse.h
3637                          *
3638                          * In this case, if the definitions produced by yacc
3639                          * haven't changed from before, parse.h won't have been
3640                          * updated and gn->mtime will reflect the current
3641                          * modification time for parse.h. This is something of a
3642                          * kludge, I admit, but it's a useful one..
3643                          *
3644                          * XXX: People like to use a rule like
3645                          *
3646                          * FRC:
3647                          *
3648                          * To force things that depend on FRC to be made, so we
3649                          * have to check for gn->children being empty as well...
3650                          */
3651                         if (!Lst_IsEmpty(&gn->commands) ||
3652                             Lst_IsEmpty(&gn->children)) {
3653                                 gn->mtime = now;
3654                         }
3655 #else
3656                         /*
3657                          * This is what Make does and it's actually a good
3658                          * thing, as it allows rules like
3659                          *
3660                          *      cmp -s y.tab.h parse.h || cp y.tab.h parse.h
3661                          *
3662                          * to function as intended. Unfortunately, thanks to
3663                          * the stateless nature of NFS (and the speed of this
3664                          * program), there are times when the modification time
3665                          * of a file created on a remote machine will not be
3666                          * modified before the stat() implied by the Dir_MTime
3667                          * occurs, thus leading us to believe that the file
3668                          * is unchanged, wreaking havoc with files that depend
3669                          * on this one.
3670                          *
3671                          * I have decided it is better to make too much than to
3672                          * make too little, so this stuff is commented out
3673                          * unless you're sure it's ok.
3674                          * -- ardeb 1/12/88
3675                          */
3676                         if (noExecute || Dir_MTime(gn) == 0) {
3677                                 gn->mtime = now;
3678                         }
3679                         if (gn->cmtime > gn->mtime)
3680                                 gn->mtime = gn->cmtime;
3681                         DEBUGF(MAKE, ("update time: %s\n",
3682                             Targ_FmtTime(gn->mtime)));
3683 #endif
3684                         if (!(gn->type & OP_EXEC)) {
3685                                 pgn->childMade = TRUE;
3686                                 Make_TimeStamp(pgn, gn);
3687                         }
3688
3689                 } else if (keepgoing) {
3690                         pgn->make = FALSE;
3691
3692                 } else {
3693                         char *p1;
3694
3695                         printf("\n\nStop in %s.\n",
3696                             Var_Value(".CURDIR", gn, &p1));
3697                         free(p1);
3698                         exit(1);
3699                 }
3700         } else if (gn->made == ERROR) {
3701                 /*
3702                  * Already had an error when making this beastie. Tell the
3703                  * parent to abort.
3704                  */
3705                 pgn->make = FALSE;
3706         } else {
3707                 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3708                         char *p1;
3709                         Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
3710                         free(p1);
3711                 }
3712                 switch(gn->made) {
3713                   case BEINGMADE:
3714                         Error("Graph cycles through %s\n", gn->name);
3715                         gn->made = ERROR;
3716                         pgn->make = FALSE;
3717                         break;
3718                   case MADE:
3719                         if ((gn->type & OP_EXEC) == 0) {
3720                             pgn->childMade = TRUE;
3721                             Make_TimeStamp(pgn, gn);
3722                         }
3723                         break;
3724                   case UPTODATE:
3725                         if ((gn->type & OP_EXEC) == 0) {
3726                             Make_TimeStamp(pgn, gn);
3727                         }
3728                         break;
3729                   default:
3730                         break;
3731                 }
3732         }
3733
3734         return (0);
3735 }
3736
3737 /*-
3738  *-----------------------------------------------------------------------
3739  * Compat_Run --
3740  *      Start making again, given a list of target nodes.
3741  *
3742  * Results:
3743  *      None.
3744  *
3745  * Side Effects:
3746  *      Guess what?
3747  *
3748  *-----------------------------------------------------------------------
3749  */
3750 void
3751 Compat_Run(Lst *targs)
3752 {
3753         GNode   *gn = NULL;     /* Current root target */
3754         int     error_cnt;              /* Number of targets not remade due to errors */
3755         LstNode *ln;
3756
3757         CompatInit();
3758         Shell_Init();           /* Set up shell. */
3759
3760         if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
3761                 signal(SIGINT, CompatCatchSig);
3762         }
3763         if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
3764                 signal(SIGTERM, CompatCatchSig);
3765         }
3766         if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
3767                 signal(SIGHUP, CompatCatchSig);
3768         }
3769         if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
3770                 signal(SIGQUIT, CompatCatchSig);
3771         }
3772
3773         ENDNode = Targ_FindNode(".END", TARG_CREATE);
3774         /*
3775          * If the user has defined a .BEGIN target, execute the commands
3776          * attached to it.
3777         */
3778         if (!queryFlag) {
3779                 gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
3780                 if (gn != NULL) {
3781                         LST_FOREACH(ln, &gn->commands) {
3782                                 if (Compat_RunCommand(Lst_Datum(ln), gn))
3783                                         break;
3784                         }
3785                         if (gn->made == ERROR) {
3786                                 printf("\n\nStop.\n");
3787                                 exit(1);
3788                         }
3789                 }
3790         }
3791
3792         /*
3793          * For each entry in the list of targets to create, call CompatMake on
3794          * it to create the thing. CompatMake will leave the 'made' field of gn
3795          * in one of several states:
3796          *      UPTODATE  gn was already up-to-date
3797          *      MADE      gn was recreated successfully
3798          *      ERROR     An error occurred while gn was being created
3799          *      ABORTED   gn was not remade because one of its inferiors
3800          *                could not be made due to errors.
3801          */
3802         error_cnt = 0;
3803         while (!Lst_IsEmpty(targs)) {
3804                 gn = Lst_DeQueue(targs);
3805                 CompatMake(gn, gn);
3806
3807                 if (gn->made == UPTODATE) {
3808                         printf("`%s' is up to date.\n", gn->name);
3809                 } else if (gn->made == ABORTED) {
3810                         printf("`%s' not remade because of errors.\n",
3811                             gn->name);
3812                         error_cnt += 1;
3813                 }
3814         }
3815
3816         /*
3817          * If the user has defined a .END target, run its commands.
3818          */
3819         if (error_cnt == 0) {
3820                 LST_FOREACH(ln, &ENDNode->commands) {
3821                         if (Compat_RunCommand(Lst_Datum(ln), gn))
3822                                 break;
3823                 }
3824         }
3825 }