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