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