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