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