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