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