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
8 * This code is derived from software contributed to Berkeley by
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
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.
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
39 * @(#)job.c 8.2 (Berkeley) 3/19/94
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
51 * handle the creation etc. of our child processes.
54 * Job_Make Start the creation of the given target.
57 * Check for and handle the termination of any children.
58 * This must be called reasonably frequently to keep the
59 * whole make going at a decent clip, since job table
60 * entries aren't removed until their process is caught
61 * this way. Its single argument is TRUE if the function
62 * should block waiting for a child to terminate.
64 * Job_CatchOutput Print any output our children have produced. Should
65 * also be called fairly frequently to keep the user
66 * informed of what's going on. If no output is waiting,
67 * it will block for a time given by the SEL_* constants,
68 * below, or until output is ready.
70 * Job_Init Called to intialize this module. in addition, any
71 * commands attached to the .BEGIN target are executed
72 * before this function returns. Hence, the makefile must
73 * have been parsed before this function is called.
75 * Job_Full Return TRUE if the job table is filled.
77 * Job_Empty Return TRUE if the job table is completely empty.
79 * Job_Finish Perform any final processing which needs doing. This
80 * includes the execution of any commands which have
81 * been/were attached to the .END target. It should only
82 * be called when the job table is empty.
84 * Job_AbortAll Abort all currently running jobs. It doesn't handle
85 * output or do anything for the jobs, just kills them.
86 * It should only be called in an emergency, as it were.
89 * Verify that the commands for a target are ok. Provide
90 * them if necessary and possible.
92 * Job_Touch Update a target without really updating it.
94 * Job_Wait Wait for all currently-running jobs to finish.
97 * The routines in this file implement the full-compatibility
98 * mode of PMake. Most of the special functionality of PMake
99 * is available in this mode. Things not supported:
100 * - different shells.
101 * - friendly variable substitution.
104 * Compat_Run Initialize things for this module and recreate
105 * thems as need creatin'
108 #include <sys/queue.h>
109 #include <sys/types.h>
110 #include <sys/select.h>
111 #include <sys/stat.h>
113 #include <sys/event.h>
115 #include <sys/wait.h>
120 #include <inttypes.h>
144 #define TMPPAT "/tmp/makeXXXXXXXXXX"
148 * The SEL_ constants determine the maximum amount of time spent in select
149 * before coming out to see if a child has finished. SEL_SEC is the number of
150 * seconds and SEL_USEC is the number of micro-seconds
154 #endif /* !USE_KQUEUE */
157 * Job Table definitions.
159 * The job "table" is kept as a linked Lst in 'jobs', with the number of
160 * active jobs maintained in the 'nJobs' variable. At no time will this
161 * exceed the value of 'maxJobs', initialized by the Job_Init function.
163 * When a job is finished, the Make_Update function is called on each of the
164 * parents of the node which was just remade. This takes care of the upward
165 * traversal of the dependency graph.
167 #define JOB_BUFSIZE 1024
169 pid_t pid; /* The child's process ID */
171 struct GNode *node; /* The target the child is making */
174 * A LstNode for the first command to be saved after the job completes.
175 * This is NULL if there was no "..." in the job's commands.
180 * An FILE* for writing out the commands. This is only
181 * used before the job is actually started.
186 * A word of flags which determine how the module handles errors,
187 * echoing, etc. for the job
189 short flags; /* Flags to control treatment of job */
190 #define JOB_IGNERR 0x001 /* Ignore non-zero exits */
191 #define JOB_SILENT 0x002 /* no output */
192 #define JOB_SPECIAL 0x004 /* Target is a special one. i.e. run it locally
193 * if we can't export it and maxLocal is 0 */
194 #define JOB_IGNDOTS 0x008 /* Ignore "..." lines when processing
196 #define JOB_FIRST 0x020 /* Job is first job for the node */
197 #define JOB_RESTART 0x080 /* Job needs to be completely restarted */
198 #define JOB_RESUME 0x100 /* Job needs to be resumed b/c it stopped,
200 #define JOB_CONTINUING 0x200 /* We are in the process of resuming this job.
201 * Used to avoid infinite recursion between
202 * JobFinish and JobRestart */
204 /* union for handling shell's output */
207 * This part is used when usePipes is true.
208 * The output is being caught via a pipe and the descriptors
209 * of our pipe, an array in which output is line buffered and
210 * the current position in that buffer are all maintained for
215 * Input side of pipe associated with
216 * job's output channel
221 * Output side of pipe associated with job's
227 * Buffer for storing the output of the
230 char op_outBuf[JOB_BUFSIZE + 1];
232 /* Current position in op_outBuf */
237 * If usePipes is false the output is routed to a temporary
238 * file and all that is kept is the name of the file and the
239 * descriptor open to the file.
242 /* Name of file to which shell output was rerouted */
243 char of_outFile[sizeof(TMPPAT)];
246 * Stream open to the output file. Used to funnel all
247 * from a single job to one file while still allowing
248 * multiple shell invocations
253 } output; /* Data for tracking a shell's output */
255 TAILQ_ENTRY(Job) link; /* list link */
258 #define outPipe output.o_pipe.op_outPipe
259 #define inPipe output.o_pipe.op_inPipe
260 #define outBuf output.o_pipe.op_outBuf
261 #define curPos output.o_pipe.op_curPos
262 #define outFile output.o_file.of_outFile
263 #define outFd output.o_file.of_outFd
265 TAILQ_HEAD(JobList, Job);
268 * error handling variables
270 static int errors = 0; /* number of errors reported */
271 static int aborting = 0; /* why is the make aborting? */
272 #define ABORT_ERROR 1 /* Because of an error */
273 #define ABORT_INTERRUPT 2 /* Because it was interrupted */
274 #define ABORT_WAIT 3 /* Waiting for jobs to finish */
277 * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
278 * is a char! So when we go above 127 we turn negative!
280 #define FILENO(a) ((unsigned)fileno(a))
283 * post-make command processing. The node postCommands is really just the
284 * .END target but we keep it around to avoid having to search for it
287 static GNode *postCommands;
290 * The number of commands actually printed for a target. Should this
291 * number be 0, no shell will be executed.
293 static int numCommands;
296 * Return values from JobStart.
298 #define JOB_RUNNING 0 /* Job is running */
299 #define JOB_ERROR 1 /* Error in starting the job */
300 #define JOB_FINISHED 2 /* The job is already finished */
301 #define JOB_STOPPED 3 /* The job is stopped */
304 * The maximum number of jobs that may run. This is initialize from the
305 * -j argument for the leading make and from the FIFO for sub-makes.
309 static int nJobs; /* The number of children currently running */
311 /* The structures that describe them */
312 static struct JobList jobs = TAILQ_HEAD_INITIALIZER(jobs);
314 static Boolean jobFull; /* Flag to tell when the job table is full. It
315 * is set TRUE when (1) the total number of
316 * running jobs equals the maximum allowed */
318 static int kqfd; /* File descriptor obtained by kqueue() */
320 static fd_set outputs; /* Set of descriptors of pipes connected to
321 * the output channels of children */
324 static GNode *lastNode; /* The node for which output was most recently
326 static const char *targFmt; /* Format string to use to head output from a
327 * job when it's not the most-recent job heard
330 #define TARG_FMT "--- %s ---\n" /* Default format */
331 #define MESSAGE(fp, gn) \
332 fprintf(fp, targFmt, gn->name);
335 * When JobStart attempts to run a job but isn't allowed to
336 * or when Job_CatchChildren detects a job that has
337 * been stopped somehow, the job is placed on the stoppedJobs queue to be run
338 * when the next job finishes.
340 * Lst of Job structures describing jobs that were stopped due to
341 * concurrency limits or externally
343 static struct JobList stoppedJobs = TAILQ_HEAD_INITIALIZER(stoppedJobs);
345 static int fifoFd; /* Fd of our job fifo */
346 static char fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
347 static int fifoMaster;
349 static sig_atomic_t interrupted;
352 #if defined(USE_PGRP) && defined(SYSV)
353 # define KILL(pid, sig) killpg(-(pid), (sig))
355 # if defined(USE_PGRP)
356 # define KILL(pid, sig) killpg((pid), (sig))
358 # define KILL(pid, sig) kill((pid), (sig))
363 * Grmpf... There is no way to set bits of the wait structure
364 * anymore with the stupid W*() macros. I liked the union wait
365 * stuff much more. So, we devise our own macros... This is
366 * really ugly, use dramamine sparingly. You have been warned.
368 #define W_SETMASKED(st, val, fun) \
371 int mask = fun(sh); \
373 for (sh = 0; ((mask >> sh) & 1) == 0; sh++) \
375 *(st) = (*(st) & ~mask) | ((val) << sh); \
378 #define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
379 #define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
381 static void JobRestart(Job *);
382 static int JobStart(GNode *, int, Job *);
383 static void JobDoOutput(Job *, Boolean);
384 static void JobInterrupt(int, int);
385 static void JobRestartJobs(void);
386 static int Compat_RunCommand(char *, struct GNode *);
388 static GNode *curTarg = NULL;
389 static GNode *ENDNode;
392 * Create a fifo file with a uniq filename, and returns a file
393 * descriptor to that fifo.
396 mkfifotemp(char *template)
401 const unsigned char padchar[] =
402 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
404 if (template[0] == '\0') {
405 errno = EINVAL; /* bad input string */
409 /* Find end of template string. */
410 pathend = strchr(template, '\0');
414 * Starting from the end of the template replace spaces with 'X' in
415 * them with random characters until there are no more 'X'.
417 while (ptr >= template && *ptr == 'X') {
418 uint32_t rand_num = arc4random() % (sizeof(padchar) - 1);
419 *ptr-- = padchar[rand_num];
423 /* Check the target directory. */
424 for (; ptr > template; --ptr) {
429 if (stat(template, &sbuf) != 0)
432 if (!S_ISDIR(sbuf.st_mode)) {
442 if (mkfifo(template, 0600) == 0) {
445 if ((fd = open(template, O_RDWR, 0600)) < 0) {
452 if (errno != EEXIST) {
458 * If we have a collision, cycle through the space of
461 for (ptr = start;;) {
464 if (*ptr == '\0' || ptr == pathend)
467 pad = strchr(padchar, *ptr);
468 if (pad == NULL || *++pad == '\0') {
480 catch_child(int sig __unused)
490 * Catch SIGCHLD so that we get kicked out of select() when we
491 * need to look at a child. This is only known to matter for the
492 * -j case (perhaps without -P).
494 * XXX this is intentionally misplaced.
498 sigemptyset(&sa.sa_mask);
499 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
500 sa.sa_handler = catch_child;
501 sigaction(SIGCHLD, &sa, NULL);
505 * Wait for child process to terminate.
508 ProcWait(ProcStuff *ps)
514 * Wait for the process to exit.
518 if (pid == -1 && errno != EINTR) {
519 Fatal("error in wait: %d", pid);
522 if (pid == ps->child_pid) {
535 * Got a signal. Set global variables and hope that someone will
539 JobCatchSig(int signo)
547 * Pass a signal on to all local jobs if
548 * USE_PGRP is defined, then die ourselves.
551 * We die by the same signal.
554 JobPassSig(int signo)
557 sigset_t nmask, omask;
558 struct sigaction act;
561 sigaddset(&nmask, signo);
562 sigprocmask(SIG_SETMASK, &nmask, &omask);
564 DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
565 TAILQ_FOREACH(job, &jobs, link) {
566 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
567 signo, (intmax_t)job->pid));
568 KILL(job->pid, signo);
572 * Deal with proper cleanup based on the signal received. We only run
573 * the .INTERRUPT target if the signal was in fact an interrupt.
574 * The other three termination signals are more of a "get out *now*"
577 if (signo == SIGINT) {
578 JobInterrupt(TRUE, signo);
579 } else if (signo == SIGHUP || signo == SIGTERM || signo == SIGQUIT) {
580 JobInterrupt(FALSE, signo);
584 * Leave gracefully if SIGQUIT, rather than core dumping.
586 if (signo == SIGQUIT) {
591 * Send ourselves the signal now we've given the message to everyone
592 * else. Note we block everything else possible while we're getting
593 * the signal. This ensures that all our jobs get continued when we
594 * wake up before we take any other signal.
595 * XXX this comment seems wrong.
597 act.sa_handler = SIG_DFL;
598 sigemptyset(&act.sa_mask);
600 sigaction(signo, &act, NULL);
602 DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
603 ~0 & ~(1 << (signo - 1))));
604 signal(signo, SIG_DFL);
606 KILL(getpid(), signo);
609 TAILQ_FOREACH(job, &jobs, link) {
610 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
611 signo, (intmax_t)job->pid));
612 KILL(job->pid, signo);
615 sigprocmask(SIG_SETMASK, &omask, NULL);
616 sigprocmask(SIG_SETMASK, &omask, NULL);
617 act.sa_handler = JobPassSig;
618 sigaction(signo, &act, NULL);
623 * Put out another command for the given job. If the command starts
624 * with an @ or a - we process it specially. In the former case,
625 * so long as the -s and -n flags weren't given to make, we stick
626 * a shell-specific echoOff command in the script. In the latter,
627 * we ignore errors for the entire job, unless the shell has error
629 * If the command is just "..." we take all future commands for this
630 * job to be commands to be executed once the entire graph has been
631 * made and return non-zero to signal that the end of the commands
632 * was reached. These commands are later attached to the postCommands
633 * node and executed by Job_Finish when all things are done.
634 * This function is called from JobStart via LST_FOREACH.
637 * Always 0, unless the command was "..."
640 * If the command begins with a '-' and the shell has no error control,
641 * the JOB_IGNERR flag is set in the job descriptor.
642 * If the command is "..." and we're not ignoring such things,
643 * tailCmds is set to the successor node of the cmd.
644 * numCommands is incremented if the command is actually printed.
647 JobPrintCommand(char *cmd, Job *job)
649 Boolean noSpecials; /* true if we shouldn't worry about
650 * inserting special commands into
651 * the input stream. */
652 Boolean shutUp = FALSE; /* true if we put a no echo command
653 * into the command file */
654 Boolean errOff = FALSE; /* true if we turned error checking
655 * off before printing the command
656 * and need to turn it back on */
657 const char *cmdTemplate;/* Template to use when printing the command */
658 char *cmdStart; /* Start of expanded command */
659 LstNode *cmdNode; /* Node for replacing the command */
661 noSpecials = (noExecute && !(job->node->type & OP_MAKE));
663 if (strcmp(cmd, "...") == 0) {
664 job->node->type |= OP_SAVE_CMDS;
665 if ((job->flags & JOB_IGNDOTS) == 0) {
667 Lst_Succ(Lst_Member(&job->node->commands, cmd));
673 #define DBPRINTF(fmt, arg) \
674 DEBUGF(JOB, (fmt, arg)); \
675 fprintf(job->cmdFILE, fmt, arg); \
676 fflush(job->cmdFILE);
681 * For debugging, we replace each command with the result of expanding
682 * the variables in the command.
684 cmdNode = Lst_Member(&job->node->commands, cmd);
686 cmd = Buf_Peel(Var_Subst(cmd, job->node, FALSE));
689 Lst_Replace(cmdNode, cmdStart);
691 cmdTemplate = "%s\n";
694 * Check for leading @', -' or +'s to control echoing, error checking,
695 * and execution on -n.
697 while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
701 shutUp = DEBUG(LOUD) ? FALSE : TRUE;
711 * We're not actually exececuting anything...
712 * but this one needs to be - use compat mode
715 Compat_RunCommand(cmd, job->node);
723 while (isspace((unsigned char)*cmd))
727 if (!(job->flags & JOB_SILENT) && !noSpecials &&
728 commandShell->hasEchoCtl) {
729 DBPRINTF("%s\n", commandShell->echoOff);
736 if (!(job->flags & JOB_IGNERR) && !noSpecials) {
737 if (commandShell->hasErrCtl) {
739 * We don't want the error-control commands
740 * showing up either, so we turn off echoing
741 * while executing them. We could put another
742 * field in the shell structure to tell
743 * JobDoOutput to look for this string too,
744 * but why make it any more complex than
747 if (!(job->flags & JOB_SILENT) && !shutUp &&
748 commandShell->hasEchoCtl) {
749 DBPRINTF("%s\n", commandShell->echoOff);
750 DBPRINTF("%s\n", commandShell->ignErr);
751 DBPRINTF("%s\n", commandShell->echoOn);
753 DBPRINTF("%s\n", commandShell->ignErr);
755 } else if (commandShell->ignErr &&
756 *commandShell->ignErr != '\0') {
758 * The shell has no error control, so we need to
759 * be weird to get it to ignore any errors from
760 * the command. If echoing is turned on, we turn
761 * it off and use the errCheck template to echo
762 * the command. Leave echoing off so the user
763 * doesn't see the weirdness we go through to
764 * ignore errors. Set cmdTemplate to use the
765 * weirdness instead of the simple "%s\n"
768 if (!(job->flags & JOB_SILENT) && !shutUp &&
769 commandShell->hasEchoCtl) {
770 DBPRINTF("%s\n", commandShell->echoOff);
771 DBPRINTF(commandShell->errCheck, cmd);
774 cmdTemplate = commandShell->ignErr;
776 * The error ignoration (hee hee) is already
777 * taken care of by the ignErr template, so
778 * pretend error checking is still on.
789 DBPRINTF(cmdTemplate, cmd);
793 * If echoing is already off, there's no point in issuing the
794 * echoOff command. Otherwise we issue it and pretend it was on
795 * for the whole command...
797 if (!shutUp && !(job->flags & JOB_SILENT) &&
798 commandShell->hasEchoCtl) {
799 DBPRINTF("%s\n", commandShell->echoOff);
802 DBPRINTF("%s\n", commandShell->errCheck);
805 DBPRINTF("%s\n", commandShell->echoOn);
812 * Called to close both input and output pipes when a job is finished.
815 * The file descriptors associated with the job are closed.
822 #if !defined(USE_KQUEUE)
823 FD_CLR(job->inPipe, &outputs);
825 if (job->outPipe != job->inPipe) {
828 JobDoOutput(job, TRUE);
832 JobDoOutput(job, TRUE);
838 * Do final processing for the given job including updating
839 * parents and starting new jobs as available/necessary. Note
840 * that we pay no attention to the JOB_IGNERR flag here.
841 * This is because when we're called because of a noexecute flag
842 * or something, jstat.w_status is 0 and when called from
843 * Job_CatchChildren, the status is zeroed if it s/b ignored.
846 * Some nodes may be put on the toBeMade queue.
847 * Final commands for the job are placed on postCommands.
849 * If we got an error and are aborting (aborting == ABORT_ERROR) and
850 * the job list is now empty, we are done for the day.
851 * If we recognized an error (errors !=0), we set the aborting flag
852 * to ABORT_ERROR so no more jobs will be started.
855 JobFinish(Job *job, int *status)
860 if (WIFEXITED(*status)) {
861 int job_status = WEXITSTATUS(*status);
865 * Deal with ignored errors in -B mode. We need to
866 * print a message telling of the ignored error as
867 * well as setting status.w_status to 0 so the next
868 * command gets run. To do this, we set done to be
869 * TRUE if in -B mode and the job exited non-zero.
871 if (job_status == 0) {
874 if (job->flags & JOB_IGNERR) {
878 * If it exited non-zero and either we're
879 * doing things our way or we're not ignoring
880 * errors, the job is finished. Similarly, if
881 * the shell died because of a signal the job
882 * is also finished. In these cases, finish
883 * out the job's output before printing the
887 if (job->cmdFILE != NULL &&
888 job->cmdFILE != stdout) {
889 fclose(job->cmdFILE);
894 } else if (WIFSIGNALED(*status)) {
895 if (WTERMSIG(*status) == SIGCONT) {
897 * No need to close things down or anything.
902 * If it exited non-zero and either we're
903 * doing things our way or we're not ignoring
904 * errors, the job is finished. Similarly, if
905 * the shell died because of a signal the job
906 * is also finished. In these cases, finish
907 * out the job's output before printing the
911 if (job->cmdFILE != NULL &&
912 job->cmdFILE != stdout) {
913 fclose(job->cmdFILE);
919 * No need to close things down or anything.
924 if (WIFEXITED(*status)) {
925 if (done || DEBUG(JOB)) {
930 (job->flags & JOB_IGNERR)) {
932 * If output is going to a file and this job
933 * is ignoring errors, arrange to have the
934 * exit status sent to the output file as
937 out = fdopen(job->outFd, "w");
939 Punt("Cannot fdopen");
944 DEBUGF(JOB, ("Process %jd exited.\n",
945 (intmax_t)job->pid));
947 if (WEXITSTATUS(*status) == 0) {
949 if (usePipes && job->node != lastNode) {
950 MESSAGE(out, job->node);
951 lastNode = job->node;
954 "*** Completed successfully\n");
957 if (usePipes && job->node != lastNode) {
958 MESSAGE(out, job->node);
959 lastNode = job->node;
961 fprintf(out, "*** Error code %d%s\n",
962 WEXITSTATUS(*status),
963 (job->flags & JOB_IGNERR) ?
966 if (job->flags & JOB_IGNERR) {
973 } else if (WIFSIGNALED(*status)) {
974 if (done || DEBUG(JOB) || (WTERMSIG(*status) == SIGCONT)) {
979 (job->flags & JOB_IGNERR)) {
981 * If output is going to a file and this job
982 * is ignoring errors, arrange to have the
983 * exit status sent to the output file as
986 out = fdopen(job->outFd, "w");
988 Punt("Cannot fdopen");
993 if (WTERMSIG(*status) == SIGCONT) {
995 * If the beastie has continued, shift the
996 * Job from the stopped list to the running
997 * one (or re-stop it if concurrency is
998 * exceeded) and go and get another child.
1000 if (job->flags & (JOB_RESUME | JOB_RESTART)) {
1001 if (usePipes && job->node != lastNode) {
1002 MESSAGE(out, job->node);
1003 lastNode = job->node;
1005 fprintf(out, "*** Continued\n");
1007 if (!(job->flags & JOB_CONTINUING)) {
1008 DEBUGF(JOB, ("Warning: process %jd was not "
1009 "continuing.\n", (intmax_t) job->pid));
1012 * We don't really want to restart a
1013 * job from scratch just because it
1014 * continued, especially not without
1015 * killing the continuing process!
1016 * That's why this is ifdef'ed out.
1022 job->flags &= ~JOB_CONTINUING;
1023 TAILQ_INSERT_TAIL(&jobs, job, link);
1025 DEBUGF(JOB, ("Process %jd is continuing locally.\n",
1026 (intmax_t) job->pid));
1027 if (nJobs == maxJobs) {
1029 DEBUGF(JOB, ("Job queue is full.\n"));
1035 if (usePipes && job->node != lastNode) {
1036 MESSAGE(out, job->node);
1037 lastNode = job->node;
1040 "*** Signal %d\n", WTERMSIG(*status));
1048 if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
1050 * If output is going to a file and this job
1051 * is ignoring errors, arrange to have the
1052 * exit status sent to the output file as
1055 out = fdopen(job->outFd, "w");
1057 Punt("Cannot fdopen");
1062 DEBUGF(JOB, ("Process %jd stopped.\n", (intmax_t) job->pid));
1063 if (usePipes && job->node != lastNode) {
1064 MESSAGE(out, job->node);
1065 lastNode = job->node;
1067 fprintf(out, "*** Stopped -- signal %d\n", WSTOPSIG(*status));
1068 job->flags |= JOB_RESUME;
1069 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1075 * Now handle the -B-mode stuff. If the beast still isn't finished,
1076 * try and restart the job on the next command. If JobStart says it's
1077 * ok, it's ok. If there's an error, this puppy is done.
1079 if (compatMake && WIFEXITED(*status) &&
1080 Lst_Succ(job->node->compat_command) != NULL) {
1081 switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
1087 W_SETEXITSTATUS(status, 1);
1091 * If we got back a JOB_FINISHED code, JobStart has
1092 * already called Make_Update and freed the job
1093 * descriptor. We set done to false here to avoid fake
1094 * cycles and double frees. JobStart needs to do the
1095 * update so we can proceed up the graph when given
1107 if (done && aborting != ABORT_ERROR &&
1108 aborting != ABORT_INTERRUPT && *status == 0) {
1110 * As long as we aren't aborting and the job didn't return a
1111 * non-zero status that we shouldn't ignore, we call
1112 * Make_Update to update the parents. In addition, any saved
1113 * commands for the node are placed on the .END target.
1115 for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
1116 Lst_AtEnd(&postCommands->commands,
1118 Var_Subst(Lst_Datum(ln), job->node, FALSE)));
1121 job->node->made = MADE;
1122 Make_Update(job->node);
1125 } else if (*status != 0) {
1133 * Set aborting if any error.
1135 if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
1137 * If we found any errors in this batch of children and the -k
1138 * flag wasn't given, we set the aborting flag so no more jobs
1141 aborting = ABORT_ERROR;
1144 if (aborting == ABORT_ERROR && Job_Empty()) {
1146 * If we are aborting and the job table is now empty, we finish.
1154 * Touch the given target. Called by JobStart when the -t flag was
1155 * given. Prints messages unless told to be silent.
1158 * The data modification of the file is changed. In addition, if the
1159 * file did not exist, it is created.
1162 Job_Touch(GNode *gn, Boolean silent)
1164 int streamID; /* ID of stream opened to do the touch */
1165 struct utimbuf times; /* Times for utime() call */
1167 if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
1169 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
1170 * targets and, as such, shouldn't really be created.
1176 fprintf(stdout, "touch %s\n", gn->name);
1184 if (gn->type & OP_ARCHV) {
1186 } else if (gn->type & OP_LIB) {
1189 char *file = gn->path ? gn->path : gn->name;
1191 times.actime = times.modtime = now;
1192 if (utime(file, ×) < 0) {
1193 streamID = open(file, O_RDWR | O_CREAT, 0666);
1195 if (streamID >= 0) {
1199 * Read and write a byte to the file to change
1200 * the modification time, then close the file.
1202 if (read(streamID, &c, 1) == 1) {
1203 lseek(streamID, (off_t)0, SEEK_SET);
1204 write(streamID, &c, 1);
1209 fprintf(stdout, "*** couldn't touch %s: %s",
1210 file, strerror(errno));
1219 * Make sure the given node has all the commands it needs.
1222 * TRUE if the commands list is/was ok.
1225 * The node will have commands from the .DEFAULT rule added to it
1229 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1232 if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
1233 (gn->type & OP_LIB) == 0) {
1235 * No commands. Look for .DEFAULT rule from which we might infer
1238 if (DEFAULT != NULL && !Lst_IsEmpty(&DEFAULT->commands)) {
1240 * Make only looks for a .DEFAULT if the node was
1241 * never the target of an operator, so that's what we
1242 * do too. If a .DEFAULT was given, we substitute its
1243 * commands for gn's commands and set the IMPSRC
1244 * variable to be the target's name The DEFAULT node
1245 * acts like a transformation rule, in that gn also
1246 * inherits any attributes or sources attached to
1249 Make_HandleUse(DEFAULT, gn);
1250 Var_Set(IMPSRC, Var_Value(TARGET, gn), gn);
1252 } else if (Dir_MTime(gn) == 0) {
1254 * The node wasn't the target of an operator we have
1255 * no .DEFAULT rule to go on and the target doesn't
1256 * already exist. There's nothing more we can do for
1257 * this branch. If the -k flag wasn't given, we stop
1258 * in our tracks, otherwise we just don't update
1259 * this node's parents so they never get examined.
1261 static const char msg[] =
1262 "make: don't know how to make";
1264 if (gn->type & OP_OPTIONAL) {
1265 fprintf(stdout, "%s %s(ignored)\n",
1268 } else if (keepgoing) {
1269 fprintf(stdout, "%s %s(continuing)\n",
1275 if (strcmp(gn->name,"love") == 0)
1276 (*abortProc)("Not war.");
1279 (*abortProc)("%s %s. Stop",
1290 * Execute the shell for the given job. Called from JobStart and
1294 * A shell is executed, outputs is altered and the Job structure added
1298 JobExec(Job *job, char **argv)
1305 DEBUGF(JOB, ("Running %s\n", job->node->name));
1306 DEBUGF(JOB, ("\tCommand: "));
1307 for (i = 0; argv[i] != NULL; i++) {
1308 DEBUGF(JOB, ("%s ", argv[i]));
1310 DEBUGF(JOB, ("\n"));
1314 * Some jobs produce no output and it's disconcerting to have
1315 * no feedback of their running (since they produce no output, the
1316 * banner with their name in it never appears). This is an attempt to
1317 * provide that feedback, even if nothing follows it.
1319 if (lastNode != job->node && (job->flags & JOB_FIRST) &&
1320 !(job->flags & JOB_SILENT)) {
1321 MESSAGE(stdout, job->node);
1322 lastNode = job->node;
1325 ps.in = FILENO(job->cmdFILE);
1328 * Set up the child's output to be routed through the
1329 * pipe we've created for it.
1331 ps.out = job->outPipe;
1334 * We're capturing output in a file, so we duplicate
1335 * the descriptor to the temporary file into the
1338 ps.out = job->outFd;
1340 ps.err = STDERR_FILENO;
1342 ps.merge_errors = 1;
1350 * Fork. Warning since we are doing vfork() instead of fork(),
1351 * do not allocate memory in the child process!
1353 if ((ps.child_pid = vfork()) == -1) {
1354 Punt("Cannot fork");
1357 } else if (ps.child_pid == 0) {
1371 job->pid = ps.child_pid;
1373 if (usePipes && (job->flags & JOB_FIRST)) {
1375 * The first time a job is run for a node, we set the
1376 * current position in the buffer to the beginning and
1377 * mark another stream to watch in the outputs mask.
1380 struct kevent kev[2];
1384 #if defined(USE_KQUEUE)
1385 EV_SET(&kev[0], job->inPipe, EVFILT_READ, EV_ADD, 0, 0, job);
1386 EV_SET(&kev[1], job->pid, EVFILT_PROC,
1387 EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
1388 if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1390 * kevent() will fail if the job is already
1393 if (errno != EINTR && errno != EBADF && errno != ESRCH)
1394 Punt("kevent: %s", strerror(errno));
1397 FD_SET(job->inPipe, &outputs);
1398 #endif /* USE_KQUEUE */
1401 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1402 fclose(job->cmdFILE);
1403 job->cmdFILE = NULL;
1407 * Now the job is actually running, add it to the table.
1410 TAILQ_INSERT_TAIL(&jobs, job, link);
1411 if (nJobs == maxJobs) {
1418 * Create the argv needed to execute the shell for a given job.
1421 JobMakeArgv(Job *job, char **argv)
1424 static char args[10]; /* For merged arguments */
1426 argv[0] = commandShell->name;
1429 if ((commandShell->exit && *commandShell->exit != '-') ||
1430 (commandShell->echo && *commandShell->echo != '-')) {
1432 * At least one of the flags doesn't have a minus before it, so
1433 * merge them together. Have to do this because the *(&(@*#*&#$#
1434 * Bourne shell thinks its second argument is a file to source.
1435 * Grrrr. Note the ten-character limitation on the combined
1438 sprintf(args, "-%s%s", (job->flags & JOB_IGNERR) ? "" :
1439 commandShell->exit ? commandShell->exit : "",
1440 (job->flags & JOB_SILENT) ? "" :
1441 commandShell->echo ? commandShell->echo : "");
1448 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1449 argv[argc] = commandShell->exit;
1452 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1453 argv[argc] = commandShell->echo;
1462 * Restart a job that stopped for some reason. The job must be neither
1463 * on the jobs nor on the stoppedJobs list.
1466 * jobFull will be set if the job couldn't be run.
1469 JobRestart(Job *job)
1472 if (job->flags & JOB_RESTART) {
1474 * Set up the control arguments to the shell. This is based on
1475 * the flags set earlier for this job. If the JOB_IGNERR flag
1476 * is clear, the 'exit' flag of the commandShell is used to
1477 * cause it to exit upon receiving an error. If the JOB_SILENT
1478 * flag is clear, the 'echo' flag of the commandShell is used
1479 * to get it to start echoing as soon as it starts
1480 * processing commands.
1484 JobMakeArgv(job, argv);
1486 DEBUGF(JOB, ("Restarting %s...", job->node->name));
1487 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL)) {
1489 * Not allowed to run -- put it back on the hold
1490 * queue and mark the table full
1492 DEBUGF(JOB, ("holding\n"));
1493 TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1495 DEBUGF(JOB, ("Job queue is full.\n"));
1499 * Job may be run locally.
1501 DEBUGF(JOB, ("running locally\n"));
1507 * The job has stopped and needs to be restarted.
1508 * Why it stopped, we don't know...
1510 DEBUGF(JOB, ("Resuming %s...", job->node->name));
1511 if ((nJobs < maxJobs || ((job->flags & JOB_SPECIAL) &&
1512 maxJobs == 0)) && nJobs != maxJobs) {
1514 * If we haven't reached the concurrency limit already
1515 * (or the job must be run and maxJobs is 0), it's ok
1521 error = (KILL(job->pid, SIGCONT) != 0);
1525 * Make sure the user knows we've continued
1526 * the beast and actually put the thing in the
1529 job->flags |= JOB_CONTINUING;
1531 W_SETTERMSIG(&status, SIGCONT);
1532 JobFinish(job, &status);
1534 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1535 DEBUGF(JOB, ("done\n"));
1537 Error("couldn't resume %s: %s",
1538 job->node->name, strerror(errno));
1540 W_SETEXITSTATUS(&status, 1);
1541 JobFinish(job, &status);
1545 * Job cannot be restarted. Mark the table as full and
1546 * place the job back on the list of stopped jobs.
1548 DEBUGF(JOB, ("table full\n"));
1549 TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1551 DEBUGF(JOB, ("Job queue is full.\n"));
1558 * Start a target-creation process going for the target described
1559 * by the graph node gn.
1562 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1563 * if there isn't actually anything left to do for the job and
1564 * JOB_RUNNING if the job has been started.
1567 * A new Job node is created and added to the list of running
1568 * jobs. PMake is forked and a child shell created.
1571 JobStart(GNode *gn, int flags, Job *previous)
1573 Job *job; /* new job descriptor */
1574 char *argv[4]; /* Argument vector to shell */
1575 Boolean cmdsOK; /* true if the nodes commands were all right */
1576 Boolean noExec; /* Set true if we decide not to run the job */
1577 int tfd; /* File descriptor for temp file */
1579 char tfile[sizeof(TMPPAT)];
1582 JobPassSig(interrupted);
1585 if (previous != NULL) {
1586 previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1589 job = emalloc(sizeof(Job));
1594 job->tailCmds = NULL;
1597 * Set the initial value of the flags for this job based on the global
1598 * ones and the node's attributes... Any flags supplied by the caller
1599 * are also added to the field.
1602 if (Targ_Ignore(gn)) {
1603 job->flags |= JOB_IGNERR;
1605 if (Targ_Silent(gn)) {
1606 job->flags |= JOB_SILENT;
1608 job->flags |= flags;
1611 * Check the commands now so any attributes from .DEFAULT have a chance
1612 * to migrate to the node.
1614 if (!compatMake && (job->flags & JOB_FIRST)) {
1615 cmdsOK = Job_CheckCommands(gn, Error);
1621 * If the -n flag wasn't given, we open up OUR (not the child's)
1622 * temporary file to stuff commands in it. The thing is rd/wr so we
1623 * don't need to reopen it to feed it to the shell. If the -n flag
1624 * *was* given, we just set the file to be stdout. Cute, huh?
1626 if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1628 * We're serious here, but if the commands were bogus, we're
1635 strcpy(tfile, TMPPAT);
1636 if ((tfd = mkstemp(tfile)) == -1)
1637 Punt("Cannot create temp file: %s", strerror(errno));
1638 job->cmdFILE = fdopen(tfd, "w+");
1640 if (job->cmdFILE == NULL) {
1642 Punt("Could not open %s", tfile);
1644 fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1646 * Send the commands to the command file, flush all its
1647 * buffers then rewind and remove the thing.
1652 * Used to be backwards; replace when start doing multiple
1653 * commands per shell.
1657 * Be compatible: If this is the first time for this
1658 * node, verify its commands are ok and open the
1659 * commands list for sequential access by later
1660 * invocations of JobStart. Once that is done, we take
1661 * the next command off the list and print it to the
1662 * command file. If the command was an ellipsis, note
1663 * that there's nothing more to execute.
1665 if (job->flags & JOB_FIRST)
1666 gn->compat_command = Lst_First(&gn->commands);
1668 gn->compat_command =
1669 Lst_Succ(gn->compat_command);
1671 if (gn->compat_command == NULL ||
1672 JobPrintCommand(Lst_Datum(gn->compat_command), job))
1675 if (noExec && !(job->flags & JOB_FIRST)) {
1677 * If we're not going to execute anything, the
1678 * job is done and we need to close down the
1679 * various file descriptors we've opened for
1680 * output, then call JobDoOutput to catch the
1681 * final characters or send the file to the
1682 * screen... Note that the i/o streams are only
1683 * open if this isn't the first job. Note also
1684 * that this could not be done in
1685 * Job_CatchChildren b/c it wasn't clear if
1686 * there were more commands to execute or not...
1692 * We can do all the commands at once. hooray for sanity
1695 LST_FOREACH(ln, &gn->commands) {
1696 if (JobPrintCommand(Lst_Datum(ln), job))
1701 * If we didn't print out any commands to the shell
1702 * script, there's not much point in executing the
1705 if (numCommands == 0) {
1710 } else if (noExecute) {
1712 * Not executing anything -- just print all the commands to
1713 * stdout in one fell swoop. This will still set up
1714 * job->tailCmds correctly.
1716 if (lastNode != gn) {
1717 MESSAGE(stdout, gn);
1720 job->cmdFILE = stdout;
1723 * Only print the commands if they're ok, but don't die if
1724 * they're not -- just let the user know they're bad and keep
1725 * going. It doesn't do any harm in this case and may do
1729 LST_FOREACH(ln, &gn->commands) {
1730 if (JobPrintCommand(Lst_Datum(ln), job))
1735 * Don't execute the shell, thank you.
1741 * Just touch the target and note that no shell should be
1742 * executed. Set cmdFILE to stdout to make life easier. Check
1743 * the commands, too, but don't die if they're no good -- it
1744 * does no harm to keep working up the graph.
1746 job->cmdFILE = stdout;
1747 Job_Touch(gn, job->flags & JOB_SILENT);
1752 * If we're not supposed to execute a shell, don't.
1756 * Unlink and close the command file if we opened one
1758 if (job->cmdFILE != stdout) {
1759 if (job->cmdFILE != NULL)
1760 fclose(job->cmdFILE);
1766 * We only want to work our way up the graph if we aren't here
1767 * because the commands for the job were no good.
1770 if (aborting == 0) {
1771 for (ln = job->tailCmds; ln != NULL;
1772 ln = LST_NEXT(ln)) {
1773 Lst_AtEnd(&postCommands->commands,
1774 Buf_Peel(Var_Subst(Lst_Datum(ln),
1775 job->node, FALSE)));
1777 job->node->made = MADE;
1778 Make_Update(job->node);
1781 return(JOB_FINISHED);
1787 fflush(job->cmdFILE);
1791 * Set up the control arguments to the shell. This is based on the flags
1792 * set earlier for this job.
1794 JobMakeArgv(job, argv);
1797 * If we're using pipes to catch output, create the pipe by which we'll
1798 * get the shell's output. If we're using files, print out that we're
1799 * starting a job and then set up its temporary-file name.
1801 if (!compatMake || (job->flags & JOB_FIRST)) {
1806 Punt("Cannot create pipe: %s", strerror(errno));
1807 job->inPipe = fd[0];
1808 job->outPipe = fd[1];
1809 fcntl(job->inPipe, F_SETFD, 1);
1810 fcntl(job->outPipe, F_SETFD, 1);
1812 fprintf(stdout, "Remaking `%s'\n", gn->name);
1814 strcpy(job->outFile, TMPPAT);
1815 if ((job->outFd = mkstemp(job->outFile)) == -1)
1816 Punt("cannot create temp file: %s",
1818 fcntl(job->outFd, F_SETFD, 1);
1822 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL) && maxJobs != 0) {
1824 * We've hit the limit of concurrency, so put the job on hold
1825 * until some other job finishes. Note that the special jobs
1826 * (.BEGIN, .INTERRUPT and .END) may be run even when the
1827 * limit has been reached (e.g. when maxJobs == 0).
1831 DEBUGF(JOB, ("Can only run job locally.\n"));
1832 job->flags |= JOB_RESTART;
1833 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1835 if (nJobs >= maxJobs) {
1837 * If we're running this job as a special case
1838 * (see above), at least say the table is full.
1841 DEBUGF(JOB, ("Local job queue is full.\n"));
1845 return (JOB_RUNNING);
1849 JobOutput(Job *job, char *cp, char *endp, int msg)
1853 if (commandShell->noPrint) {
1854 ecp = strstr(cp, commandShell->noPrint);
1855 while (ecp != NULL) {
1858 if (msg && job->node != lastNode) {
1859 MESSAGE(stdout, job->node);
1860 lastNode = job->node;
1863 * The only way there wouldn't be a newline
1864 * after this line is if it were the last in
1865 * the buffer. However, since the non-printable
1866 * comes after it, there must be a newline, so
1867 * we don't print one.
1869 fprintf(stdout, "%s", cp);
1872 cp = ecp + strlen(commandShell->noPrint);
1875 * Still more to print, look again after
1876 * skipping the whitespace following the
1877 * non-printable command....
1880 while (*cp == ' ' || *cp == '\t' ||
1884 ecp = strstr(cp, commandShell->noPrint);
1895 * This function is called at different times depending on
1896 * whether the user has specified that output is to be collected
1897 * via pipes or temporary files. In the former case, we are called
1898 * whenever there is something to read on the pipe. We collect more
1899 * output from the given job and store it in the job's outBuf. If
1900 * this makes up a line, we print it tagged by the job's identifier,
1902 * If output has been collected in a temporary file, we open the
1903 * file and read it line by line, transfering it to our own
1904 * output channel until the file is empty. At which point we
1905 * remove the temporary file.
1906 * In both cases, however, we keep our figurative eye out for the
1907 * 'noPrint' line for the shell from which the output came. If
1908 * we recognize a line, we don't print it. If the command is not
1909 * alone on the line (the character after it is not \0 or \n), we
1910 * do print whatever follows it.
1913 * curPos may be shifted as may the contents of outBuf.
1916 JobDoOutput(Job *job, Boolean finish)
1918 Boolean gotNL = FALSE; /* true if got a newline */
1919 Boolean fbuf; /* true if our buffer filled up */
1920 int nr; /* number of bytes read */
1921 int i; /* auxiliary index into outBuf */
1922 int max; /* limit for i (end of current data) */
1923 int nRead; /* (Temporary) number of bytes read */
1924 FILE *oFILE; /* Stream pointer to shell's output file */
1929 * Read as many bytes as will fit in the buffer.
1935 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1936 JOB_BUFSIZE - job->curPos);
1938 * Check for interrupt here too, because the above read may
1939 * block when the child process is stopped. In this case the
1940 * interrupt will unblock it (we don't use SA_RESTART).
1943 JobPassSig(interrupted);
1946 DEBUGF(JOB, ("JobDoOutput(piperead)"));
1953 * If we hit the end-of-file (the job is dead), we must flush
1954 * its remaining output, so pretend we read a newline if
1955 * there's any output remaining in the buffer.
1956 * Also clear the 'finish' flag so we stop looping.
1958 if (nr == 0 && job->curPos != 0) {
1959 job->outBuf[job->curPos] = '\n';
1962 } else if (nr == 0) {
1967 * Look for the last newline in the bytes we just got. If there
1968 * is one, break out of the loop with 'i' as its index and
1971 max = job->curPos + nr;
1972 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1973 if (job->outBuf[i] == '\n') {
1976 } else if (job->outBuf[i] == '\0') {
1980 job->outBuf[i] = ' ';
1986 if (job->curPos == JOB_BUFSIZE) {
1988 * If we've run out of buffer space, we have
1989 * no choice but to print the stuff. sigh.
1995 if (gotNL || fbuf) {
1997 * Need to send the output to the screen. Null terminate
1998 * it first, overwriting the newline character if there
1999 * was one. So long as the line isn't one we should
2000 * filter (according to the shell description), we print
2001 * the line, preceded by a target banner if this target
2002 * isn't the same as the one for which we last printed
2003 * something. The rest of the data in the buffer are
2004 * then shifted down to the start of the buffer and
2005 * curPos is set accordingly.
2007 job->outBuf[i] = '\0';
2008 if (i >= job->curPos) {
2011 cp = JobOutput(job, job->outBuf,
2012 &job->outBuf[i], FALSE);
2015 * There's still more in that buffer. This time,
2016 * though, we know there's no newline at the
2017 * end, so we add one of our own free will.
2020 if (job->node != lastNode) {
2021 MESSAGE(stdout, job->node);
2022 lastNode = job->node;
2024 fprintf(stdout, "%s%s", cp,
2030 /* shift the remaining characters down */
2031 memcpy(job->outBuf, &job->outBuf[i + 1],
2033 job->curPos = max - (i + 1);
2037 * We have written everything out, so we just
2038 * start over from the start of the buffer.
2039 * No copying. No nothing.
2046 * If the finish flag is true, we must loop until we hit
2047 * end-of-file on the pipe. This is guaranteed to happen
2048 * eventually since the other end of the pipe is now
2049 * closed (we closed it explicitly and the child has
2050 * exited). When we do get an EOF, finish will be set
2051 * FALSE and we'll fall through and out.
2058 * We've been called to retrieve the output of the job from the
2059 * temporary file where it's been squirreled away. This consists
2060 * of opening the file, reading the output line by line, being
2061 * sure not to print the noPrint line for the shell we used,
2062 * then close and remove the temporary file. Very simple.
2064 * Change to read in blocks and do FindSubString type things
2065 * as for pipes? That would allow for "@echo -n..."
2067 oFILE = fopen(job->outFile, "r");
2068 if (oFILE != NULL) {
2069 fprintf(stdout, "Results of making %s:\n",
2073 while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2074 char *cp, *endp, *oendp;
2077 oendp = endp = inLine + strlen(inLine);
2078 if (endp[-1] == '\n') {
2081 cp = JobOutput(job, inLine, endp, FALSE);
2084 * There's still more in that buffer. This time,
2085 * though, we know there's no newline at the
2086 * end, so we add one of our own free will.
2088 fprintf(stdout, "%s", cp);
2090 if (endp != oendp) {
2091 fprintf(stdout, "\n");
2096 eunlink(job->outFile);
2103 * Handle the exit of a child. Called from Make_Make.
2106 * The job descriptor is removed from the list of children.
2109 * We do waits, blocking or not, according to the wisdom of our
2110 * caller, until there are no more children to report. For each
2111 * job, call JobFinish to finish things off. This will take care of
2112 * putting jobs on the stoppedJobs queue.
2115 Job_CatchChildren(Boolean block)
2117 pid_t pid; /* pid of dead child */
2118 Job *job; /* job descriptor for dead child */
2119 int status; /* Exit/termination status */
2122 * Don't even bother if we know there's no one around.
2129 pid = waitpid((pid_t)-1, &status,
2130 (block ? 0 : WNOHANG) | WUNTRACED);
2134 DEBUGF(JOB, ("Process %jd exited or stopped.\n",
2137 TAILQ_FOREACH(job, &jobs, link) {
2138 if (job->pid == pid)
2143 if (WIFSIGNALED(status) &&
2144 (WTERMSIG(status) == SIGCONT)) {
2145 TAILQ_FOREACH(job, &jobs, link) {
2146 if (job->pid == pid)
2150 Error("Resumed child (%jd) "
2151 "not in table", (intmax_t)pid);
2154 TAILQ_REMOVE(&stoppedJobs, job, link);
2156 Error("Child (%jd) not in table?",
2161 TAILQ_REMOVE(&jobs, job, link);
2163 if (fifoFd >= 0 && maxJobs > 1) {
2164 write(fifoFd, "+", 1);
2166 if (nJobs >= maxJobs)
2171 DEBUGF(JOB, ("Job queue is no longer full.\n"));
2176 JobFinish(job, &status);
2179 JobPassSig(interrupted);
2184 * Catch the output from our children, if we're using
2185 * pipes do so. Otherwise just block time until we get a
2186 * signal(most likely a SIGCHLD) since there's no point in
2187 * just spinning when there's nothing to do and the reaping
2188 * of a child can wait for a while.
2191 * Output is read from pipes if we're piping.
2192 * -----------------------------------------------------------------------
2196 Job_CatchOutput(int flag __unused)
2198 Job_CatchOutput(int flag)
2204 struct kevent kev[KEV_SIZE];
2207 struct timeval timeout;
2216 if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
2218 Punt("kevent: %s", strerror(errno));
2220 JobPassSig(interrupted);
2222 for (i = 0; i < nfds; i++) {
2223 if (kev[i].flags & EV_ERROR) {
2224 warnc(kev[i].data, "kevent");
2227 switch (kev[i].filter) {
2229 JobDoOutput(kev[i].udata, FALSE);
2233 * Just wake up and let
2234 * Job_CatchChildren() collect the
2243 timeout.tv_sec = SEL_SEC;
2244 timeout.tv_usec = SEL_USEC;
2245 if (flag && jobFull && fifoFd >= 0)
2246 FD_SET(fifoFd, &readfds);
2248 nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
2249 (fd_set *)NULL, &timeout);
2252 JobPassSig(interrupted);
2255 if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2259 job = TAILQ_FIRST(&jobs);
2260 while (nfds != 0 && job != NULL) {
2261 if (FD_ISSET(job->inPipe, &readfds)) {
2262 JobDoOutput(job, FALSE);
2265 job = TAILQ_NEXT(job, link);
2267 #endif /* !USE_KQUEUE */
2273 * Start the creation of a target. Basically a front-end for
2274 * JobStart used by the Make module.
2277 * Another job is started.
2283 JobStart(gn, 0, NULL);
2288 * Initialize the process module, given a maximum number of jobs.
2291 * lists and counters are initialized
2294 Job_Init(int maxproc)
2296 GNode *begin; /* node for commands to do at the very start */
2298 struct sigaction sa;
2301 env = getenv("MAKE_JOBS_FIFO");
2303 if (env == NULL && maxproc > 1) {
2305 * We did not find the environment variable so we are the
2306 * leader. Create the fifo, open it, write one char per
2307 * allowed job into the pipe.
2309 fifoFd = mkfifotemp(fifoName);
2314 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2316 setenv("MAKE_JOBS_FIFO", env, 1);
2317 while (maxproc-- > 0) {
2318 write(fifoFd, "+", 1);
2320 /* The master make does not get a magic token */
2325 } else if (env != NULL) {
2327 * We had the environment variable so we are a slave.
2328 * Open fifo and give ourselves a magic token which represents
2329 * the token our parent make has grabbed to start his make
2330 * process. Otherwise the sub-makes would gobble up tokens and
2331 * the proper number of tokens to specify to -j would depend
2332 * on the depth of the tree and the order of execution.
2334 fifoFd = open(env, O_RDWR, 0);
2336 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2353 if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2355 * If only one job can run at a time, there's no need for a
2356 * banner, no is there?
2364 * Catch the four signals that POSIX specifies if they aren't ignored.
2365 * JobCatchSignal will just set global variables and hope someone
2366 * else is going to handle the interrupt.
2368 sa.sa_handler = JobCatchSig;
2369 sigemptyset(&sa.sa_mask);
2372 if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2373 sigaction(SIGINT, &sa, NULL);
2375 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2376 sigaction(SIGHUP, &sa, NULL);
2378 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2379 sigaction(SIGQUIT, &sa, NULL);
2381 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2382 sigaction(SIGTERM, &sa, NULL);
2385 * There are additional signals that need to be caught and passed if
2386 * either the export system wants to be told directly of signals or if
2387 * we're giving each job its own process group (since then it won't get
2388 * signals from the terminal driver as we own the terminal)
2390 #if defined(USE_PGRP)
2391 if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2392 sigaction(SIGTSTP, &sa, NULL);
2394 if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2395 sigaction(SIGTTOU, &sa, NULL);
2397 if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2398 sigaction(SIGTTIN, &sa, NULL);
2400 if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2401 sigaction(SIGWINCH, &sa, NULL);
2406 if ((kqfd = kqueue()) == -1) {
2407 Punt("kqueue: %s", strerror(errno));
2411 begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2413 if (begin != NULL) {
2414 JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2417 Job_CatchChildren(!usePipes);
2420 postCommands = Targ_FindNode(".END", TARG_CREATE);
2425 * See if the job table is full. It is considered full if it is OR
2426 * if we are in the process of aborting OR if we have
2427 * reached/exceeded our local quota. This prevents any more jobs
2431 * TRUE if the job table is full, FALSE otherwise
2441 if (fifoFd >= 0 && jobFull) {
2442 i = read(fifoFd, &c, 1);
2453 * See if the job table is empty. Because the local concurrency may
2454 * be set to 0, it is possible for the job table to become empty,
2455 * while the list of stoppedJobs remains non-empty. In such a case,
2456 * we want to restart as many jobs as we can.
2459 * TRUE if it is. FALSE if it ain't.
2465 if (!TAILQ_EMPTY(&stoppedJobs) && !aborting) {
2467 * The job table is obviously not full if it has no
2468 * jobs in it...Try and restart the stopped jobs.
2483 * Handle the receipt of an interrupt.
2486 * All children are killed. Another job will be started if the
2487 * .INTERRUPT target was given.
2490 JobInterrupt(int runINTERRUPT, int signo)
2492 Job *job; /* job descriptor in that element */
2493 GNode *interrupt; /* the node describing the .INTERRUPT target */
2495 aborting = ABORT_INTERRUPT;
2497 TAILQ_FOREACH(job, &jobs, link) {
2498 if (!Targ_Precious(job->node)) {
2499 char *file = (job->node->path == NULL ?
2500 job->node->name : job->node->path);
2502 if (!noExecute && eunlink(file) != -1) {
2503 Error("*** %s removed", file);
2507 DEBUGF(JOB, ("JobInterrupt passing signal to child "
2508 "%jd.\n", (intmax_t)job->pid));
2509 KILL(job->pid, signo);
2513 if (runINTERRUPT && !touchFlag) {
2515 * clear the interrupted flag because we would get an
2516 * infinite loop otherwise.
2520 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2521 if (interrupt != NULL) {
2522 ignoreErrors = FALSE;
2524 JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
2527 Job_CatchChildren(!usePipes);
2535 * Do final processing such as the running of the commands
2536 * attached to the .END target.
2539 * Number of errors reported.
2545 if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
2547 Error("Errors reported so .END ignored");
2549 JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
2553 Job_CatchChildren(!usePipes);
2568 * Waits for all running jobs to finish and returns. Sets 'aborting'
2569 * to ABORT_WAIT to prevent other jobs from starting.
2572 * Currently running jobs finish.
2578 aborting = ABORT_WAIT;
2579 while (nJobs != 0) {
2581 Job_CatchChildren(!usePipes);
2588 * Abort all currently running jobs without handling output or anything.
2589 * This function is to be called only in the event of a major
2590 * error. Most definitely NOT to be called from JobInterrupt.
2593 * All children are killed, not just the firstborn
2598 Job *job; /* the job descriptor in that element */
2601 aborting = ABORT_ERROR;
2604 TAILQ_FOREACH(job, &jobs, link) {
2606 * kill the child process with increasingly drastic
2607 * signals to make darn sure it's dead.
2609 KILL(job->pid, SIGINT);
2610 KILL(job->pid, SIGKILL);
2615 * Catch as many children as want to report in at first, then give up
2617 while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2623 * Tries to restart stopped jobs if there are slots available.
2624 * Note that this tries to restart them regardless of pending errors.
2625 * It's not good to leave stopped jobs lying around!
2628 * Resumes(and possibly migrates) jobs.
2631 JobRestartJobs(void)
2635 while (!jobFull && (job = TAILQ_FIRST(&stoppedJobs)) != NULL) {
2636 DEBUGF(JOB, ("Job queue is not full. "
2637 "Restarting a stopped job.\n"));
2638 TAILQ_REMOVE(&stoppedJobs, job, link);
2645 * Execute the command in cmd, and return the output of that command
2649 * A string containing the output of the command, or the empty string
2650 * If error is not NULL, it contains the reason for the command failure
2651 * Any output sent to stderr in the child process is passed to stderr,
2652 * and not captured in the string.
2655 * The string must be freed by the caller.
2658 Cmd_Exec(const char *cmd, const char **error)
2660 int fds[2]; /* Pipe streams */
2661 int status; /* command exit status */
2662 Buffer *buf; /* buffer to store the result */
2670 * Open a pipe for fetching its output
2672 if (pipe(fds) == -1) {
2673 *error = "Couldn't create pipe for \"%s\"";
2677 /* Set close-on-exec on read side of pipe. */
2678 fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC);
2680 ps.in = STDIN_FILENO;
2682 ps.err = STDERR_FILENO;
2684 ps.merge_errors = 0;
2688 /* Set up arguments for shell */
2689 ps.argv = emalloc(4 * sizeof(char *));
2690 ps.argv[0] = strdup(commandShell->name);
2691 ps.argv[1] = strdup("-c");
2692 ps.argv[2] = strdup(cmd);
2697 * Fork. Warning since we are doing vfork() instead of fork(),
2698 * do not allocate memory in the child process!
2700 if ((ps.child_pid = vfork()) == -1) {
2701 *error = "Couldn't exec \"%s\"";
2704 } else if (ps.child_pid == 0) {
2717 close(fds[1]); /* No need for the writing half of the pipe. */
2720 char result[BUFSIZ];
2722 rcnt = read(fds[0], result, sizeof(result));
2724 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
2725 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
2728 *error = "Error reading shell's output for \"%s\"";
2731 * Close the input side of the pipe.
2735 status = ProcWait(&ps);
2738 *error = "\"%s\" returned non-zero status";
2740 Buf_StripNewlines(buf);
2747 * Interrupt handler - set flag and defer handling to the main code
2750 CompatCatchSig(int signo)
2753 interrupted = signo;
2757 *-----------------------------------------------------------------------
2758 * CompatInterrupt --
2759 * Interrupt the creation of the current target and remove it if
2760 * it ain't precious.
2766 * The target is removed and the process exits. If .INTERRUPT exists,
2767 * its commands are run first WITH INTERRUPTS IGNORED..
2769 *-----------------------------------------------------------------------
2772 CompatInterrupt(int signo)
2775 sigset_t nmask, omask;
2778 sigemptyset(&nmask);
2779 sigaddset(&nmask, SIGINT);
2780 sigaddset(&nmask, SIGTERM);
2781 sigaddset(&nmask, SIGHUP);
2782 sigaddset(&nmask, SIGQUIT);
2783 sigprocmask(SIG_SETMASK, &nmask, &omask);
2785 /* prevent recursion in evaluation of .INTERRUPT */
2788 if (curTarg != NULL && !Targ_Precious(curTarg)) {
2789 const char *file = Var_Value(TARGET, curTarg);
2791 if (!noExecute && eunlink(file) != -1) {
2792 printf("*** %s removed\n", file);
2797 * Run .INTERRUPT only if hit with interrupt signal
2799 if (signo == SIGINT) {
2800 gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2802 LST_FOREACH(ln, &gn->commands) {
2803 if (Compat_RunCommand(Lst_Datum(ln), gn))
2809 sigprocmask(SIG_SETMASK, &omask, NULL);
2811 if (signo == SIGQUIT)
2813 signal(signo, SIG_DFL);
2814 kill(getpid(), signo);
2821 * Returns NULL if a specified line must be executed by the shell,
2822 * and an argument vector if it can be run via execvp().
2825 * Uses brk_string so destroys the contents of argv.
2828 shellneed(ArgArray *aa, char *cmd)
2833 if (commandShell->meta == NULL || commandShell->builtins.argc <= 1)
2837 if (strpbrk(cmd, commandShell->meta) != NULL)
2841 * Break the command into words to form an argument
2842 * vector we can execute.
2844 brk_string(aa, cmd, TRUE);
2845 for (p = commandShell->builtins.argv + 1; *p != 0; p++) {
2846 if ((ret = strcmp(aa->argv[1], *p)) == 0) {
2847 /* found - use shell */
2856 return (aa->argv + 1);
2860 * Execute the next command for a target. If the command returns an
2861 * error, the node's made field is set to ERROR and creation stops.
2862 * The node from which the command came is also given. This is used
2863 * to execute the commands in compat mode and when executing commands
2864 * with the '+' flag in non-compat mode. In these modes each command
2865 * line should be executed by its own shell. We do some optimisation here:
2866 * if the shell description defines both a string of meta characters and
2867 * a list of builtins and the command line neither contains a meta character
2868 * nor starts with one of the builtins then we execute the command directly
2869 * without invoking a shell.
2872 * 0 if the command succeeded, 1 if an error occurred.
2875 * The node's 'made' field may be set to ERROR.
2878 Compat_RunCommand(char *cmd, GNode *gn)
2881 char *cmdStart; /* Start of expanded command */
2882 Boolean silent; /* Don't print command */
2883 Boolean doit; /* Execute even in -n */
2884 Boolean errCheck; /* Check errors */
2885 int reason; /* Reason for child's death */
2886 int status; /* Description of child's death */
2887 LstNode *cmdNode; /* Node where current cmd is located */
2888 char **av; /* Argument vector for thing to exec */
2891 silent = gn->type & OP_SILENT;
2892 errCheck = !(gn->type & OP_IGNORE);
2895 cmdNode = Lst_Member(&gn->commands, cmd);
2896 cmdStart = Buf_Peel(Var_Subst(cmd, gn, FALSE));
2899 * brk_string will return an argv with a NULL in av[0], thus causing
2900 * execvp() to choke and die horribly. Besides, how can we execute a
2901 * null command? In any case, we warn the user that the command
2902 * expanded to nothing (is this the right thing to do?).
2904 if (*cmdStart == '\0') {
2906 Error("%s expands to empty string", cmd);
2911 Lst_Replace(cmdNode, cmdStart);
2913 if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
2914 Lst_AtEnd(&ENDNode->commands, cmdStart);
2916 } else if (strcmp(cmdStart, "...") == 0) {
2917 gn->type |= OP_SAVE_CMDS;
2921 while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
2925 silent = DEBUG(LOUD) ? FALSE : TRUE;
2939 while (isspace((unsigned char)*cmd))
2943 * Print the command before echoing if we're not supposed to be quiet
2944 * for this one. We also print the command if -n given, but not if '+'.
2946 if (!silent || (noExecute && !doit)) {
2947 printf("%s\n", cmd);
2952 * If we're not supposed to execute any commands, this is as far as
2955 if (!doit && noExecute) {
2959 ps.in = STDIN_FILENO;
2960 ps.out = STDOUT_FILENO;
2961 ps.err = STDERR_FILENO;
2963 ps.merge_errors = 0;
2967 if ((av = shellneed(&aa, cmd)) == NULL) {
2969 * Shell meta character or shell builtin found - pass
2970 * command to shell. We give the shell the -e flag as
2971 * well as -c if it is supposed to exit when it hits an error.
2973 ps.argv = emalloc(4 * sizeof(char *));
2974 ps.argv[0] = strdup(commandShell->path);
2975 ps.argv[1] = strdup(errCheck ? "-ec" : "-c");
2976 ps.argv[2] = strdup(cmd);
2983 ps.errCheck = errCheck;
2986 * Warning since we are doing vfork() instead of fork(),
2987 * do not allocate memory in the child process!
2989 if ((ps.child_pid = vfork()) == -1) {
2990 Fatal("Could not fork");
2992 } else if (ps.child_pid == 0) {
3010 * we need to print out the command associated with this
3011 * Gnode in Targ_PrintCmd from Targ_PrintGraph when debugging
3012 * at level g2, in main(), Fatal() and DieHorribly(),
3013 * therefore do not free it when debugging.
3015 if (!DEBUG(GRAPH2)) {
3020 * The child is off and running. Now all we can do is wait...
3022 reason = ProcWait(&ps);
3025 CompatInterrupt(interrupted);
3028 * Decode and report the reason child exited, then
3029 * indicate how we handled it.
3031 if (WIFEXITED(reason)) {
3032 status = WEXITSTATUS(reason);
3036 printf("*** Error code %d", status);
3038 } else if (WIFSTOPPED(reason)) {
3039 status = WSTOPSIG(reason);
3041 status = WTERMSIG(reason);
3042 printf("*** Signal %d", status);
3053 printf(" (continuing)\n");
3058 * Continue executing
3059 * commands for this target.
3060 * If we return 0, this will
3063 printf(" (ignored)\n");
3070 *-----------------------------------------------------------------------
3072 * Make a target, given the parent, to abort if necessary.
3075 * If an error is detected and not being ignored, the process exits.
3077 *-----------------------------------------------------------------------
3080 CompatMake(GNode *gn, GNode *pgn)
3084 if (gn->type & OP_USE) {
3085 Make_HandleUse(gn, pgn);
3087 } else if (gn->made == UNMADE) {
3089 * First mark ourselves to be made, then apply whatever
3090 * transformations the suffix module thinks are necessary.
3091 * Once that's done, we can descend and make all our children.
3092 * If any of them has an error but the -k flag was given, our
3093 * 'make' field will be set FALSE again. This is our signal to
3094 * not attempt to do anything but abort our parent as well.
3097 gn->made = BEINGMADE;
3099 LST_FOREACH(ln, &gn->children)
3100 CompatMake(Lst_Datum(ln), gn);
3107 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3108 Var_Set(IMPSRC, Var_Value(TARGET, gn), pgn);
3112 * All the children were made ok. Now cmtime contains the
3113 * modification time of the newest child, we need to find out
3114 * if we exist and when we were modified last. The criteria for
3115 * datedness are defined by the Make_OODate function.
3117 DEBUGF(MAKE, ("Examining %s...", gn->name));
3118 if (!Make_OODate(gn)) {
3119 gn->made = UPTODATE;
3120 DEBUGF(MAKE, ("up-to-date.\n"));
3123 DEBUGF(MAKE, ("out-of-date.\n"));
3127 * If the user is just seeing if something is out-of-date,
3128 * exit now to tell him/her "yes".
3135 * We need to be re-made. We also have to make sure we've got
3136 * a $? variable. To be nice, we also define the $> variable
3137 * using Make_DoAllVar().
3142 * Alter our type to tell if errors should be ignored or things
3143 * should not be printed so Compat_RunCommand knows what to do.
3145 if (Targ_Ignore(gn)) {
3146 gn->type |= OP_IGNORE;
3148 if (Targ_Silent(gn)) {
3149 gn->type |= OP_SILENT;
3152 if (Job_CheckCommands(gn, Fatal)) {
3154 * Our commands are ok, but we still have to worry
3155 * about the -t flag...
3159 LST_FOREACH(ln, &gn->commands) {
3160 if (Compat_RunCommand(Lst_Datum(ln),
3166 Job_Touch(gn, gn->type & OP_SILENT);
3172 if (gn->made != ERROR) {
3174 * If the node was made successfully, mark it so, update
3175 * its modification time and timestamp all its parents.
3176 * Note that for .ZEROTIME targets, the timestamping
3177 * isn't done. This is to keep its state from affecting
3178 * that of its parent.
3183 * We can't re-stat the thing, but we can at least take
3184 * care of rules where a target depends on a source that
3185 * actually creates the target, but only if it has
3193 * mv y.tab.o parse.o
3194 * cmp -s y.tab.h parse.h || mv y.tab.h parse.h
3196 * In this case, if the definitions produced by yacc
3197 * haven't changed from before, parse.h won't have been
3198 * updated and gn->mtime will reflect the current
3199 * modification time for parse.h. This is something of a
3200 * kludge, I admit, but it's a useful one..
3202 * XXX: People like to use a rule like
3206 * To force things that depend on FRC to be made, so we
3207 * have to check for gn->children being empty as well...
3209 if (!Lst_IsEmpty(&gn->commands) ||
3210 Lst_IsEmpty(&gn->children)) {
3215 * This is what Make does and it's actually a good
3216 * thing, as it allows rules like
3218 * cmp -s y.tab.h parse.h || cp y.tab.h parse.h
3220 * to function as intended. Unfortunately, thanks to
3221 * the stateless nature of NFS (and the speed of this
3222 * program), there are times when the modification time
3223 * of a file created on a remote machine will not be
3224 * modified before the stat() implied by the Dir_MTime
3225 * occurs, thus leading us to believe that the file
3226 * is unchanged, wreaking havoc with files that depend
3229 * I have decided it is better to make too much than to
3230 * make too little, so this stuff is commented out
3231 * unless you're sure it's ok.
3234 if (noExecute || Dir_MTime(gn) == 0) {
3237 if (gn->cmtime > gn->mtime)
3238 gn->mtime = gn->cmtime;
3239 DEBUGF(MAKE, ("update time: %s\n",
3240 Targ_FmtTime(gn->mtime)));
3242 if (!(gn->type & OP_EXEC)) {
3243 pgn->childMade = TRUE;
3244 Make_TimeStamp(pgn, gn);
3247 } else if (keepgoing) {
3251 printf("\n\nStop in %s.\n", Var_Value(".CURDIR", gn));
3254 } else if (gn->made == ERROR) {
3256 * Already had an error when making this beastie. Tell the
3261 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3262 Var_Set(IMPSRC, Var_Value(TARGET, gn), pgn);
3266 Error("Graph cycles through %s\n", gn->name);
3271 if ((gn->type & OP_EXEC) == 0) {
3272 pgn->childMade = TRUE;
3273 Make_TimeStamp(pgn, gn);
3277 if ((gn->type & OP_EXEC) == 0) {
3278 Make_TimeStamp(pgn, gn);
3290 *-----------------------------------------------------------------------
3292 * Start making again, given a list of target nodes.
3300 *-----------------------------------------------------------------------
3303 Compat_Run(Lst *targs)
3305 GNode *gn = NULL; /* Current root target */
3306 int error_cnt; /* Number of targets not remade due to errors */
3309 if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
3310 signal(SIGINT, CompatCatchSig);
3312 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
3313 signal(SIGTERM, CompatCatchSig);
3315 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
3316 signal(SIGHUP, CompatCatchSig);
3318 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
3319 signal(SIGQUIT, CompatCatchSig);
3322 ENDNode = Targ_FindNode(".END", TARG_CREATE);
3324 * If the user has defined a .BEGIN target, execute the commands
3328 gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
3330 LST_FOREACH(ln, &gn->commands) {
3331 if (Compat_RunCommand(Lst_Datum(ln), gn))
3334 if (gn->made == ERROR) {
3335 printf("\n\nStop.\n");
3342 * For each entry in the list of targets to create, call CompatMake on
3343 * it to create the thing. CompatMake will leave the 'made' field of gn
3344 * in one of several states:
3345 * UPTODATE gn was already up-to-date
3346 * MADE gn was recreated successfully
3347 * ERROR An error occurred while gn was being created
3348 * ABORTED gn was not remade because one of its inferiors
3349 * could not be made due to errors.
3352 while (!Lst_IsEmpty(targs)) {
3353 gn = Lst_DeQueue(targs);
3356 if (gn->made == UPTODATE) {
3357 printf("`%s' is up to date.\n", gn->name);
3358 } else if (gn->made == ABORTED) {
3359 printf("`%s' not remade because of errors.\n",
3366 * If the user has defined a .END target, run its commands.
3368 if (error_cnt == 0) {
3369 LST_FOREACH(ln, &ENDNode->commands) {
3370 if (Compat_RunCommand(Lst_Datum(ln), ENDNode))