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