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