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