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