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