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