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