1 /* $NetBSD: job.c,v 1.302 2020/11/01 18:45:49 rillig Exp $ */
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * Copyright (c) 1988, 1989 by Adam de Boor
37 * Copyright (c) 1989 by Berkeley Softworks
38 * All rights reserved.
40 * This code is derived from software contributed to Berkeley by
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. All advertising materials mentioning features or use of this software
52 * must display the following acknowledgement:
53 * This product includes software developed by the University of
54 * California, Berkeley and its contributors.
55 * 4. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
74 * handle the creation etc. of our child processes.
77 * Job_Init Called to initialize this module. In addition,
78 * any commands attached to the .BEGIN target
79 * are executed before this function returns.
80 * Hence, the makefiles must have been parsed
81 * before this function is called.
83 * Job_End Clean up any memory used.
85 * Job_Make Start the creation of the given target.
88 * Check for and handle the termination of any
89 * children. This must be called reasonably
90 * frequently to keep the whole make going at
91 * a decent clip, since job table entries aren't
92 * removed until their process is caught this way.
95 * Print any output our children have produced.
96 * Should also be called fairly frequently to
97 * keep the user informed of what's going on.
98 * If no output is waiting, it will block for
99 * a time given by the SEL_* constants, below,
100 * or until output is ready.
102 * Job_ParseShell Given the line following a .SHELL target, parse
103 * the line as a shell specification. Returns
104 * FALSE if the spec was incorrect.
106 * Job_Finish Perform any final processing which needs doing.
107 * This includes the execution of any commands
108 * which have been/were attached to the .END
109 * target. It should only be called when the
110 * job table is empty.
112 * Job_AbortAll Abort all currently running jobs. It doesn't
113 * handle output or do anything for the jobs,
114 * just kills them. It should only be called in
118 * Verify that the commands for a target are
119 * ok. Provide them if necessary and possible.
121 * Job_Touch Update a target without really updating it.
123 * Job_Wait Wait for all currently-running jobs to finish.
129 #include <sys/types.h>
130 #include <sys/stat.h>
131 #include <sys/file.h>
132 #include <sys/time.h>
136 #if !defined(USE_SELECT) && defined(HAVE_POLL_H)
139 #ifndef USE_SELECT /* no poll.h */
142 #if defined(HAVE_SYS_SELECT_H)
143 # include <sys/select.h>
148 #if defined(HAVE_SYS_SOCKET_H)
149 # include <sys/socket.h>
155 #include "pathnames.h"
158 /* "@(#)job.c 8.2 (Berkeley) 3/19/94" */
159 MAKE_RCSID("$NetBSD: job.c,v 1.302 2020/11/01 18:45:49 rillig Exp $");
161 /* A shell defines how the commands are run. All commands for a target are
162 * written into a single file, which is then given to the shell to execute
163 * the commands from it. The commands are written to the file using a few
164 * templates for echo control and error control.
166 * The name of the shell is the basename for the predefined shells, such as
167 * "sh", "csh", "bash". For custom shells, it is the full pathname, and its
168 * basename is used to select the type of shell; the longest match wins.
169 * So /usr/pkg/bin/bash has type sh, /usr/local/bin/tcsh has type csh.
171 * The echoing of command lines is controlled using hasEchoCtl, echoOff,
172 * echoOn, noPrint and noPrintLen. When echoOff is executed by the shell, it
173 * still outputs something, but this something is not interesting, therefore
174 * it is filtered out using noPrint and noPrintLen.
176 * The error checking for individual commands is controlled using hasErrCtl,
177 * errOnOrEcho, errOffOrExecIgnore and errExit.
179 * If a shell doesn't have error control, errOnOrEcho becomes a printf template
180 * for echoing the command, should echoing be on; errOffOrExecIgnore becomes
181 * another printf template for executing the command while ignoring the return
182 * status. Finally errExit is a printf template for running the command and
183 * causing the shell to exit on error. If any of these strings are empty when
184 * hasErrCtl is FALSE, the command will be executed anyway as is, and if it
185 * causes an error, so be it. Any templates setup to echo the command will
186 * escape any '$ ` \ "' characters in the command string to avoid common
187 * problems with echo "%s\n" as a template.
189 * The command-line flags "echo" and "exit" also control the behavior. The
190 * "echo" flag causes the shell to start echoing commands right away. The
191 * "exit" flag causes the shell to exit when an error is detected in one of
194 typedef struct Shell {
196 /* The name of the shell. For Bourne and C shells, this is used only to
197 * find the shell description when used as the single source of a .SHELL
198 * target. For user-defined shells, this is the full path of the shell. */
201 Boolean hasEchoCtl; /* True if both echoOff and echoOn defined */
202 const char *echoOff; /* command to turn off echo */
203 const char *echoOn; /* command to turn it back on again */
204 const char *noPrint; /* text to skip when printing output from
205 * shell. This is usually the same as echoOff */
206 size_t noPrintLen; /* length of noPrint command */
208 Boolean hasErrCtl; /* set if can control error checking for
209 * individual commands */
210 /* XXX: split into errOn and echoCmd */
211 const char *errOnOrEcho; /* template to turn on error checking */
212 /* XXX: split into errOff and execIgnore */
213 const char *errOffOrExecIgnore; /* template to turn off error checking */
214 const char *errExit; /* template to use for testing exit code */
216 /* string literal that results in a newline character when it appears
217 * outside of any 'quote' or "quote" characters */
219 char commentChar; /* character used by shell for comment lines */
224 const char *echo; /* echo commands */
225 const char *exit; /* exit on error */
229 * FreeBSD: traditionally .MAKE is not required to
230 * pass jobs queue to sub-makes.
231 * Use .MAKE.ALWAYS_PASS_JOB_QUEUE=no to disable.
233 #define MAKE_ALWAYS_PASS_JOB_QUEUE ".MAKE.ALWAYS_PASS_JOB_QUEUE"
234 static int Always_pass_job_queue = TRUE;
236 * FreeBSD: aborting entire parallel make isn't always
237 * desired. When doing tinderbox for example, failure of
238 * one architecture should not stop all.
239 * We still want to bail on interrupt though.
241 #define MAKE_JOB_ERROR_TOKEN "MAKE_JOB_ERROR_TOKEN"
242 static int Job_error_token = TRUE;
245 * error handling variables
247 static int errors = 0; /* number of errors reported */
248 typedef enum AbortReason { /* why is the make aborting? */
250 ABORT_ERROR, /* Because of an error */
251 ABORT_INTERRUPT, /* Because it was interrupted */
252 ABORT_WAIT /* Waiting for jobs to finish */
254 static AbortReason aborting = ABORT_NONE;
255 #define JOB_TOKENS "+EI+" /* Token to requeue for each abort state */
258 * this tracks the number of tokens currently "out" to build jobs.
260 int jobTokensRunning = 0;
262 /* The number of commands actually printed to the shell commands file for
263 * the current job. Should this number be 0, no shell will be executed. */
264 static int numCommands;
266 typedef enum JobStartResult {
267 JOB_RUNNING, /* Job is running */
268 JOB_ERROR, /* Error in starting the job */
269 JOB_FINISHED /* The job is already finished */
273 * Descriptions for various shells.
275 * The build environment may set DEFSHELL_INDEX to one of
276 * DEFSHELL_INDEX_SH, DEFSHELL_INDEX_KSH, or DEFSHELL_INDEX_CSH, to
277 * select one of the predefined shells as the default shell.
279 * Alternatively, the build environment may set DEFSHELL_CUSTOM to the
280 * name or the full path of a sh-compatible shell, which will be used as
283 * ".SHELL" lines in Makefiles can choose the default shell from the
284 * set defined here, or add additional shells.
287 #ifdef DEFSHELL_CUSTOM
288 #define DEFSHELL_INDEX_CUSTOM 0
289 #define DEFSHELL_INDEX_SH 1
290 #define DEFSHELL_INDEX_KSH 2
291 #define DEFSHELL_INDEX_CSH 3
292 #else /* !DEFSHELL_CUSTOM */
293 #define DEFSHELL_INDEX_SH 0
294 #define DEFSHELL_INDEX_KSH 1
295 #define DEFSHELL_INDEX_CSH 2
296 #endif /* !DEFSHELL_CUSTOM */
298 #ifndef DEFSHELL_INDEX
299 #define DEFSHELL_INDEX 0 /* DEFSHELL_INDEX_CUSTOM or DEFSHELL_INDEX_SH */
300 #endif /* !DEFSHELL_INDEX */
302 static Shell shells[] = {
303 #ifdef DEFSHELL_CUSTOM
305 * An sh-compatible shell with a non-standard name.
307 * Keep this in sync with the "sh" description below, but avoid
308 * non-portable features that might not be supplied by all
309 * sh-compatible shells.
312 DEFSHELL_CUSTOM, /* .name */
313 FALSE, /* .hasEchoCtl */
318 FALSE, /* .hasErrCtl */
319 "echo \"%s\"\n", /* .errOnOrEcho */
320 "%s\n", /* .errOffOrExecIgnore */
321 "{ %s \n} || exit $?\n", /* .errExit */
322 "'\n'", /* .newline */
323 '#', /* .commentChar */
327 #endif /* DEFSHELL_CUSTOM */
329 * SH description. Echo control is also possible and, under
330 * sun UNIX anyway, one can even control error checking.
334 FALSE, /* .hasEchoCtl */
339 FALSE, /* .hasErrCtl */
340 "echo \"%s\"\n", /* .errOnOrEcho */
341 "%s\n", /* .errOffOrExecIgnore */
342 "{ %s \n} || exit $?\n", /* .errExit */
343 "'\n'", /* .newline */
344 '#', /* .commentChar*/
345 #if defined(MAKE_NATIVE) && defined(__NetBSD__)
357 TRUE, /* .hasEchoCtl */
358 "set +v", /* .echoOff */
359 "set -v", /* .echoOn */
360 "set +v", /* .noPrint */
362 FALSE, /* .hasErrCtl */
363 "echo \"%s\"\n", /* .errOnOrEcho */
364 "%s\n", /* .errOffOrExecIgnore */
365 "{ %s \n} || exit $?\n", /* .errExit */
366 "'\n'", /* .newline */
367 '#', /* .commentChar */
372 * CSH description. The csh can do echo control by playing
373 * with the setting of the 'echo' shell variable. Sadly,
374 * however, it is unable to do error control nicely.
378 TRUE, /* .hasEchoCtl */
379 "unset verbose", /* .echoOff */
380 "set verbose", /* .echoOn */
381 "unset verbose", /* .noPrint */
382 13, /* .noPrintLen */
383 FALSE, /* .hasErrCtl */
384 "echo \"%s\"\n", /* .errOnOrEcho */
385 /* XXX: Mismatch between errOn and execIgnore */
386 "csh -c \"%s || exit 0\"\n", /* .errOffOrExecIgnore */
388 "'\\\n'", /* .newline */
389 '#', /* .commentChar */
395 /* This is the shell to which we pass all commands in the Makefile.
396 * It is set by the Job_ParseShell function. */
397 static Shell *commandShell = &shells[DEFSHELL_INDEX];
398 const char *shellPath = NULL; /* full pathname of executable image */
399 const char *shellName = NULL; /* last component of shellPath */
400 char *shellErrFlag = NULL;
401 static char *shellArgv = NULL; /* Custom shell args */
404 static Job *job_table; /* The structures that describe them */
405 static Job *job_table_end; /* job_table + maxJobs */
406 static unsigned int wantToken; /* we want a token */
407 static int lurking_children = 0;
408 static int make_suspended = 0; /* non-zero if we've seen a SIGTSTP (etc) */
411 * Set of descriptors of pipes connected to
412 * the output channels of children
414 static struct pollfd *fds = NULL;
415 static Job **jobfds = NULL;
416 static nfds_t nfds = 0;
417 static void watchfd(Job *);
418 static void clearfd(Job *);
419 static int readyfd(Job *);
421 static GNode *lastNode; /* The node for which output was most recently
423 static char *targPrefix = NULL; /* What we print at the start of TARG_FMT */
424 static Job tokenWaitJob; /* token wait pseudo-job */
426 static Job childExitJob; /* child exit pseudo-job */
427 #define CHILD_EXIT "."
428 #define DO_JOB_RESUME "R"
430 enum { npseudojobs = 2 }; /* number of pseudo-jobs */
432 #define TARG_FMT "%s %s ---\n" /* Default format */
433 #define MESSAGE(fp, gn) \
434 if (opts.maxJobs != 1 && targPrefix && *targPrefix) \
435 (void)fprintf(fp, TARG_FMT, targPrefix, gn->name)
437 static sigset_t caught_signals; /* Set of signals we handle */
439 static void JobDoOutput(Job *, Boolean);
440 static void JobInterrupt(int, int) MAKE_ATTR_DEAD;
441 static void JobRestartJobs(void);
442 static void JobSigReset(void);
447 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
455 job_table_dump(const char *where)
459 debug_printf("job table @ %s\n", where);
460 for (job = job_table; job < job_table_end; job++) {
461 debug_printf("job %d, status %d, flags %d, pid %d\n",
462 (int)(job - job_table), job->job_state, job->flags, job->pid);
467 * Delete the target of a failed, interrupted, or otherwise
468 * unsuccessful job unless inhibited by .PRECIOUS.
471 JobDeleteTarget(GNode *gn)
475 if (gn->type & OP_JOIN)
477 if (gn->type & OP_PHONY)
479 if (Targ_Precious(gn))
484 file = GNode_Path(gn);
485 if (eunlink(file) != -1)
486 Error("*** %s removed", file);
490 * JobSigLock/JobSigUnlock
492 * Signal lock routines to get exclusive access. Currently used to
493 * protect `jobs' and `stoppedJobs' list manipulations.
495 static void JobSigLock(sigset_t *omaskp)
497 if (sigprocmask(SIG_BLOCK, &caught_signals, omaskp) != 0) {
498 Punt("JobSigLock: sigprocmask: %s", strerror(errno));
503 static void JobSigUnlock(sigset_t *omaskp)
505 (void)sigprocmask(SIG_SETMASK, omaskp, NULL);
509 JobCreatePipe(Job *job, int minfd)
514 if (pipe(pipe_fds) == -1)
515 Punt("Cannot create pipe: %s", strerror(errno));
517 for (i = 0; i < 2; i++) {
518 /* Avoid using low numbered fds */
519 fd = fcntl(pipe_fds[i], F_DUPFD, minfd);
526 job->inPipe = pipe_fds[0];
527 job->outPipe = pipe_fds[1];
529 /* Set close-on-exec flag for both */
530 if (fcntl(job->inPipe, F_SETFD, FD_CLOEXEC) == -1)
531 Punt("Cannot set close-on-exec: %s", strerror(errno));
532 if (fcntl(job->outPipe, F_SETFD, FD_CLOEXEC) == -1)
533 Punt("Cannot set close-on-exec: %s", strerror(errno));
536 * We mark the input side of the pipe non-blocking; we poll(2) the
537 * pipe when we're waiting for a job token, but we might lose the
538 * race for the token when a new one becomes available, so the read
539 * from the pipe should not block.
541 flags = fcntl(job->inPipe, F_GETFL, 0);
543 Punt("Cannot get flags: %s", strerror(errno));
545 if (fcntl(job->inPipe, F_SETFL, flags) == -1)
546 Punt("Cannot set flags: %s", strerror(errno));
549 /* Pass the signal to each running job. */
551 JobCondPassSig(int signo)
555 DEBUG1(JOB, "JobCondPassSig(%d) called.\n", signo);
557 for (job = job_table; job < job_table_end; job++) {
558 if (job->job_state != JOB_ST_RUNNING)
560 DEBUG2(JOB, "JobCondPassSig passing signal %d to child %d.\n",
562 KILLPG(job->pid, signo);
568 * Sends a token on the child exit pipe to wake us up from select()/poll(). */
570 JobChildSig(int signo MAKE_ATTR_UNUSED)
572 while (write(childExitJob.outPipe, CHILD_EXIT, 1) == -1 && errno == EAGAIN)
577 /* Resume all stopped jobs. */
579 JobContinueSig(int signo MAKE_ATTR_UNUSED)
582 * Defer sending SIGCONT to our stopped children until we return
583 * from the signal handler.
585 while (write(childExitJob.outPipe, DO_JOB_RESUME, 1) == -1 &&
590 /* Pass a signal on to all jobs, then resend to ourselves.
591 * We die by the same signal. */
592 MAKE_ATTR_DEAD static void
593 JobPassSig_int(int signo)
595 /* Run .INTERRUPT target then exit */
596 JobInterrupt(TRUE, signo);
599 /* Pass a signal on to all jobs, then resend to ourselves.
600 * We die by the same signal. */
601 MAKE_ATTR_DEAD static void
602 JobPassSig_term(int signo)
604 /* Dont run .INTERRUPT target then exit */
605 JobInterrupt(FALSE, signo);
609 JobPassSig_suspend(int signo)
611 sigset_t nmask, omask;
612 struct sigaction act;
614 /* Suppress job started/continued messages */
617 /* Pass the signal onto every job */
618 JobCondPassSig(signo);
621 * Send ourselves the signal now we've given the message to everyone else.
622 * Note we block everything else possible while we're getting the signal.
623 * This ensures that all our jobs get continued when we wake up before
624 * we take any other signal.
627 sigdelset(&nmask, signo);
628 (void)sigprocmask(SIG_SETMASK, &nmask, &omask);
630 act.sa_handler = SIG_DFL;
631 sigemptyset(&act.sa_mask);
633 (void)sigaction(signo, &act, NULL);
636 debug_printf("JobPassSig passing signal %d to self.\n", signo);
638 (void)kill(getpid(), signo);
641 * We've been continued.
643 * A whole host of signals continue to happen!
644 * SIGCHLD for any processes that actually suspended themselves.
645 * SIGCHLD for any processes that exited while we were alseep.
646 * The SIGCONT that actually caused us to wakeup.
648 * Since we defer passing the SIGCONT on to our children until
649 * the main processing loop, we can be sure that all the SIGCHLD
650 * events will have happened by then - and that the waitpid() will
651 * collect the child 'suspended' events.
652 * For correct sequencing we just need to ensure we process the
653 * waitpid() before passing on the SIGCONT.
655 * In any case nothing else is needed here.
658 /* Restore handler and signal mask */
659 act.sa_handler = JobPassSig_suspend;
660 (void)sigaction(signo, &act, NULL);
661 (void)sigprocmask(SIG_SETMASK, &omask, NULL);
665 JobFindPid(int pid, JobState status, Boolean isJobs)
669 for (job = job_table; job < job_table_end; job++) {
670 if ((job->job_state == status) && job->pid == pid)
673 if (DEBUG(JOB) && isJobs)
674 job_table_dump("no pid");
678 /* Parse leading '@', '-' and '+', which control the exact execution mode. */
682 Boolean *out_shutUp, Boolean *out_errOff, Boolean *out_runAlways)
687 *out_runAlways = FALSE;
691 *out_shutUp = !DEBUG(LOUD);
695 *out_runAlways = TRUE;
701 pp_skip_whitespace(&p);
706 /* Escape a string for a double-quoted string literal in sh, csh and ksh. */
708 EscapeShellDblQuot(const char *cmd)
712 /* Worst that could happen is every char needs escaping. */
713 char *esc = bmake_malloc(strlen(cmd) * 2 + 1);
714 for (i = 0, j = 0; cmd[i] != '\0'; i++, j++) {
715 if (cmd[i] == '$' || cmd[i] == '`' || cmd[i] == '\\' || cmd[i] == '"')
725 *-----------------------------------------------------------------------
727 * Put out another command for the given job. If the command starts
728 * with an @ or a - we process it specially. In the former case,
729 * so long as the -s and -n flags weren't given to make, we stick
730 * a shell-specific echoOff command in the script. In the latter,
731 * we ignore errors for the entire job, unless the shell has error
733 * If the command is just "..." we take all future commands for this
734 * job to be commands to be executed once the entire graph has been
735 * made and return non-zero to signal that the end of the commands
736 * was reached. These commands are later attached to the postCommands
737 * node and executed by Job_End when all things are done.
740 * If the command begins with a '-' and the shell has no error control,
741 * the JOB_IGNERR flag is set in the job descriptor.
742 * numCommands is incremented if the command is actually printed.
743 *-----------------------------------------------------------------------
746 JobPrintCommand(Job *job, char *cmd)
748 const char *const cmdp = cmd;
749 Boolean noSpecials; /* true if we shouldn't worry about
750 * inserting special commands into
751 * the input stream. */
752 Boolean shutUp; /* true if we put a no echo command
753 * into the command file */
754 Boolean errOff; /* true if we turned error checking
755 * off before printing the command
756 * and need to turn it back on */
758 const char *cmdTemplate; /* Template to use when printing the
760 char *cmdStart; /* Start of expanded command */
761 char *escCmd = NULL; /* Command with quotes/backticks escaped */
763 noSpecials = !GNode_ShouldExecute(job->node);
765 #define DBPRINTF(fmt, arg) if (DEBUG(JOB)) { \
766 debug_printf(fmt, arg); \
768 (void)fprintf(job->cmdFILE, fmt, arg); \
769 (void)fflush(job->cmdFILE);
773 Var_Subst(cmd, job->node, VARE_WANTRES, &cmd);
774 /* TODO: handle errors */
777 cmdTemplate = "%s\n";
779 ParseRunOptions(&cmd, &shutUp, &errOff, &runAlways);
781 if (runAlways && noSpecials) {
783 * We're not actually executing anything...
784 * but this one needs to be - use compat mode just for it.
786 Compat_RunCommand(cmdp, job->node);
792 * If the shell doesn't have error control the alternate echo'ing will
793 * be done (to avoid showing additional error checking code)
794 * and this will need the characters '$ ` \ "' escaped
797 if (!commandShell->hasErrCtl)
798 escCmd = EscapeShellDblQuot(cmd);
801 if (!(job->flags & JOB_SILENT) && !noSpecials &&
802 commandShell->hasEchoCtl) {
803 DBPRINTF("%s\n", commandShell->echoOff);
805 if (commandShell->hasErrCtl)
812 if (commandShell->hasErrCtl) {
814 * we don't want the error-control commands showing
815 * up either, so we turn off echoing while executing
816 * them. We could put another field in the shell
817 * structure to tell JobDoOutput to look for this
818 * string too, but why make it any more complex than
821 if (!(job->flags & JOB_SILENT) && !shutUp &&
822 commandShell->hasEchoCtl) {
823 DBPRINTF("%s\n", commandShell->echoOff);
824 DBPRINTF("%s\n", commandShell->errOffOrExecIgnore);
825 DBPRINTF("%s\n", commandShell->echoOn);
827 DBPRINTF("%s\n", commandShell->errOffOrExecIgnore);
829 } else if (commandShell->errOffOrExecIgnore &&
830 commandShell->errOffOrExecIgnore[0] != '\0')
833 * The shell has no error control, so we need to be
834 * weird to get it to ignore any errors from the command.
835 * If echoing is turned on, we turn it off and use the
836 * errOnOrEcho template to echo the command. Leave echoing
837 * off so the user doesn't see the weirdness we go through
838 * to ignore errors. Set cmdTemplate to use the weirdness
839 * instead of the simple "%s\n" template.
841 job->flags |= JOB_IGNERR;
842 if (!(job->flags & JOB_SILENT) && !shutUp) {
843 if (commandShell->hasEchoCtl) {
844 DBPRINTF("%s\n", commandShell->echoOff);
846 DBPRINTF(commandShell->errOnOrEcho, escCmd);
850 DBPRINTF(commandShell->errOnOrEcho, escCmd);
853 cmdTemplate = commandShell->errOffOrExecIgnore;
855 * The error ignoration (hee hee) is already taken care
856 * of by the errOffOrExecIgnore template, so pretend error
857 * checking is still on.
869 * If errors are being checked and the shell doesn't have error control
870 * but does supply an errExit template, then setup commands to run
874 if (!commandShell->hasErrCtl && commandShell->errExit &&
875 commandShell->errExit[0] != '\0') {
876 if (!(job->flags & JOB_SILENT) && !shutUp) {
877 if (commandShell->hasEchoCtl) {
878 DBPRINTF("%s\n", commandShell->echoOff);
880 DBPRINTF(commandShell->errOnOrEcho, escCmd);
883 /* If it's a comment line or blank, treat as an ignored error */
884 if ((escCmd[0] == commandShell->commentChar) ||
886 cmdTemplate = commandShell->errOffOrExecIgnore;
888 cmdTemplate = commandShell->errExit;
893 if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0 &&
894 (job->flags & JOB_TRACED) == 0) {
895 DBPRINTF("set -%s\n", "x");
896 job->flags |= JOB_TRACED;
899 DBPRINTF(cmdTemplate, cmd);
904 * If echoing is already off, there's no point in issuing the
905 * echoOff command. Otherwise we issue it and pretend it was on
906 * for the whole command...
908 if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl){
909 DBPRINTF("%s\n", commandShell->echoOff);
912 DBPRINTF("%s\n", commandShell->errOnOrEcho);
914 if (shutUp && commandShell->hasEchoCtl) {
915 DBPRINTF("%s\n", commandShell->echoOn);
919 /* Print all commands to the shell file that is later executed.
921 * The special command "..." stops printing and saves the remaining commands
922 * to be executed later. */
924 JobPrintCommands(Job *job)
928 for (ln = job->node->commands->first; ln != NULL; ln = ln->next) {
929 const char *cmd = ln->datum;
931 if (strcmp(cmd, "...") == 0) {
932 job->node->type |= OP_SAVE_CMDS;
933 if ((job->flags & JOB_IGNDOTS) == 0) {
934 job->tailCmds = ln->next;
938 JobPrintCommand(job, ln->datum);
942 /* Save the delayed commands, to be executed when everything else is done. */
944 JobSaveCommands(Job *job)
946 StringListNode *node;
948 for (node = job->tailCmds; node != NULL; node = node->next) {
949 const char *cmd = node->datum;
951 /* XXX: This Var_Subst is only intended to expand the dynamic
952 * variables such as .TARGET, .IMPSRC. It is not intended to
953 * expand the other variables as well; see deptgt-end.mk. */
954 (void)Var_Subst(cmd, job->node, VARE_WANTRES, &expanded_cmd);
955 /* TODO: handle errors */
956 Lst_Append(Targ_GetEndNode()->commands, expanded_cmd);
961 /* Called to close both input and output pipes when a job is finished. */
966 (void)close(job->outPipe);
969 JobDoOutput(job, TRUE);
970 (void)close(job->inPipe);
975 *-----------------------------------------------------------------------
977 * Do final processing for the given job including updating
978 * parents and starting new jobs as available/necessary. Note
979 * that we pay no attention to the JOB_IGNERR flag here.
980 * This is because when we're called because of a noexecute flag
981 * or something, jstat.w_status is 0 and when called from
982 * Job_CatchChildren, the status is zeroed if it s/b ignored.
986 * status sub-why job went away
989 * Final commands for the job are placed on postCommands.
991 * If we got an error and are aborting (aborting == ABORT_ERROR) and
992 * the job list is now empty, we are done for the day.
993 * If we recognized an error (errors !=0), we set the aborting flag
994 * to ABORT_ERROR so no more jobs will be started.
995 *-----------------------------------------------------------------------
998 JobFinish (Job *job, WAIT_T status)
1000 Boolean done, return_job_token;
1002 DEBUG3(JOB, "JobFinish: %d [%s], status %d\n",
1003 job->pid, job->node->name, status);
1005 if ((WIFEXITED(status) &&
1006 (((WEXITSTATUS(status) != 0) && !(job->flags & JOB_IGNERR)))) ||
1007 WIFSIGNALED(status))
1010 * If it exited non-zero and either we're doing things our
1011 * way or we're not ignoring errors, the job is finished.
1012 * Similarly, if the shell died because of a signal
1013 * the job is also finished. In these
1014 * cases, finish out the job's output before printing the exit
1018 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1019 (void)fclose(job->cmdFILE);
1020 job->cmdFILE = NULL;
1023 } else if (WIFEXITED(status)) {
1025 * Deal with ignored errors in -B mode. We need to print a message
1026 * telling of the ignored error as well as setting status.w_status
1027 * to 0 so the next command gets run. To do this, we set done to be
1028 * TRUE if in -B mode and the job exited non-zero.
1030 done = WEXITSTATUS(status) != 0;
1032 * Old comment said: "Note we don't
1033 * want to close down any of the streams until we know we're at the
1035 * But we do. Otherwise when are we going to print the rest of the
1041 * No need to close things down or anything.
1047 if (WIFEXITED(status)) {
1048 DEBUG2(JOB, "Process %d [%s] exited.\n",
1049 job->pid, job->node->name);
1050 if (WEXITSTATUS(status) != 0) {
1051 if (job->node != lastNode) {
1052 MESSAGE(stdout, job->node);
1053 lastNode = job->node;
1057 meta_job_error(job, job->node, job->flags, WEXITSTATUS(status));
1060 if (!dieQuietly(job->node, -1))
1061 (void)printf("*** [%s] Error code %d%s\n",
1063 WEXITSTATUS(status),
1064 (job->flags & JOB_IGNERR) ? " (ignored)" : "");
1065 if (job->flags & JOB_IGNERR) {
1066 WAIT_STATUS(status) = 0;
1068 if (deleteOnError) {
1069 JobDeleteTarget(job->node);
1071 PrintOnError(job->node, NULL);
1073 } else if (DEBUG(JOB)) {
1074 if (job->node != lastNode) {
1075 MESSAGE(stdout, job->node);
1076 lastNode = job->node;
1078 (void)printf("*** [%s] Completed successfully\n",
1082 if (job->node != lastNode) {
1083 MESSAGE(stdout, job->node);
1084 lastNode = job->node;
1086 (void)printf("*** [%s] Signal %d\n",
1087 job->node->name, WTERMSIG(status));
1088 if (deleteOnError) {
1089 JobDeleteTarget(job->node);
1092 (void)fflush(stdout);
1099 if ((x = meta_job_finish(job)) != 0 && status == 0) {
1105 return_job_token = FALSE;
1107 Trace_Log(JOBEND, job);
1108 if (!(job->flags & JOB_SPECIAL)) {
1109 if ((WAIT_STATUS(status) != 0) ||
1110 (aborting == ABORT_ERROR) ||
1111 (aborting == ABORT_INTERRUPT))
1112 return_job_token = TRUE;
1115 if ((aborting != ABORT_ERROR) && (aborting != ABORT_INTERRUPT) &&
1116 (WAIT_STATUS(status) == 0)) {
1118 * As long as we aren't aborting and the job didn't return a non-zero
1119 * status that we shouldn't ignore, we call Make_Update to update
1122 JobSaveCommands(job);
1123 job->node->made = MADE;
1124 if (!(job->flags & JOB_SPECIAL))
1125 return_job_token = TRUE;
1126 Make_Update(job->node);
1127 job->job_state = JOB_ST_FREE;
1128 } else if (WAIT_STATUS(status)) {
1130 job->job_state = JOB_ST_FREE;
1134 * Set aborting if any error.
1136 if (errors && !opts.keepgoing && (aborting != ABORT_INTERRUPT)) {
1138 * If we found any errors in this batch of children and the -k flag
1139 * wasn't given, we set the aborting flag so no more jobs get
1142 aborting = ABORT_ERROR;
1145 if (return_job_token)
1148 if (aborting == ABORT_ERROR && jobTokensRunning == 0) {
1150 * If we are aborting and the job table is now empty, we finish.
1156 /* Touch the given target. Called by JobStart when the -t flag was given.
1158 * The modification date of the file is changed.
1159 * If the file did not exist, it is created. */
1161 Job_Touch(GNode *gn, Boolean silent)
1163 int streamID; /* ID of stream opened to do the touch */
1164 struct utimbuf times; /* Times for utime() call */
1166 if (gn->type & (OP_JOIN|OP_USE|OP_USEBEFORE|OP_EXEC|OP_OPTIONAL|
1167 OP_SPECIAL|OP_PHONY)) {
1169 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets
1170 * and, as such, shouldn't really be created.
1175 if (!silent || !GNode_ShouldExecute(gn)) {
1176 (void)fprintf(stdout, "touch %s\n", gn->name);
1177 (void)fflush(stdout);
1180 if (!GNode_ShouldExecute(gn)) {
1184 if (gn->type & OP_ARCHV) {
1186 } else if (gn->type & OP_LIB) {
1189 const char *file = GNode_Path(gn);
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 the
1200 * modification time, then close the file.
1202 if (read(streamID, &c, 1) == 1) {
1203 (void)lseek(streamID, (off_t)0, SEEK_SET);
1204 while (write(streamID, &c, 1) == -1 && errno == EAGAIN)
1208 (void)close(streamID);
1210 (void)fprintf(stdout, "*** couldn't touch %s: %s",
1211 file, strerror(errno));
1212 (void)fflush(stdout);
1218 /* Make sure the given node has all the commands it needs.
1220 * The node will have commands from the .DEFAULT rule added to it if it
1224 * gn The target whose commands need verifying
1225 * abortProc Function to abort with message
1228 * TRUE if the commands list is/was ok.
1231 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1233 if (GNode_IsTarget(gn))
1235 if (!Lst_IsEmpty(gn->commands))
1237 if ((gn->type & OP_LIB) && !Lst_IsEmpty(gn->children))
1241 * No commands. Look for .DEFAULT rule from which we might infer
1244 if ((DEFAULT != NULL) && !Lst_IsEmpty(DEFAULT->commands) &&
1245 (gn->type & OP_SPECIAL) == 0) {
1247 * Make only looks for a .DEFAULT if the node was never the
1248 * target of an operator, so that's what we do too. If
1249 * a .DEFAULT was given, we substitute its commands for gn's
1250 * commands and set the IMPSRC variable to be the target's name
1251 * The DEFAULT node acts like a transformation rule, in that
1252 * gn also inherits any attributes or sources attached to
1255 Make_HandleUse(DEFAULT, gn);
1256 Var_Set(IMPSRC, GNode_VarTarget(gn), gn);
1260 if (Dir_MTime(gn, 0) != 0 || (gn->type & OP_SPECIAL))
1264 * The node wasn't the target of an operator. We have no .DEFAULT
1265 * rule to go on and the target doesn't already exist. There's
1266 * nothing more we can do for this branch. If the -k flag wasn't
1267 * given, we stop in our tracks, otherwise we just don't update
1268 * this node's parents so they never get examined.
1271 if (gn->flags & FROM_DEPEND) {
1272 if (!Job_RunTarget(".STALE", gn->fname))
1273 fprintf(stdout, "%s: %s, %d: ignoring stale %s for %s\n",
1274 progname, gn->fname, gn->lineno, makeDependfile,
1279 if (gn->type & OP_OPTIONAL) {
1280 (void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
1281 progname, gn->name, "ignored");
1282 (void)fflush(stdout);
1286 if (opts.keepgoing) {
1287 (void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
1288 progname, gn->name, "continuing");
1289 (void)fflush(stdout);
1293 abortProc("%s: don't know how to make %s. Stop", progname, gn->name);
1297 /* Execute the shell for the given job.
1299 * A shell is executed, its output is altered and the Job structure added
1303 JobExec(Job *job, char **argv)
1305 int cpid; /* ID of new child */
1308 job->flags &= ~JOB_TRACED;
1313 debug_printf("Running %s %sly\n", job->node->name, "local");
1314 debug_printf("\tCommand: ");
1315 for (i = 0; argv[i] != NULL; i++) {
1316 debug_printf("%s ", argv[i]);
1322 * Some jobs produce no output and it's disconcerting to have
1323 * no feedback of their running (since they produce no output, the
1324 * banner with their name in it never appears). This is an attempt to
1325 * provide that feedback, even if nothing follows it.
1327 if ((lastNode != job->node) && !(job->flags & JOB_SILENT)) {
1328 MESSAGE(stdout, job->node);
1329 lastNode = job->node;
1332 /* No interruptions until this job is on the `jobs' list */
1335 /* Pre-emptively mark job running, pid still zero though */
1336 job->job_state = JOB_ST_RUNNING;
1340 Punt("Cannot vfork: %s", strerror(errno));
1348 meta_job_child(job);
1352 * Reset all signal handlers; this is necessary because we also
1353 * need to unblock signals before we exec(2).
1357 /* Now unblock signals */
1358 sigemptyset(&tmask);
1359 JobSigUnlock(&tmask);
1362 * Must duplicate the input stream down to the child's input and
1363 * reset it to the beginning (again). Since the stream was marked
1364 * close-on-exec, we must clear that bit in the new input.
1366 if (dup2(fileno(job->cmdFILE), 0) == -1)
1367 execDie("dup2", "job->cmdFILE");
1368 if (fcntl(0, F_SETFD, 0) == -1)
1369 execDie("fcntl clear close-on-exec", "stdin");
1370 if (lseek(0, (off_t)0, SEEK_SET) == -1)
1371 execDie("lseek to 0", "stdin");
1373 if (Always_pass_job_queue ||
1374 (job->node->type & (OP_MAKE | OP_SUBMAKE))) {
1376 * Pass job token pipe to submakes.
1378 if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1)
1379 execDie("clear close-on-exec", "tokenWaitJob.inPipe");
1380 if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1)
1381 execDie("clear close-on-exec", "tokenWaitJob.outPipe");
1385 * Set up the child's output to be routed through the pipe
1386 * we've created for it.
1388 if (dup2(job->outPipe, 1) == -1)
1389 execDie("dup2", "job->outPipe");
1392 * The output channels are marked close on exec. This bit was
1393 * duplicated by the dup2(on some systems), so we have to clear
1394 * it before routing the shell's error output to the same place as
1395 * its standard output.
1397 if (fcntl(1, F_SETFD, 0) == -1)
1398 execDie("clear close-on-exec", "stdout");
1399 if (dup2(1, 2) == -1)
1400 execDie("dup2", "1, 2");
1403 * We want to switch the child into a different process family so
1404 * we can kill it and all its descendants in one fell swoop,
1405 * by killing its process family, but not commit suicide.
1407 #if defined(HAVE_SETPGID)
1408 (void)setpgid(0, getpid());
1410 #if defined(HAVE_SETSID)
1411 /* XXX: dsl - I'm sure this should be setpgrp()... */
1414 (void)setpgrp(0, getpid());
1420 (void)execv(shellPath, argv);
1421 execDie("exec", shellPath);
1424 /* Parent, continuing after the child exec */
1427 Trace_Log(JOBSTART, job);
1431 meta_job_parent(job, cpid);
1436 * Set the current position in the buffer to the beginning
1437 * and mark another stream to watch in the outputs mask
1443 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1444 (void)fclose(job->cmdFILE);
1445 job->cmdFILE = NULL;
1449 * Now the job is actually running, add it to the table.
1452 debug_printf("JobExec(%s): pid %d added to jobs table\n",
1453 job->node->name, job->pid);
1454 job_table_dump("job started");
1456 JobSigUnlock(&mask);
1459 /* Create the argv needed to execute the shell for a given job. */
1461 JobMakeArgv(Job *job, char **argv)
1464 static char args[10]; /* For merged arguments */
1466 argv[0] = UNCONST(shellName);
1469 if ((commandShell->exit && commandShell->exit[0] != '-') ||
1470 (commandShell->echo && commandShell->echo[0] != '-'))
1473 * At least one of the flags doesn't have a minus before it, so
1474 * merge them together. Have to do this because the *(&(@*#*&#$#
1475 * Bourne shell thinks its second argument is a file to source.
1476 * Grrrr. Note the ten-character limitation on the combined arguments.
1478 (void)snprintf(args, sizeof(args), "-%s%s",
1479 ((job->flags & JOB_IGNERR) ? "" :
1480 (commandShell->exit ? commandShell->exit : "")),
1481 ((job->flags & JOB_SILENT) ? "" :
1482 (commandShell->echo ? commandShell->echo : "")));
1489 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1490 argv[argc] = UNCONST(commandShell->exit);
1493 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1494 argv[argc] = UNCONST(commandShell->echo);
1502 *-----------------------------------------------------------------------
1504 * Start a target-creation process going for the target described
1505 * by the graph node gn.
1508 * gn target to create
1509 * flags flags for the job to override normal ones.
1510 * e.g. JOB_SPECIAL or JOB_IGNDOTS
1511 * previous The previous Job structure for this node, if any.
1514 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1515 * if there isn't actually anything left to do for the job and
1516 * JOB_RUNNING if the job has been started.
1519 * A new Job node is created and added to the list of running
1520 * jobs. PMake is forked and a child shell created.
1522 * NB: I'm fairly sure that this code is never called with JOB_SPECIAL set
1523 * JOB_IGNDOTS is never set (dsl)
1524 * Also the return value is ignored by everyone.
1525 *-----------------------------------------------------------------------
1527 static JobStartResult
1528 JobStart(GNode *gn, int flags)
1530 Job *job; /* new job descriptor */
1531 char *argv[10]; /* Argument vector to shell */
1532 Boolean cmdsOK; /* true if the nodes commands were all right */
1533 Boolean noExec; /* Set true if we decide not to run the job */
1534 int tfd; /* File descriptor to the temp file */
1536 for (job = job_table; job < job_table_end; job++) {
1537 if (job->job_state == JOB_ST_FREE)
1540 if (job >= job_table_end)
1541 Punt("JobStart no job slots vacant");
1543 memset(job, 0, sizeof *job);
1544 job->job_state = JOB_ST_SETUP;
1545 if (gn->type & OP_SPECIAL)
1546 flags |= JOB_SPECIAL;
1549 job->tailCmds = NULL;
1552 * Set the initial value of the flags for this job based on the global
1553 * ones and the node's attributes... Any flags supplied by the caller
1554 * are also added to the field.
1557 if (Targ_Ignore(gn)) {
1558 job->flags |= JOB_IGNERR;
1560 if (Targ_Silent(gn)) {
1561 job->flags |= JOB_SILENT;
1563 job->flags |= flags;
1566 * Check the commands now so any attributes from .DEFAULT have a chance
1567 * to migrate to the node
1569 cmdsOK = Job_CheckCommands(gn, Error);
1571 job->inPollfd = NULL;
1573 * If the -n flag wasn't given, we open up OUR (not the child's)
1574 * temporary file to stuff commands in it. The thing is rd/wr so we don't
1575 * need to reopen it to feed it to the shell. If the -n flag *was* given,
1576 * we just set the file to be stdout. Cute, huh?
1578 if (((gn->type & OP_MAKE) && !opts.noRecursiveExecute) ||
1579 (!opts.noExecute && !opts.touchFlag)) {
1581 * tfile is the name of a file into which all shell commands are
1582 * put. It is removed before the child shell is executed, unless
1583 * DEBUG(SCRIPT) is set.
1588 * We're serious here, but if the commands were bogus, we're
1592 PrintOnError(gn, NULL); /* provide some clue */
1597 tfd = mkTempFile(TMPPAT, &tfile);
1599 (void)eunlink(tfile);
1600 JobSigUnlock(&mask);
1602 job->cmdFILE = fdopen(tfd, "w+");
1603 if (job->cmdFILE == NULL) {
1604 Punt("Could not fdopen %s", tfile);
1606 (void)fcntl(fileno(job->cmdFILE), F_SETFD, FD_CLOEXEC);
1608 * Send the commands to the command file, flush all its buffers then
1609 * rewind and remove the thing.
1615 meta_job_start(job, gn);
1616 if (Targ_Silent(gn)) { /* might have changed */
1617 job->flags |= JOB_SILENT;
1622 * We can do all the commands at once. hooray for sanity
1625 JobPrintCommands(job);
1628 * If we didn't print out any commands to the shell script,
1629 * there's not much point in executing the shell, is there?
1631 if (numCommands == 0) {
1636 } else if (!GNode_ShouldExecute(gn)) {
1638 * Not executing anything -- just print all the commands to stdout
1639 * in one fell swoop. This will still set up job->tailCmds correctly.
1641 if (lastNode != gn) {
1642 MESSAGE(stdout, gn);
1645 job->cmdFILE = stdout;
1647 * Only print the commands if they're ok, but don't die if they're
1648 * not -- just let the user know they're bad and keep going. It
1649 * doesn't do any harm in this case and may do some good.
1652 JobPrintCommands(job);
1654 * Don't execute the shell, thank you.
1659 * Just touch the target and note that no shell should be executed.
1660 * Set cmdFILE to stdout to make life easier. Check the commands, too,
1661 * but don't die if they're no good -- it does no harm to keep working
1664 job->cmdFILE = stdout;
1665 Job_Touch(gn, job->flags&JOB_SILENT);
1668 /* Just in case it isn't already... */
1669 (void)fflush(job->cmdFILE);
1672 * If we're not supposed to execute a shell, don't.
1675 if (!(job->flags & JOB_SPECIAL))
1678 * Unlink and close the command file if we opened one
1680 if (job->cmdFILE != stdout) {
1681 if (job->cmdFILE != NULL) {
1682 (void)fclose(job->cmdFILE);
1683 job->cmdFILE = NULL;
1688 * We only want to work our way up the graph if we aren't here because
1689 * the commands for the job were no good.
1691 if (cmdsOK && aborting == ABORT_NONE) {
1692 JobSaveCommands(job);
1693 job->node->made = MADE;
1694 Make_Update(job->node);
1696 job->job_state = JOB_ST_FREE;
1697 return cmdsOK ? JOB_FINISHED : JOB_ERROR;
1701 * Set up the control arguments to the shell. This is based on the flags
1702 * set earlier for this job.
1704 JobMakeArgv(job, argv);
1706 /* Create the pipe by which we'll get the shell's output. */
1707 JobCreatePipe(job, 3);
1714 JobOutput(Job *job, char *cp, char *endp)
1718 if (commandShell->noPrint && commandShell->noPrint[0] != '\0') {
1719 while ((ecp = strstr(cp, commandShell->noPrint)) != NULL) {
1723 * The only way there wouldn't be a newline after
1724 * this line is if it were the last in the buffer.
1725 * however, since the non-printable comes after it,
1726 * there must be a newline, so we don't print one.
1728 (void)fprintf(stdout, "%s", cp);
1729 (void)fflush(stdout);
1731 cp = ecp + commandShell->noPrintLen;
1734 * Still more to print, look again after skipping
1735 * the whitespace following the non-printable
1739 while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
1751 *-----------------------------------------------------------------------
1753 * This function is called at different times depending on
1754 * whether the user has specified that output is to be collected
1755 * via pipes or temporary files. In the former case, we are called
1756 * whenever there is something to read on the pipe. We collect more
1757 * output from the given job and store it in the job's outBuf. If
1758 * this makes up a line, we print it tagged by the job's identifier,
1760 * If output has been collected in a temporary file, we open the
1761 * file and read it line by line, transferring it to our own
1762 * output channel until the file is empty. At which point we
1763 * remove the temporary file.
1764 * In both cases, however, we keep our figurative eye out for the
1765 * 'noPrint' line for the shell from which the output came. If
1766 * we recognize a line, we don't print it. If the command is not
1767 * alone on the line (the character after it is not \0 or \n), we
1768 * do print whatever follows it.
1771 * job the job whose output needs printing
1772 * finish TRUE if this is the last time we'll be called
1776 * curPos may be shifted as may the contents of outBuf.
1777 *-----------------------------------------------------------------------
1780 JobDoOutput(Job *job, Boolean finish)
1782 Boolean gotNL = FALSE; /* true if got a newline */
1783 Boolean fbuf; /* true if our buffer filled up */
1784 size_t nr; /* number of bytes read */
1785 size_t i; /* auxiliary index into outBuf */
1786 size_t max; /* limit for i (end of current data) */
1787 ssize_t nRead; /* (Temporary) number of bytes read */
1790 * Read as many bytes as will fit in the buffer.
1796 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1797 JOB_BUFSIZE - job->curPos);
1799 if (errno == EAGAIN)
1802 perror("JobDoOutput(piperead)");
1810 * If we hit the end-of-file (the job is dead), we must flush its
1811 * remaining output, so pretend we read a newline if there's any
1812 * output remaining in the buffer.
1813 * Also clear the 'finish' flag so we stop looping.
1815 if ((nr == 0) && (job->curPos != 0)) {
1816 job->outBuf[job->curPos] = '\n';
1819 } else if (nr == 0) {
1824 * Look for the last newline in the bytes we just got. If there is
1825 * one, break out of the loop with 'i' as its index and gotNL set
1828 max = job->curPos + nr;
1829 for (i = job->curPos + nr - 1; i >= job->curPos && i != (size_t)-1; i--) {
1830 if (job->outBuf[i] == '\n') {
1833 } else if (job->outBuf[i] == '\0') {
1837 job->outBuf[i] = ' ';
1843 if (job->curPos == JOB_BUFSIZE) {
1845 * If we've run out of buffer space, we have no choice
1846 * but to print the stuff. sigh.
1852 if (gotNL || fbuf) {
1854 * Need to send the output to the screen. Null terminate it
1855 * first, overwriting the newline character if there was one.
1856 * So long as the line isn't one we should filter (according
1857 * to the shell description), we print the line, preceded
1858 * by a target banner if this target isn't the same as the
1859 * one for which we last printed something.
1860 * The rest of the data in the buffer are then shifted down
1861 * to the start of the buffer and curPos is set accordingly.
1863 job->outBuf[i] = '\0';
1864 if (i >= job->curPos) {
1867 cp = JobOutput(job, job->outBuf, &job->outBuf[i]);
1870 * There's still more in that thar buffer. This time, though,
1871 * we know there's no newline at the end, so we add one of
1872 * our own free will.
1875 if (!opts.beSilent && job->node != lastNode) {
1876 MESSAGE(stdout, job->node);
1877 lastNode = job->node;
1881 meta_job_output(job, cp, gotNL ? "\n" : "");
1884 (void)fprintf(stdout, "%s%s", cp, gotNL ? "\n" : "");
1885 (void)fflush(stdout);
1889 * max is the last offset still in the buffer. Move any remaining
1890 * characters to the start of the buffer and update the end marker
1894 (void)memmove(job->outBuf, &job->outBuf[i + 1], max - (i + 1));
1895 job->curPos = max - (i + 1);
1903 * If the finish flag is true, we must loop until we hit
1904 * end-of-file on the pipe. This is guaranteed to happen
1905 * eventually since the other end of the pipe is now closed
1906 * (we closed it explicitly and the child has exited). When
1907 * we do get an EOF, finish will be set FALSE and we'll fall
1919 * Unfortunately it is too complicated to run .BEGIN, .END, and
1920 * .INTERRUPT job in the parallel job module. As of 2020-09-25,
1921 * unit-tests/deptgt-end-jobs.mk hangs in an endless loop.
1923 * Running these jobs in compat mode also guarantees that these
1924 * jobs do not overlap with other unrelated jobs.
1926 List *lst = Lst_New();
1927 Lst_Append(lst, targ);
1928 (void)Make_Run(lst);
1929 Lst_Destroy(lst, NULL);
1930 JobStart(targ, JOB_SPECIAL);
1931 while (jobTokensRunning) {
1935 Compat_Make(targ, targ);
1936 if (targ->made == ERROR) {
1937 PrintOnError(targ, "\n\nStop.");
1943 /* Handle the exit of a child. Called from Make_Make.
1945 * The job descriptor is removed from the list of children.
1948 * We do waits, blocking or not, according to the wisdom of our
1949 * caller, until there are no more children to report. For each
1950 * job, call JobFinish to finish things off.
1953 Job_CatchChildren(void)
1955 int pid; /* pid of dead child */
1956 WAIT_T status; /* Exit/termination status */
1959 * Don't even bother if we know there's no one around.
1961 if (jobTokensRunning == 0)
1964 while ((pid = waitpid((pid_t) -1, &status, WNOHANG | WUNTRACED)) > 0) {
1965 DEBUG2(JOB, "Process %d exited/stopped status %x.\n", pid,
1966 WAIT_STATUS(status));
1967 JobReapChild(pid, status, TRUE);
1972 * It is possible that wait[pid]() was called from elsewhere,
1973 * this lets us reap jobs regardless.
1976 JobReapChild(pid_t pid, WAIT_T status, Boolean isJobs)
1978 Job *job; /* job descriptor for dead child */
1981 * Don't even bother if we know there's no one around.
1983 if (jobTokensRunning == 0)
1986 job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
1989 if (!lurking_children)
1990 Error("Child (%d) status %x not in table?", pid, status);
1992 return; /* not ours */
1994 if (WIFSTOPPED(status)) {
1995 DEBUG2(JOB, "Process %d (%s) stopped.\n", job->pid, job->node->name);
1996 if (!make_suspended) {
1997 switch (WSTOPSIG(status)) {
1999 (void)printf("*** [%s] Suspended\n", job->node->name);
2002 (void)printf("*** [%s] Stopped\n", job->node->name);
2005 (void)printf("*** [%s] Stopped -- signal %d\n",
2006 job->node->name, WSTOPSIG(status));
2008 job->job_suspended = 1;
2010 (void)fflush(stdout);
2014 job->job_state = JOB_ST_FINISHED;
2015 job->exit_status = WAIT_STATUS(status);
2017 JobFinish(job, status);
2020 /* Catch the output from our children, if we're using pipes do so. Otherwise
2021 * just block time until we get a signal(most likely a SIGCHLD) since there's
2022 * no point in just spinning when there's nothing to do and the reaping of a
2023 * child can wait for a while. */
2025 Job_CatchOutput(void)
2031 (void)fflush(stdout);
2033 /* The first fd in the list is the job token pipe */
2035 nready = poll(fds + 1 - wantToken, nfds - 1 + wantToken, POLL_MSEC);
2036 } while (nready < 0 && errno == EINTR);
2039 Punt("poll: %s", strerror(errno));
2041 if (nready > 0 && readyfd(&childExitJob)) {
2044 count = read(childExitJob.inPipe, &token, 1);
2047 Punt("unexpected eof on token pipe");
2049 Punt("token pipe read: %s", strerror(errno));
2051 if (token == DO_JOB_RESUME[0])
2052 /* Complete relay requested from our SIGCONT handler */
2061 Job_CatchChildren();
2065 for (i = npseudojobs * nfds_per_job(); i < nfds; i++) {
2066 if (!fds[i].revents)
2069 if (job->job_state == JOB_ST_RUNNING)
2070 JobDoOutput(job, FALSE);
2071 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2073 * With meta mode, we may have activity on the job's filemon
2074 * descriptor too, which at the moment is any pollfd other than
2077 if (useMeta && job->inPollfd != &fds[i]) {
2078 if (meta_job_event(job) <= 0) {
2079 fds[i].events = 0; /* never mind */
2088 /* Start the creation of a target. Basically a front-end for JobStart used by
2089 * the Make module. */
2093 (void)JobStart(gn, 0);
2099 if (shellPath == NULL) {
2101 * We are using the default shell, which may be an absolute
2102 * path if DEFSHELL_CUSTOM is defined.
2104 shellName = commandShell->name;
2105 #ifdef DEFSHELL_CUSTOM
2106 if (*shellName == '/') {
2107 shellPath = shellName;
2108 shellName = strrchr(shellPath, '/');
2112 shellPath = str_concat3(_PATH_DEFSHELLDIR, "/", shellName);
2114 Var_Set_with_flags(".SHELL", shellPath, VAR_CMDLINE, VAR_SET_READONLY);
2115 if (commandShell->exit == NULL) {
2116 commandShell->exit = "";
2118 if (commandShell->echo == NULL) {
2119 commandShell->echo = "";
2121 if (commandShell->hasErrCtl && commandShell->exit[0] != '\0') {
2123 strcmp(commandShell->exit, &shellErrFlag[1]) != 0) {
2125 shellErrFlag = NULL;
2127 if (!shellErrFlag) {
2128 size_t n = strlen(commandShell->exit) + 2;
2130 shellErrFlag = bmake_malloc(n);
2132 snprintf(shellErrFlag, n, "-%s", commandShell->exit);
2135 } else if (shellErrFlag) {
2137 shellErrFlag = NULL;
2141 /* Return the string literal that is used in the current command shell
2142 * to produce a newline character. */
2144 Shell_GetNewline(void)
2146 return commandShell->newline;
2154 } else if (!Var_Exists(MAKE_JOB_PREFIX, VAR_GLOBAL)) {
2155 Var_Set(MAKE_JOB_PREFIX, "---", VAR_GLOBAL);
2158 (void)Var_Subst("${" MAKE_JOB_PREFIX "}",
2159 VAR_GLOBAL, VARE_WANTRES, &targPrefix);
2160 /* TODO: handle errors */
2163 /* Initialize the process module. */
2168 /* Allocate space for all the job info */
2169 job_table = bmake_malloc((size_t)opts.maxJobs * sizeof *job_table);
2170 memset(job_table, 0, (size_t)opts.maxJobs * sizeof *job_table);
2171 job_table_end = job_table + opts.maxJobs;
2174 aborting = ABORT_NONE;
2179 Always_pass_job_queue = getBoolean(MAKE_ALWAYS_PASS_JOB_QUEUE,
2180 Always_pass_job_queue);
2182 Job_error_token = getBoolean(MAKE_JOB_ERROR_TOKEN, Job_error_token);
2186 * There is a non-zero chance that we already have children.
2187 * eg after 'make -f- <<EOF'
2188 * Since their termination causes a 'Child (pid) not in table' message,
2189 * Collect the status of any that are already dead, and suppress the
2190 * error message if there are any undead ones.
2194 rval = waitpid((pid_t) -1, &status, WNOHANG);
2198 lurking_children = 1;
2204 JobCreatePipe(&childExitJob, 3);
2206 /* Preallocate enough for the maximum number of jobs. */
2207 fds = bmake_malloc(sizeof(*fds) *
2208 (npseudojobs + (size_t)opts.maxJobs) * nfds_per_job());
2209 jobfds = bmake_malloc(sizeof(*jobfds) *
2210 (npseudojobs + (size_t)opts.maxJobs) * nfds_per_job());
2212 /* These are permanent entries and take slots 0 and 1 */
2213 watchfd(&tokenWaitJob);
2214 watchfd(&childExitJob);
2216 sigemptyset(&caught_signals);
2218 * Install a SIGCHLD handler.
2220 (void)bmake_signal(SIGCHLD, JobChildSig);
2221 sigaddset(&caught_signals, SIGCHLD);
2223 #define ADDSIG(s,h) \
2224 if (bmake_signal(s, SIG_IGN) != SIG_IGN) { \
2225 sigaddset(&caught_signals, s); \
2226 (void)bmake_signal(s, h); \
2230 * Catch the four signals that POSIX specifies if they aren't ignored.
2231 * JobPassSig will take care of calling JobInterrupt if appropriate.
2233 ADDSIG(SIGINT, JobPassSig_int)
2234 ADDSIG(SIGHUP, JobPassSig_term)
2235 ADDSIG(SIGTERM, JobPassSig_term)
2236 ADDSIG(SIGQUIT, JobPassSig_term)
2239 * There are additional signals that need to be caught and passed if
2240 * either the export system wants to be told directly of signals or if
2241 * we're giving each job its own process group (since then it won't get
2242 * signals from the terminal driver as we own the terminal)
2244 ADDSIG(SIGTSTP, JobPassSig_suspend)
2245 ADDSIG(SIGTTOU, JobPassSig_suspend)
2246 ADDSIG(SIGTTIN, JobPassSig_suspend)
2247 ADDSIG(SIGWINCH, JobCondPassSig)
2248 ADDSIG(SIGCONT, JobContinueSig)
2251 (void)Job_RunTarget(".BEGIN", NULL);
2252 /* Create the .END node now, even though no code in the unit tests
2253 * depends on it. See also Targ_GetEndNode in Compat_Run. */
2254 (void)Targ_GetEndNode();
2257 static void JobSigReset(void)
2260 if (sigismember(&caught_signals, s)) { \
2261 (void)bmake_signal(s, SIG_DFL); \
2274 (void)bmake_signal(SIGCHLD, SIG_DFL);
2277 /* Find a shell in 'shells' given its name, or return NULL. */
2279 FindShellByName(const char *name)
2282 const Shell *shellsEnd = sh + sizeof shells / sizeof shells[0];
2284 for (sh = shells; sh < shellsEnd; sh++) {
2285 if (strcmp(name, sh->name) == 0)
2292 *-----------------------------------------------------------------------
2294 * Parse a shell specification and set up commandShell, shellPath
2295 * and shellName appropriately.
2298 * line The shell spec
2301 * FALSE if the specification was incorrect.
2304 * commandShell points to a Shell structure (either predefined or
2305 * created from the shell spec), shellPath is the full path of the
2306 * shell described by commandShell, while shellName is just the
2307 * final component of shellPath.
2310 * A shell specification consists of a .SHELL target, with dependency
2311 * operator, followed by a series of blank-separated words. Double
2312 * quotes can be used to use blanks in words. A backslash escapes
2313 * anything (most notably a double-quote and a space) and
2314 * provides the functionality it does in C. Each word consists of
2315 * keyword and value separated by an equal sign. There should be no
2316 * unnecessary spaces in the word. The keywords are as follows:
2317 * name Name of shell.
2318 * path Location of shell.
2319 * quiet Command to turn off echoing.
2320 * echo Command to turn echoing on
2321 * filter Result of turning off echoing that shouldn't be
2323 * echoFlag Flag to turn echoing on at the start
2324 * errFlag Flag to turn error checking on at the start
2325 * hasErrCtl True if shell has error checking control
2326 * newline String literal to represent a newline char
2327 * check Command to turn on error checking if hasErrCtl
2328 * is TRUE or template of command to echo a command
2329 * for which error checking is off if hasErrCtl is
2331 * ignore Command to turn off error checking if hasErrCtl
2332 * is TRUE or template of command to execute a
2333 * command so as to ignore any errors it returns if
2334 * hasErrCtl is FALSE.
2336 *-----------------------------------------------------------------------
2339 Job_ParseShell(char *line)
2347 Boolean fullSpec = FALSE;
2350 pp_skip_whitespace(&line);
2354 memset(&newShell, 0, sizeof(newShell));
2357 * Parse the specification by keyword
2359 wordsList = Str_Words(line, TRUE);
2360 words = wordsList.words;
2361 argc = wordsList.len;
2362 path = wordsList.freeIt;
2363 if (words == NULL) {
2364 Error("Unterminated quoted string [%s]", line);
2369 for (path = NULL, argv = words; argc != 0; argc--, argv++) {
2371 if (strncmp(arg, "path=", 5) == 0) {
2373 } else if (strncmp(arg, "name=", 5) == 0) {
2374 newShell.name = arg + 5;
2376 if (strncmp(arg, "quiet=", 6) == 0) {
2377 newShell.echoOff = arg + 6;
2378 } else if (strncmp(arg, "echo=", 5) == 0) {
2379 newShell.echoOn = arg + 5;
2380 } else if (strncmp(arg, "filter=", 7) == 0) {
2381 newShell.noPrint = arg + 7;
2382 newShell.noPrintLen = strlen(newShell.noPrint);
2383 } else if (strncmp(arg, "echoFlag=", 9) == 0) {
2384 newShell.echo = arg + 9;
2385 } else if (strncmp(arg, "errFlag=", 8) == 0) {
2386 newShell.exit = arg + 8;
2387 } else if (strncmp(arg, "hasErrCtl=", 10) == 0) {
2389 newShell.hasErrCtl = c == 'Y' || c == 'y' ||
2390 c == 'T' || c == 't';
2391 } else if (strncmp(arg, "newline=", 8) == 0) {
2392 newShell.newline = arg + 8;
2393 } else if (strncmp(arg, "check=", 6) == 0) {
2394 newShell.errOnOrEcho = arg + 6;
2395 } else if (strncmp(arg, "ignore=", 7) == 0) {
2396 newShell.errOffOrExecIgnore = arg + 7;
2397 } else if (strncmp(arg, "errout=", 7) == 0) {
2398 newShell.errExit = arg + 7;
2399 } else if (strncmp(arg, "comment=", 8) == 0) {
2400 newShell.commentChar = arg[8];
2402 Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"", arg);
2412 * If no path was given, the user wants one of the pre-defined shells,
2413 * yes? So we find the one s/he wants with the help of FindShellByName
2414 * and set things up the right way. shellPath will be set up by
2417 if (newShell.name == NULL) {
2418 Parse_Error(PARSE_FATAL, "Neither path nor name specified");
2422 if ((sh = FindShellByName(newShell.name)) == NULL) {
2423 Parse_Error(PARSE_WARNING, "%s: No matching shell",
2429 shellName = newShell.name;
2431 /* Shell_Init has already been called! Do it again. */
2432 free(UNCONST(shellPath));
2439 * The user provided a path. If s/he gave nothing else (fullSpec is
2440 * FALSE), try and find a matching shell in the ones we know of.
2441 * Else we just take the specification at its word and copy it
2442 * to a new location. In either case, we need to record the
2443 * path the user gave for the shell.
2446 path = strrchr(path, '/');
2448 path = UNCONST(shellPath);
2452 if (newShell.name != NULL) {
2453 shellName = newShell.name;
2458 if ((sh = FindShellByName(shellName)) == NULL) {
2459 Parse_Error(PARSE_WARNING, "%s: No matching shell",
2466 commandShell = bmake_malloc(sizeof(Shell));
2467 *commandShell = newShell;
2469 /* this will take care of shellErrFlag */
2473 if (commandShell->echoOn && commandShell->echoOff) {
2474 commandShell->hasEchoCtl = TRUE;
2477 if (!commandShell->hasErrCtl) {
2478 if (commandShell->errOnOrEcho == NULL) {
2479 commandShell->errOnOrEcho = "";
2481 if (commandShell->errOffOrExecIgnore == NULL) {
2482 commandShell->errOffOrExecIgnore = "%s\n";
2487 * Do not free up the words themselves, since they might be in use by the
2488 * shell specification.
2494 /* Handle the receipt of an interrupt.
2496 * All children are killed. Another job will be started if the .INTERRUPT
2497 * target is defined.
2500 * runINTERRUPT Non-zero if commands for the .INTERRUPT target
2501 * should be executed
2502 * signo signal received
2505 JobInterrupt(int runINTERRUPT, int signo)
2507 Job *job; /* job descriptor in that element */
2508 GNode *interrupt; /* the node describing the .INTERRUPT target */
2512 aborting = ABORT_INTERRUPT;
2516 for (job = job_table; job < job_table_end; job++) {
2517 if (job->job_state != JOB_ST_RUNNING)
2522 JobDeleteTarget(gn);
2524 DEBUG2(JOB, "JobInterrupt passing signal %d to child %d.\n",
2526 KILLPG(job->pid, signo);
2530 JobSigUnlock(&mask);
2532 if (runINTERRUPT && !opts.touchFlag) {
2533 interrupt = Targ_FindNode(".INTERRUPT");
2534 if (interrupt != NULL) {
2535 opts.ignoreErrors = FALSE;
2539 Trace_Log(MAKEINTR, 0);
2543 /* Do the final processing, i.e. run the commands attached to the .END target.
2545 * Return the number of errors reported. */
2549 GNode *endNode = Targ_GetEndNode();
2550 if (!Lst_IsEmpty(endNode->commands) || !Lst_IsEmpty(endNode->children)) {
2552 Error("Errors reported so .END ignored");
2560 /* Clean up any memory used by the jobs module. */
2569 /* Waits for all running jobs to finish and returns.
2570 * Sets 'aborting' to ABORT_WAIT to prevent other jobs from starting. */
2574 aborting = ABORT_WAIT;
2575 while (jobTokensRunning != 0) {
2578 aborting = ABORT_NONE;
2581 /* Abort all currently running jobs without handling output or anything.
2582 * This function is to be called only in the event of a major error.
2583 * Most definitely NOT to be called from JobInterrupt.
2585 * All children are killed, not just the firstborn. */
2589 Job *job; /* the job descriptor in that element */
2592 aborting = ABORT_ERROR;
2594 if (jobTokensRunning) {
2595 for (job = job_table; job < job_table_end; job++) {
2596 if (job->job_state != JOB_ST_RUNNING)
2599 * kill the child process with increasingly drastic signals to make
2600 * darn sure it's dead.
2602 KILLPG(job->pid, SIGINT);
2603 KILLPG(job->pid, SIGKILL);
2608 * Catch as many children as want to report in at first, then give up
2610 while (waitpid((pid_t) -1, &foo, WNOHANG) > 0)
2614 /* Tries to restart stopped jobs if there are slots available.
2615 * Called in process context in response to a SIGCONT. */
2617 JobRestartJobs(void)
2621 for (job = job_table; job < job_table_end; job++) {
2622 if (job->job_state == JOB_ST_RUNNING &&
2623 (make_suspended || job->job_suspended)) {
2624 DEBUG1(JOB, "Restarting stopped job pid %d.\n", job->pid);
2625 if (job->job_suspended) {
2626 (void)printf("*** [%s] Continued\n", job->node->name);
2627 (void)fflush(stdout);
2629 job->job_suspended = 0;
2630 if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
2631 debug_printf("Failed to send SIGCONT to %d\n", job->pid);
2634 if (job->job_state == JOB_ST_FINISHED)
2635 /* Job exit deferred after calling waitpid() in a signal handler */
2636 JobFinish(job, job->exit_status);
2644 if (job->inPollfd != NULL)
2645 Punt("Watching watched job");
2647 fds[nfds].fd = job->inPipe;
2648 fds[nfds].events = POLLIN;
2650 job->inPollfd = &fds[nfds];
2652 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2654 fds[nfds].fd = meta_job_fd(job);
2655 fds[nfds].events = fds[nfds].fd == -1 ? 0 : POLLIN;
2666 if (job->inPollfd == NULL)
2667 Punt("Unwatching unwatched job");
2668 i = (size_t)(job->inPollfd - fds);
2670 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2673 * Sanity check: there should be two fds per job, so the job's
2674 * pollfd number should be even.
2676 assert(nfds_per_job() == 2);
2678 Punt("odd-numbered fd with meta");
2683 * Move last job in table into hole made by dead job.
2687 jobfds[i] = jobfds[nfds];
2688 jobfds[i]->inPollfd = &fds[i];
2689 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2691 fds[i + 1] = fds[nfds + 1];
2692 jobfds[i + 1] = jobfds[nfds + 1];
2696 job->inPollfd = NULL;
2702 if (job->inPollfd == NULL)
2703 Punt("Polling unwatched job");
2704 return (job->inPollfd->revents & POLLIN) != 0;
2707 /* Put a token (back) into the job pipe.
2708 * This allows a make process to start a build job. */
2712 char tok = JOB_TOKENS[aborting], tok1;
2714 if (!Job_error_token && aborting == ABORT_ERROR) {
2715 if (jobTokensRunning == 0)
2717 tok = '+'; /* no error token */
2720 /* If we are depositing an error token flush everything else */
2721 while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2724 DEBUG3(JOB, "(%d) aborting %d, deposit token %c\n",
2725 getpid(), aborting, tok);
2726 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2730 /* Prep the job token pipe in the root make process. */
2732 Job_ServerStart(int max_tokens, int jp_0, int jp_1)
2737 if (jp_0 >= 0 && jp_1 >= 0) {
2738 /* Pipe passed in from parent */
2739 tokenWaitJob.inPipe = jp_0;
2740 tokenWaitJob.outPipe = jp_1;
2741 (void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
2742 (void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
2746 JobCreatePipe(&tokenWaitJob, 15);
2748 snprintf(jobarg, sizeof(jobarg), "%d,%d",
2749 tokenWaitJob.inPipe, tokenWaitJob.outPipe);
2751 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
2752 Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
2755 * Preload the job pipe with one token per job, save the one
2756 * "extra" token for the primary job.
2758 * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
2759 * larger than the write buffer size of the pipe, we will
2762 for (i = 1; i < max_tokens; i++)
2766 /* Return a withdrawn token to the pool. */
2768 Job_TokenReturn(void)
2771 if (jobTokensRunning < 0)
2772 Punt("token botch");
2773 if (jobTokensRunning || JOB_TOKENS[aborting] != '+')
2777 /* Attempt to withdraw a token from the pool.
2779 * If pool is empty, set wantToken so that we wake up when a token is
2782 * Returns TRUE if a token was withdrawn, and FALSE if the pool is currently
2785 Job_TokenWithdraw(void)
2791 DEBUG3(JOB, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
2792 getpid(), aborting, jobTokensRunning);
2794 if (aborting != ABORT_NONE || (jobTokensRunning >= opts.maxJobs))
2797 count = read(tokenWaitJob.inPipe, &tok, 1);
2799 Fatal("eof on job pipe!");
2800 if (count < 0 && jobTokensRunning != 0) {
2801 if (errno != EAGAIN) {
2802 Fatal("job pipe read: %s", strerror(errno));
2804 DEBUG1(JOB, "(%d) blocked for token\n", getpid());
2808 if (count == 1 && tok != '+') {
2809 /* make being abvorted - remove any other job tokens */
2810 DEBUG2(JOB, "(%d) aborted by token %c\n", getpid(), tok);
2811 while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2813 /* And put the stopper back */
2814 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2816 if (dieQuietly(NULL, 1))
2818 Fatal("A failure has been detected in another branch of the parallel make");
2821 if (count == 1 && jobTokensRunning == 0)
2822 /* We didn't want the token really */
2823 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2827 DEBUG1(JOB, "(%d) withdrew token\n", getpid());
2831 /* Run the named target if found. If a filename is specified, then set that
2834 * Exits if the target fails. */
2836 Job_RunTarget(const char *target, const char *fname) {
2837 GNode *gn = Targ_FindNode(target);
2842 Var_Set(ALLSRC, fname, gn);
2845 if (gn->made == ERROR) {
2846 PrintOnError(gn, "\n\nStop.");
2854 emul_poll(struct pollfd *fd, int nfd, int timeout)
2857 int i, maxfd, nselect, npoll;
2858 struct timeval tv, *tvp;
2865 for (i = 0; i < nfd; i++) {
2868 if (fd[i].events & POLLIN)
2869 FD_SET(fd[i].fd, &rfds);
2871 if (fd[i].events & POLLOUT)
2872 FD_SET(fd[i].fd, &wfds);
2874 if (fd[i].fd > maxfd)
2878 if (maxfd >= FD_SETSIZE) {
2879 Punt("Ran out of fd_set slots; "
2880 "recompile with a larger FD_SETSIZE.");
2886 usecs = timeout * 1000;
2887 tv.tv_sec = usecs / 1000000;
2888 tv.tv_usec = usecs % 1000000;
2892 nselect = select(maxfd + 1, &rfds, &wfds, 0, tvp);
2898 for (i = 0; i < nfd; i++) {
2899 if (FD_ISSET(fd[i].fd, &rfds))
2900 fd[i].revents |= POLLIN;
2902 if (FD_ISSET(fd[i].fd, &wfds))
2903 fd[i].revents |= POLLOUT;
2911 #endif /* USE_SELECT */