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