1 /* $NetBSD: job.c,v 1.459 2023/02/15 06:52:58 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 * the .BEGIN target is made including all of its
79 * dependencies 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 a special dependency line with target '.SHELL',
103 * define the shell that is used for the creation
104 * commands in jobs mode.
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. Do not handle
113 * output or do anything for the jobs, just kill them.
114 * Should only be called in an emergency.
117 * Verify that the commands for a target are
118 * ok. Provide them if necessary and possible.
120 * Job_Touch Update a target without really updating it.
122 * Job_Wait Wait for all currently-running jobs to finish.
128 #include <sys/types.h>
129 #include <sys/stat.h>
130 #include <sys/file.h>
131 #include <sys/time.h>
135 #if !defined(USE_SELECT) && defined(HAVE_POLL_H)
138 #ifndef USE_SELECT /* no poll.h */
141 #if defined(HAVE_SYS_SELECT_H)
142 # include <sys/select.h>
147 #if defined(HAVE_SYS_SOCKET_H)
148 # include <sys/socket.h>
154 #include "pathnames.h"
157 /* "@(#)job.c 8.2 (Berkeley) 3/19/94" */
158 MAKE_RCSID("$NetBSD: job.c,v 1.459 2023/02/15 06:52:58 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 * errOn, errOff and runChkTmpl.
179 * In case a shell doesn't have error control, echoTmpl is a printf template
180 * for echoing the command, should echoing be on; runIgnTmpl is another
181 * printf template for executing the command while ignoring the return
182 * status. Finally runChkTmpl 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 set up to echo the command will
186 * escape any '$ ` \ "' characters in the command string to avoid unwanted
187 * shell code injection, the escaped command is safe to use in double quotes.
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 {
197 * The name of the shell. For Bourne and C shells, this is used only
198 * to find the shell description when used as the single source of a
199 * .SHELL target. For user-defined shells, this is the full path of
204 bool hasEchoCtl; /* whether both echoOff and echoOn are there */
205 const char *echoOff; /* command to turn echoing off */
206 const char *echoOn; /* command to turn echoing back on */
207 const char *noPrint; /* text to skip when printing output from the
208 * shell. This is usually the same as echoOff */
209 size_t noPrintLen; /* length of noPrint command */
211 bool hasErrCtl; /* whether error checking can be controlled
212 * for individual commands */
213 const char *errOn; /* command to turn on error checking */
214 const char *errOff; /* command to turn off error checking */
216 const char *echoTmpl; /* template to echo a command */
217 const char *runIgnTmpl; /* template to run a command without error
219 const char *runChkTmpl; /* template to run a command with error
223 * A string literal that results in a newline character when it
224 * occurs outside of any 'quote' or "quote" characters.
227 char commentChar; /* character used by shell for comment lines */
229 const char *echoFlag; /* shell flag to echo commands */
230 const char *errFlag; /* shell flag to exit on error */
233 typedef struct CommandFlags {
234 /* Whether to echo the command before or instead of running it. */
237 /* Run the command even in -n or -N mode. */
241 * true if we turned error checking off before writing the command to
242 * the commands file and need to turn it back on
248 * Write shell commands to a file.
250 * TODO: keep track of whether commands are echoed.
251 * TODO: keep track of whether error checking is active.
253 typedef struct ShellWriter {
256 /* we've sent 'set -x' */
262 * FreeBSD: traditionally .MAKE is not required to
263 * pass jobs queue to sub-makes.
264 * Use .MAKE.ALWAYS_PASS_JOB_QUEUE=no to disable.
266 #define MAKE_ALWAYS_PASS_JOB_QUEUE "${.MAKE.ALWAYS_PASS_JOB_QUEUE:U}"
267 static bool Always_pass_job_queue = true;
269 * FreeBSD: aborting entire parallel make isn't always
270 * desired. When doing tinderbox for example, failure of
271 * one architecture should not stop all.
272 * We still want to bail on interrupt though.
274 #define MAKE_JOB_ERROR_TOKEN "${MAKE_JOB_ERROR_TOKEN:U}"
275 static bool Job_error_token = true;
278 * error handling variables
280 static int job_errors = 0; /* number of errors reported */
281 static enum { /* Why is the make aborting? */
283 ABORT_ERROR, /* Aborted because of an error */
284 ABORT_INTERRUPT, /* Aborted because it was interrupted */
285 ABORT_WAIT /* Waiting for jobs to finish */
286 } aborting = ABORT_NONE;
287 #define JOB_TOKENS "+EI+" /* Token to requeue for each abort state */
290 * this tracks the number of tokens currently "out" to build jobs.
292 int jobTokensRunning = 0;
294 typedef enum JobStartResult {
295 JOB_RUNNING, /* Job is running */
296 JOB_ERROR, /* Error in starting the job */
297 JOB_FINISHED /* The job is already finished */
301 * Descriptions for various shells.
303 * The build environment may set DEFSHELL_INDEX to one of
304 * DEFSHELL_INDEX_SH, DEFSHELL_INDEX_KSH, or DEFSHELL_INDEX_CSH, to
305 * select one of the predefined shells as the default shell.
307 * Alternatively, the build environment may set DEFSHELL_CUSTOM to the
308 * name or the full path of a sh-compatible shell, which will be used as
311 * ".SHELL" lines in Makefiles can choose the default shell from the
312 * set defined here, or add additional shells.
315 #ifdef DEFSHELL_CUSTOM
316 #define DEFSHELL_INDEX_CUSTOM 0
317 #define DEFSHELL_INDEX_SH 1
318 #define DEFSHELL_INDEX_KSH 2
319 #define DEFSHELL_INDEX_CSH 3
320 #else /* !DEFSHELL_CUSTOM */
321 #define DEFSHELL_INDEX_SH 0
322 #define DEFSHELL_INDEX_KSH 1
323 #define DEFSHELL_INDEX_CSH 2
324 #endif /* !DEFSHELL_CUSTOM */
326 #ifndef DEFSHELL_INDEX
327 #define DEFSHELL_INDEX 0 /* DEFSHELL_INDEX_CUSTOM or DEFSHELL_INDEX_SH */
328 #endif /* !DEFSHELL_INDEX */
330 static Shell shells[] = {
331 #ifdef DEFSHELL_CUSTOM
333 * An sh-compatible shell with a non-standard name.
335 * Keep this in sync with the "sh" description below, but avoid
336 * non-portable features that might not be supplied by all
337 * sh-compatible shells.
340 DEFSHELL_CUSTOM, /* .name */
341 false, /* .hasEchoCtl */
346 false, /* .hasErrCtl */
349 "echo \"%s\"\n", /* .echoTmpl */
350 "%s\n", /* .runIgnTmpl */
351 "{ %s \n} || exit $?\n", /* .runChkTmpl */
352 "'\n'", /* .newline */
353 '#', /* .commentChar */
357 #endif /* DEFSHELL_CUSTOM */
359 * SH description. Echo control is also possible and, under
360 * sun UNIX anyway, one can even control error checking.
364 false, /* .hasEchoCtl */
369 false, /* .hasErrCtl */
372 "echo \"%s\"\n", /* .echoTmpl */
373 "%s\n", /* .runIgnTmpl */
374 "{ %s \n} || exit $?\n", /* .runChkTmpl */
375 "'\n'", /* .newline */
376 '#', /* .commentChar*/
377 #if defined(MAKE_NATIVE) && defined(__NetBSD__)
378 /* XXX: -q is not really echoFlag, it's more like noEchoInSysFlag. */
390 true, /* .hasEchoCtl */
391 "set +v", /* .echoOff */
392 "set -v", /* .echoOn */
393 "set +v", /* .noPrint */
395 false, /* .hasErrCtl */
398 "echo \"%s\"\n", /* .echoTmpl */
399 "%s\n", /* .runIgnTmpl */
400 "{ %s \n} || exit $?\n", /* .runChkTmpl */
401 "'\n'", /* .newline */
402 '#', /* .commentChar */
407 * CSH description. The csh can do echo control by playing
408 * with the setting of the 'echo' shell variable. Sadly,
409 * however, it is unable to do error control nicely.
413 true, /* .hasEchoCtl */
414 "unset verbose", /* .echoOff */
415 "set verbose", /* .echoOn */
416 "unset verbose", /* .noPrint */
417 13, /* .noPrintLen */
418 false, /* .hasErrCtl */
421 "echo \"%s\"\n", /* .echoTmpl */
422 "csh -c \"%s || exit 0\"\n", /* .runIgnTmpl */
423 "", /* .runChkTmpl */
424 "'\\\n'", /* .newline */
425 '#', /* .commentChar */
432 * This is the shell to which we pass all commands in the Makefile.
433 * It is set by the Job_ParseShell function.
435 static Shell *shell = &shells[DEFSHELL_INDEX];
436 const char *shellPath = NULL; /* full pathname of executable image */
437 const char *shellName = NULL; /* last component of shellPath */
438 char *shellErrFlag = NULL;
439 static char *shell_freeIt = NULL; /* Allocated memory for custom .SHELL */
442 static Job *job_table; /* The structures that describe them */
443 static Job *job_table_end; /* job_table + maxJobs */
444 static unsigned int wantToken; /* we want a token */
445 static bool lurking_children = false;
446 static bool make_suspended = false; /* Whether we've seen a SIGTSTP (etc) */
449 * Set of descriptors of pipes connected to
450 * the output channels of children
452 static struct pollfd *fds = NULL;
453 static Job **jobByFdIndex = NULL;
454 static nfds_t fdsLen = 0;
455 static void watchfd(Job *);
456 static void clearfd(Job *);
457 static bool readyfd(Job *);
459 static char *targPrefix = NULL; /* To identify a job change in the output. */
460 static Job tokenWaitJob; /* token wait pseudo-job */
462 static Job childExitJob; /* child exit pseudo-job */
463 #define CHILD_EXIT "."
464 #define DO_JOB_RESUME "R"
467 npseudojobs = 2 /* number of pseudo-jobs */
470 static sigset_t caught_signals; /* Set of signals we handle */
471 static volatile sig_atomic_t caught_sigchld;
473 static void CollectOutput(Job *, bool);
474 static void JobInterrupt(bool, int) MAKE_ATTR_DEAD;
475 static void JobRestartJobs(void);
476 static void JobSigReset(void);
479 SwitchOutputTo(GNode *gn)
481 /* The node for which output was most recently produced. */
482 static GNode *lastNode = NULL;
488 if (opts.maxJobs != 1 && targPrefix != NULL && targPrefix[0] != '\0')
489 (void)fprintf(stdout, "%s %s ---\n", targPrefix, gn->name);
495 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
503 Job_FlagsToString(const Job *job, char *buf, size_t bufsize)
505 snprintf(buf, bufsize, "%c%c%c",
506 job->ignerr ? 'i' : '-',
507 !job->echo ? 's' : '-',
508 job->special ? 'S' : '-');
512 DumpJobs(const char *where)
517 debug_printf("job table @ %s\n", where);
518 for (job = job_table; job < job_table_end; job++) {
519 Job_FlagsToString(job, flags, sizeof flags);
520 debug_printf("job %d, status %d, flags %s, pid %d\n",
521 (int)(job - job_table), job->status, flags, job->pid);
526 * Delete the target of a failed, interrupted, or otherwise
527 * unsuccessful job unless inhibited by .PRECIOUS.
530 JobDeleteTarget(GNode *gn)
534 if (gn->type & OP_JOIN)
536 if (gn->type & OP_PHONY)
538 if (GNode_IsPrecious(gn))
543 file = GNode_Path(gn);
544 if (unlink_file(file) == 0)
545 Error("*** %s removed", file);
549 * JobSigLock/JobSigUnlock
551 * Signal lock routines to get exclusive access. Currently used to
552 * protect `jobs' and `stoppedJobs' list manipulations.
555 JobSigLock(sigset_t *omaskp)
557 if (sigprocmask(SIG_BLOCK, &caught_signals, omaskp) != 0) {
558 Punt("JobSigLock: sigprocmask: %s", strerror(errno));
564 JobSigUnlock(sigset_t *omaskp)
566 (void)sigprocmask(SIG_SETMASK, omaskp, NULL);
570 JobCreatePipe(Job *job, int minfd)
575 if (pipe(pipe_fds) == -1)
576 Punt("Cannot create pipe: %s", strerror(errno));
578 for (i = 0; i < 2; i++) {
579 /* Avoid using low numbered fds */
580 fd = fcntl(pipe_fds[i], F_DUPFD, minfd);
587 job->inPipe = pipe_fds[0];
588 job->outPipe = pipe_fds[1];
590 /* Set close-on-exec flag for both */
591 if (fcntl(job->inPipe, F_SETFD, FD_CLOEXEC) == -1)
592 Punt("Cannot set close-on-exec: %s", strerror(errno));
593 if (fcntl(job->outPipe, F_SETFD, FD_CLOEXEC) == -1)
594 Punt("Cannot set close-on-exec: %s", strerror(errno));
597 * We mark the input side of the pipe non-blocking; we poll(2) the
598 * pipe when we're waiting for a job token, but we might lose the
599 * race for the token when a new one becomes available, so the read
600 * from the pipe should not block.
602 flags = fcntl(job->inPipe, F_GETFL, 0);
604 Punt("Cannot get flags: %s", strerror(errno));
606 if (fcntl(job->inPipe, F_SETFL, flags) == -1)
607 Punt("Cannot set flags: %s", strerror(errno));
610 /* Pass the signal to each running job. */
612 JobCondPassSig(int signo)
616 DEBUG1(JOB, "JobCondPassSig(%d) called.\n", signo);
618 for (job = job_table; job < job_table_end; job++) {
619 if (job->status != JOB_ST_RUNNING)
621 DEBUG2(JOB, "JobCondPassSig passing signal %d to child %d.\n",
623 KILLPG(job->pid, signo);
630 * Sends a token on the child exit pipe to wake us up from select()/poll().
634 JobChildSig(int signo MAKE_ATTR_UNUSED)
637 while (write(childExitJob.outPipe, CHILD_EXIT, 1) == -1 &&
643 /* Resume all stopped jobs. */
646 JobContinueSig(int signo MAKE_ATTR_UNUSED)
649 * Defer sending SIGCONT to our stopped children until we return
650 * from the signal handler.
652 while (write(childExitJob.outPipe, DO_JOB_RESUME, 1) == -1 &&
658 * Pass a signal on to all jobs, then resend to ourselves.
659 * We die by the same signal.
661 MAKE_ATTR_DEAD static void
662 JobPassSig_int(int signo)
664 /* Run .INTERRUPT target then exit */
665 JobInterrupt(true, signo);
669 * Pass a signal on to all jobs, then resend to ourselves.
670 * We die by the same signal.
672 MAKE_ATTR_DEAD static void
673 JobPassSig_term(int signo)
675 /* Dont run .INTERRUPT target then exit */
676 JobInterrupt(false, signo);
680 JobPassSig_suspend(int signo)
682 sigset_t nmask, omask;
683 struct sigaction act;
685 /* Suppress job started/continued messages */
686 make_suspended = true;
688 /* Pass the signal onto every job */
689 JobCondPassSig(signo);
692 * Send ourselves the signal now we've given the message to everyone
693 * else. Note we block everything else possible while we're getting
694 * the signal. This ensures that all our jobs get continued when we
695 * wake up before we take any other signal.
698 sigdelset(&nmask, signo);
699 (void)sigprocmask(SIG_SETMASK, &nmask, &omask);
701 act.sa_handler = SIG_DFL;
702 sigemptyset(&act.sa_mask);
704 (void)sigaction(signo, &act, NULL);
706 DEBUG1(JOB, "JobPassSig passing signal %d to self.\n", signo);
708 (void)kill(getpid(), signo);
711 * We've been continued.
713 * A whole host of signals continue to happen!
714 * SIGCHLD for any processes that actually suspended themselves.
715 * SIGCHLD for any processes that exited while we were alseep.
716 * The SIGCONT that actually caused us to wakeup.
718 * Since we defer passing the SIGCONT on to our children until
719 * the main processing loop, we can be sure that all the SIGCHLD
720 * events will have happened by then - and that the waitpid() will
721 * collect the child 'suspended' events.
722 * For correct sequencing we just need to ensure we process the
723 * waitpid() before passing on the SIGCONT.
725 * In any case nothing else is needed here.
728 /* Restore handler and signal mask */
729 act.sa_handler = JobPassSig_suspend;
730 (void)sigaction(signo, &act, NULL);
731 (void)sigprocmask(SIG_SETMASK, &omask, NULL);
735 JobFindPid(int pid, JobStatus status, bool isJobs)
739 for (job = job_table; job < job_table_end; job++) {
740 if (job->status == status && job->pid == pid)
743 if (DEBUG(JOB) && isJobs)
748 /* Parse leading '@', '-' and '+', which control the exact execution mode. */
750 ParseCommandFlags(char **pp, CommandFlags *out_cmdFlags)
753 out_cmdFlags->echo = true;
754 out_cmdFlags->ignerr = false;
755 out_cmdFlags->always = false;
759 out_cmdFlags->echo = DEBUG(LOUD);
761 out_cmdFlags->ignerr = true;
763 out_cmdFlags->always = true;
764 else if (!ch_isspace(*p))
765 /* Ignore whitespace for compatibility with gnu make */
770 pp_skip_whitespace(&p);
775 /* Escape a string for a double-quoted string literal in sh, csh and ksh. */
777 EscapeShellDblQuot(const char *cmd)
781 /* Worst that could happen is every char needs escaping. */
782 char *esc = bmake_malloc(strlen(cmd) * 2 + 1);
783 for (i = 0, j = 0; cmd[i] != '\0'; i++, j++) {
784 if (cmd[i] == '$' || cmd[i] == '`' || cmd[i] == '\\' ||
795 ShellWriter_WriteFmt(ShellWriter *wr, const char *fmt, const char *arg)
797 DEBUG1(JOB, fmt, arg);
799 (void)fprintf(wr->f, fmt, arg);
805 ShellWriter_WriteLine(ShellWriter *wr, const char *line)
807 ShellWriter_WriteFmt(wr, "%s\n", line);
811 ShellWriter_EchoOff(ShellWriter *wr)
813 if (shell->hasEchoCtl)
814 ShellWriter_WriteLine(wr, shell->echoOff);
818 ShellWriter_EchoCmd(ShellWriter *wr, const char *escCmd)
820 ShellWriter_WriteFmt(wr, shell->echoTmpl, escCmd);
824 ShellWriter_EchoOn(ShellWriter *wr)
826 if (shell->hasEchoCtl)
827 ShellWriter_WriteLine(wr, shell->echoOn);
831 ShellWriter_TraceOn(ShellWriter *wr)
834 ShellWriter_WriteLine(wr, "set -x");
840 ShellWriter_ErrOff(ShellWriter *wr, bool echo)
843 ShellWriter_EchoOff(wr);
844 ShellWriter_WriteLine(wr, shell->errOff);
846 ShellWriter_EchoOn(wr);
850 ShellWriter_ErrOn(ShellWriter *wr, bool echo)
853 ShellWriter_EchoOff(wr);
854 ShellWriter_WriteLine(wr, shell->errOn);
856 ShellWriter_EchoOn(wr);
860 * The shell has no built-in error control, so emulate error control by
861 * enclosing each shell command in a template like "{ %s \n } || exit $?"
862 * (configurable per shell).
865 JobWriteSpecialsEchoCtl(Job *job, ShellWriter *wr, CommandFlags *inout_cmdFlags,
866 const char *escCmd, const char **inout_cmdTemplate)
868 /* XXX: Why is the whole job modified at this point? */
871 if (job->echo && inout_cmdFlags->echo) {
872 ShellWriter_EchoOff(wr);
873 ShellWriter_EchoCmd(wr, escCmd);
876 * Leave echoing off so the user doesn't see the commands
877 * for toggling the error checking.
879 inout_cmdFlags->echo = false;
881 *inout_cmdTemplate = shell->runIgnTmpl;
884 * The template runIgnTmpl already takes care of ignoring errors,
885 * so pretend error checking is still on.
886 * XXX: What effects does this have, and why is it necessary?
888 inout_cmdFlags->ignerr = false;
892 JobWriteSpecials(Job *job, ShellWriter *wr, const char *escCmd, bool run,
893 CommandFlags *inout_cmdFlags, const char **inout_cmdTemplate)
897 * If there is no command to run, there is no need to switch
898 * error checking off and on again for nothing.
900 inout_cmdFlags->ignerr = false;
901 } else if (shell->hasErrCtl)
902 ShellWriter_ErrOff(wr, job->echo && inout_cmdFlags->echo);
903 else if (shell->runIgnTmpl != NULL && shell->runIgnTmpl[0] != '\0') {
904 JobWriteSpecialsEchoCtl(job, wr, inout_cmdFlags, escCmd,
907 inout_cmdFlags->ignerr = false;
911 * Write a shell command to the job's commands file, to be run later.
913 * If the command starts with '@' and neither the -s nor the -n flag was
914 * given to make, stick a shell-specific echoOff command in the script.
916 * If the command starts with '-' and the shell has no error control (none
917 * of the predefined shells has that), ignore errors for the entire job.
919 * XXX: Why ignore errors for the entire job? This is even documented in the
920 * manual page, but without any rationale since there is no known rationale.
922 * XXX: The manual page says the '-' "affects the entire job", but that's not
923 * accurate. The '-' does not affect the commands before the '-'.
925 * If the command is just "...", skip all further commands of this job. These
926 * commands are attached to the .END node instead and will be run by
927 * Job_Finish after all other targets have been made.
930 JobWriteCommand(Job *job, ShellWriter *wr, StringListNode *ln, const char *ucmd)
934 CommandFlags cmdFlags;
935 /* Template for writing a command to the shell file */
936 const char *cmdTemplate;
937 char *xcmd; /* The expanded command */
939 char *escCmd; /* xcmd escaped to be used in double quotes */
941 run = GNode_ShouldExecute(job->node);
943 xcmd = Var_Subst(ucmd, job->node, VARE_WANTRES);
944 /* TODO: handle errors */
947 cmdTemplate = "%s\n";
949 ParseCommandFlags(&xcmd, &cmdFlags);
951 /* The '+' command flag overrides the -n or -N options. */
952 if (cmdFlags.always && !run) {
954 * We're not actually executing anything...
955 * but this one needs to be - use compat mode just for it.
957 (void)Compat_RunCommand(ucmd, job->node, ln);
963 * If the shell doesn't have error control, the alternate echoing
964 * will be done (to avoid showing additional error checking code)
965 * and this needs some characters escaped.
967 escCmd = shell->hasErrCtl ? NULL : EscapeShellDblQuot(xcmd);
969 if (!cmdFlags.echo) {
970 if (job->echo && run && shell->hasEchoCtl) {
971 ShellWriter_EchoOff(wr);
973 if (shell->hasErrCtl)
974 cmdFlags.echo = true;
978 if (cmdFlags.ignerr) {
979 JobWriteSpecials(job, wr, escCmd, run, &cmdFlags, &cmdTemplate);
983 * If errors are being checked and the shell doesn't have
984 * error control but does supply an runChkTmpl template, then
985 * set up commands to run through it.
988 if (!shell->hasErrCtl && shell->runChkTmpl != NULL &&
989 shell->runChkTmpl[0] != '\0') {
990 if (job->echo && cmdFlags.echo) {
991 ShellWriter_EchoOff(wr);
992 ShellWriter_EchoCmd(wr, escCmd);
993 cmdFlags.echo = false;
996 * If it's a comment line or blank, avoid the possible
997 * syntax error generated by "{\n} || exit $?".
999 cmdTemplate = escCmd[0] == shell->commentChar ||
1002 : shell->runChkTmpl;
1003 cmdFlags.ignerr = false;
1007 if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0)
1008 ShellWriter_TraceOn(wr);
1010 ShellWriter_WriteFmt(wr, cmdTemplate, xcmd);
1014 if (cmdFlags.ignerr)
1015 ShellWriter_ErrOn(wr, cmdFlags.echo && job->echo);
1018 ShellWriter_EchoOn(wr);
1022 * Write all commands to the shell file that is later executed.
1024 * The special command "..." stops writing and saves the remaining commands
1025 * to be executed later, when the target '.END' is made.
1027 * Return whether at least one command was written to the shell file.
1030 JobWriteCommands(Job *job)
1036 wr.f = job->cmdFILE;
1039 for (ln = job->node->commands.first; ln != NULL; ln = ln->next) {
1040 const char *cmd = ln->datum;
1042 if (strcmp(cmd, "...") == 0) {
1043 job->node->type |= OP_SAVE_CMDS;
1044 job->tailCmds = ln->next;
1048 JobWriteCommand(job, &wr, ln, ln->datum);
1056 * Save the delayed commands (those after '...'), to be executed later in
1057 * the '.END' node, when everything else is done.
1060 JobSaveCommands(Job *job)
1064 for (ln = job->tailCmds; ln != NULL; ln = ln->next) {
1065 const char *cmd = ln->datum;
1068 * XXX: This Var_Subst is only intended to expand the dynamic
1069 * variables such as .TARGET, .IMPSRC. It is not intended to
1070 * expand the other variables as well; see deptgt-end.mk.
1072 expanded_cmd = Var_Subst(cmd, job->node, VARE_WANTRES);
1073 /* TODO: handle errors */
1074 Lst_Append(&Targ_GetEndNode()->commands, expanded_cmd);
1079 /* Called to close both input and output pipes when a job is finished. */
1081 JobClosePipes(Job *job)
1084 (void)close(job->outPipe);
1087 CollectOutput(job, true);
1088 (void)close(job->inPipe);
1093 DebugFailedJob(const Job *job)
1095 const StringListNode *ln;
1101 debug_printf("*** Failed target: %s\n", job->node->name);
1102 debug_printf("*** Failed commands:\n");
1103 for (ln = job->node->commands.first; ln != NULL; ln = ln->next) {
1104 const char *cmd = ln->datum;
1105 debug_printf("\t%s\n", cmd);
1107 if (strchr(cmd, '$') != NULL) {
1108 char *xcmd = Var_Subst(cmd, job->node, VARE_WANTRES);
1109 debug_printf("\t=> %s\n", xcmd);
1116 JobFinishDoneExitedError(Job *job, WAIT_T *inout_status)
1118 SwitchOutputTo(job->node);
1121 meta_job_error(job, job->node,
1122 job->ignerr, WEXITSTATUS(*inout_status));
1125 if (!shouldDieQuietly(job->node, -1)) {
1126 DebugFailedJob(job);
1127 (void)printf("*** [%s] Error code %d%s\n",
1128 job->node->name, WEXITSTATUS(*inout_status),
1129 job->ignerr ? " (ignored)" : "");
1133 WAIT_STATUS(*inout_status) = 0;
1136 JobDeleteTarget(job->node);
1137 PrintOnError(job->node, "\n");
1142 JobFinishDoneExited(Job *job, WAIT_T *inout_status)
1144 DEBUG2(JOB, "Process %d [%s] exited.\n", job->pid, job->node->name);
1146 if (WEXITSTATUS(*inout_status) != 0)
1147 JobFinishDoneExitedError(job, inout_status);
1148 else if (DEBUG(JOB)) {
1149 SwitchOutputTo(job->node);
1150 (void)printf("*** [%s] Completed successfully\n",
1156 JobFinishDoneSignaled(Job *job, WAIT_T status)
1158 SwitchOutputTo(job->node);
1159 DebugFailedJob(job);
1160 (void)printf("*** [%s] Signal %d\n", job->node->name, WTERMSIG(status));
1162 JobDeleteTarget(job->node);
1166 JobFinishDone(Job *job, WAIT_T *inout_status)
1168 if (WIFEXITED(*inout_status))
1169 JobFinishDoneExited(job, inout_status);
1171 JobFinishDoneSignaled(job, *inout_status);
1173 (void)fflush(stdout);
1177 * Do final processing for the given job including updating parent nodes and
1178 * starting new jobs as available/necessary.
1180 * Deferred commands for the job are placed on the .END node.
1182 * If there was a serious error (job_errors != 0; not an ignored one), no more
1183 * jobs will be started.
1187 * status sub-why job went away
1190 JobFinish (Job *job, WAIT_T status)
1192 bool done, return_job_token;
1194 DEBUG3(JOB, "JobFinish: %d [%s], status %d\n",
1195 job->pid, job->node->name, status);
1197 if ((WIFEXITED(status) &&
1198 ((WEXITSTATUS(status) != 0 && !job->ignerr))) ||
1199 WIFSIGNALED(status)) {
1200 /* Finished because of an error. */
1203 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1204 if (fclose(job->cmdFILE) != 0)
1205 Punt("Cannot write shell script for '%s': %s",
1206 job->node->name, strerror(errno));
1207 job->cmdFILE = NULL;
1211 } else if (WIFEXITED(status)) {
1213 * Deal with ignored errors in -B mode. We need to print a
1214 * message telling of the ignored error as well as to run
1217 done = WEXITSTATUS(status) != 0;
1222 /* No need to close things down or anything. */
1227 JobFinishDone(job, &status);
1231 int meta_status = meta_job_finish(job);
1232 if (meta_status != 0 && status == 0)
1233 status = meta_status;
1237 return_job_token = false;
1239 Trace_Log(JOBEND, job);
1240 if (!job->special) {
1241 if (WAIT_STATUS(status) != 0 ||
1242 (aborting == ABORT_ERROR) || aborting == ABORT_INTERRUPT)
1243 return_job_token = true;
1246 if (aborting != ABORT_ERROR && aborting != ABORT_INTERRUPT &&
1247 (WAIT_STATUS(status) == 0)) {
1249 * As long as we aren't aborting and the job didn't return a
1250 * non-zero status that we shouldn't ignore, we call
1251 * Make_Update to update the parents.
1253 JobSaveCommands(job);
1254 job->node->made = MADE;
1256 return_job_token = true;
1257 Make_Update(job->node);
1258 job->status = JOB_ST_FREE;
1259 } else if (status != 0) {
1261 job->status = JOB_ST_FREE;
1264 if (job_errors > 0 && !opts.keepgoing && aborting != ABORT_INTERRUPT) {
1265 /* Prevent more jobs from getting started. */
1266 aborting = ABORT_ERROR;
1269 if (return_job_token)
1272 if (aborting == ABORT_ERROR && jobTokensRunning == 0)
1277 TouchRegular(GNode *gn)
1279 const char *file = GNode_Path(gn);
1280 struct utimbuf times;
1285 times.modtime = now;
1286 if (utime(file, ×) >= 0)
1289 fd = open(file, O_RDWR | O_CREAT, 0666);
1291 (void)fprintf(stderr, "*** couldn't touch %s: %s\n",
1292 file, strerror(errno));
1293 (void)fflush(stderr);
1294 return; /* XXX: What about propagating the error? */
1298 * Last resort: update the file's time stamps in the traditional way.
1299 * XXX: This doesn't work for empty files, which are sometimes used
1302 if (read(fd, &c, 1) == 1) {
1303 (void)lseek(fd, 0, SEEK_SET);
1304 while (write(fd, &c, 1) == -1 && errno == EAGAIN)
1307 (void)close(fd); /* XXX: What about propagating the error? */
1311 * Touch the given target. Called by JobStart when the -t flag was given.
1313 * The modification date of the file is changed.
1314 * If the file did not exist, it is created.
1317 Job_Touch(GNode *gn, bool echo)
1320 (OP_JOIN | OP_USE | OP_USEBEFORE | OP_EXEC | OP_OPTIONAL |
1321 OP_SPECIAL | OP_PHONY)) {
1323 * These are "virtual" targets and should not really be
1329 if (echo || !GNode_ShouldExecute(gn)) {
1330 (void)fprintf(stdout, "touch %s\n", gn->name);
1331 (void)fflush(stdout);
1334 if (!GNode_ShouldExecute(gn))
1337 if (gn->type & OP_ARCHV)
1339 else if (gn->type & OP_LIB)
1346 * Make sure the given node has all the commands it needs.
1348 * The node will have commands from the .DEFAULT rule added to it if it
1352 * gn The target whose commands need verifying
1353 * abortProc Function to abort with message
1356 * true if the commands list is/was ok.
1359 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1361 if (GNode_IsTarget(gn))
1363 if (!Lst_IsEmpty(&gn->commands))
1365 if ((gn->type & OP_LIB) && !Lst_IsEmpty(&gn->children))
1369 * No commands. Look for .DEFAULT rule from which we might infer
1372 if (defaultNode != NULL && !Lst_IsEmpty(&defaultNode->commands) &&
1373 !(gn->type & OP_SPECIAL)) {
1375 * The traditional Make only looks for a .DEFAULT if the node
1376 * was never the target of an operator, so that's what we do
1379 * The .DEFAULT node acts like a transformation rule, in that
1380 * gn also inherits any attributes or sources attached to
1383 Make_HandleUse(defaultNode, gn);
1384 Var_Set(gn, IMPSRC, GNode_VarTarget(gn));
1388 Dir_UpdateMTime(gn, false);
1389 if (gn->mtime != 0 || (gn->type & OP_SPECIAL))
1393 * The node wasn't the target of an operator. We have no .DEFAULT
1394 * rule to go on and the target doesn't already exist. There's
1395 * nothing more we can do for this branch. If the -k flag wasn't
1396 * given, we stop in our tracks, otherwise we just don't update
1397 * this node's parents so they never get examined.
1400 if (gn->flags.fromDepend) {
1401 if (!Job_RunTarget(".STALE", gn->fname))
1403 "%s: %s, %u: ignoring stale %s for %s\n",
1404 progname, gn->fname, gn->lineno, makeDependfile,
1409 if (gn->type & OP_OPTIONAL) {
1410 (void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
1411 progname, gn->name, "ignored");
1412 (void)fflush(stdout);
1416 if (opts.keepgoing) {
1417 (void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
1418 progname, gn->name, "continuing");
1419 (void)fflush(stdout);
1423 abortProc("%s: don't know how to make %s. Stop", progname, gn->name);
1428 * Execute the shell for the given job.
1430 * See Job_CatchOutput for handling the output of the shell.
1433 JobExec(Job *job, char **argv)
1435 int cpid; /* ID of new child */
1441 debug_printf("Running %s\n", job->node->name);
1442 debug_printf("\tCommand: ");
1443 for (i = 0; argv[i] != NULL; i++) {
1444 debug_printf("%s ", argv[i]);
1450 * Some jobs produce no output and it's disconcerting to have
1451 * no feedback of their running (since they produce no output, the
1452 * banner with their name in it never appears). This is an attempt to
1453 * provide that feedback, even if nothing follows it.
1456 SwitchOutputTo(job->node);
1458 /* No interruptions until this job is on the `jobs' list */
1461 /* Pre-emptively mark job running, pid still zero though */
1462 job->status = JOB_ST_RUNNING;
1468 Punt("Cannot vfork: %s", strerror(errno));
1476 meta_job_child(job);
1479 * Reset all signal handlers; this is necessary because we
1480 * also need to unblock signals before we exec(2).
1484 /* Now unblock signals */
1485 sigemptyset(&tmask);
1486 JobSigUnlock(&tmask);
1489 * Must duplicate the input stream down to the child's input
1490 * and reset it to the beginning (again). Since the stream
1491 * was marked close-on-exec, we must clear that bit in the
1494 if (dup2(fileno(job->cmdFILE), 0) == -1)
1495 execDie("dup2", "job->cmdFILE");
1496 if (fcntl(0, F_SETFD, 0) == -1)
1497 execDie("fcntl clear close-on-exec", "stdin");
1498 if (lseek(0, 0, SEEK_SET) == -1)
1499 execDie("lseek to 0", "stdin");
1501 if (Always_pass_job_queue ||
1502 (job->node->type & (OP_MAKE | OP_SUBMAKE))) {
1504 * Pass job token pipe to submakes.
1506 if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1)
1507 execDie("clear close-on-exec",
1508 "tokenWaitJob.inPipe");
1509 if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1)
1510 execDie("clear close-on-exec",
1511 "tokenWaitJob.outPipe");
1515 * Set up the child's output to be routed through the pipe
1516 * we've created for it.
1518 if (dup2(job->outPipe, 1) == -1)
1519 execDie("dup2", "job->outPipe");
1522 * The output channels are marked close on exec. This bit
1523 * was duplicated by the dup2(on some systems), so we have
1524 * to clear it before routing the shell's error output to
1525 * the same place as its standard output.
1527 if (fcntl(1, F_SETFD, 0) == -1)
1528 execDie("clear close-on-exec", "stdout");
1529 if (dup2(1, 2) == -1)
1530 execDie("dup2", "1, 2");
1533 * We want to switch the child into a different process
1534 * family so we can kill it and all its descendants in
1535 * one fell swoop, by killing its process family, but not
1538 #if defined(HAVE_SETPGID)
1539 (void)setpgid(0, getpid());
1541 # if defined(HAVE_SETSID)
1542 /* XXX: dsl - I'm sure this should be setpgrp()... */
1545 (void)setpgrp(0, getpid());
1549 (void)execv(shellPath, argv);
1550 execDie("exec", shellPath);
1553 /* Parent, continuing after the child exec */
1556 Trace_Log(JOBSTART, job);
1560 meta_job_parent(job, cpid);
1564 * Set the current position in the buffer to the beginning
1565 * and mark another stream to watch in the outputs mask
1571 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1572 if (fclose(job->cmdFILE) != 0)
1573 Punt("Cannot write shell script for '%s': %s",
1574 job->node->name, strerror(errno));
1575 job->cmdFILE = NULL;
1578 /* Now that the job is actually running, add it to the table. */
1580 debug_printf("JobExec(%s): pid %d added to jobs table\n",
1581 job->node->name, job->pid);
1582 DumpJobs("job started");
1584 JobSigUnlock(&mask);
1587 /* Create the argv needed to execute the shell for a given job. */
1589 JobMakeArgv(Job *job, char **argv)
1592 static char args[10]; /* For merged arguments */
1594 argv[0] = UNCONST(shellName);
1597 if ((shell->errFlag != NULL && shell->errFlag[0] != '-') ||
1598 (shell->echoFlag != NULL && shell->echoFlag[0] != '-')) {
1600 * At least one of the flags doesn't have a minus before it,
1601 * so merge them together. Have to do this because the Bourne
1602 * shell thinks its second argument is a file to source.
1603 * Grrrr. Note the ten-character limitation on the combined
1606 * TODO: Research until when the above comments were
1607 * practically relevant.
1609 (void)snprintf(args, sizeof args, "-%s%s",
1611 (shell->errFlag != NULL ? shell->errFlag : "")),
1613 (shell->echoFlag != NULL ? shell->echoFlag : "")));
1615 if (args[1] != '\0') {
1620 if (!job->ignerr && shell->errFlag != NULL) {
1621 argv[argc] = UNCONST(shell->errFlag);
1624 if (job->echo && shell->echoFlag != NULL) {
1625 argv[argc] = UNCONST(shell->echoFlag);
1633 JobWriteShellCommands(Job *job, GNode *gn, bool *out_run)
1636 * tfile is the name of a file into which all shell commands
1637 * are put. It is removed before the child shell is executed,
1638 * unless DEBUG(SCRIPT) is set.
1640 char tfile[MAXPATHLEN];
1641 int tfd; /* File descriptor to the temp file */
1643 tfd = Job_TempFile(TMPPAT, tfile, sizeof tfile);
1645 job->cmdFILE = fdopen(tfd, "w+");
1646 if (job->cmdFILE == NULL)
1647 Punt("Could not fdopen %s", tfile);
1649 (void)fcntl(fileno(job->cmdFILE), F_SETFD, FD_CLOEXEC);
1653 meta_job_start(job, gn);
1654 if (gn->type & OP_SILENT) /* might have changed */
1659 *out_run = JobWriteCommands(job);
1663 * Start a target-creation process going for the target described by gn.
1666 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1667 * if there isn't actually anything left to do for the job and
1668 * JOB_RUNNING if the job has been started.
1671 * A new Job node is created and added to the list of running
1672 * jobs. PMake is forked and a child shell created.
1674 * NB: The return value is ignored by everyone.
1676 static JobStartResult
1677 JobStart(GNode *gn, bool special)
1679 Job *job; /* new job descriptor */
1680 char *argv[10]; /* Argument vector to shell */
1681 bool cmdsOK; /* true if the nodes commands were all right */
1684 for (job = job_table; job < job_table_end; job++) {
1685 if (job->status == JOB_ST_FREE)
1688 if (job >= job_table_end)
1689 Punt("JobStart no job slots vacant");
1691 memset(job, 0, sizeof *job);
1693 job->tailCmds = NULL;
1694 job->status = JOB_ST_SET_UP;
1696 job->special = special || gn->type & OP_SPECIAL;
1697 job->ignerr = opts.ignoreErrors || gn->type & OP_IGNORE;
1698 job->echo = !(opts.silent || gn->type & OP_SILENT);
1701 * Check the commands now so any attributes from .DEFAULT have a
1702 * chance to migrate to the node.
1704 cmdsOK = Job_CheckCommands(gn, Error);
1706 job->inPollfd = NULL;
1708 if (Lst_IsEmpty(&gn->commands)) {
1709 job->cmdFILE = stdout;
1713 * We're serious here, but if the commands were bogus, we're
1717 PrintOnError(gn, "\n"); /* provide some clue */
1720 } else if (((gn->type & OP_MAKE) && !opts.noRecursiveExecute) ||
1721 (!opts.noExecute && !opts.touch)) {
1723 * The above condition looks very similar to
1724 * GNode_ShouldExecute but is subtly different. It prevents
1725 * that .MAKE targets are touched since these are usually
1730 * We're serious here, but if the commands were bogus, we're
1734 PrintOnError(gn, "\n"); /* provide some clue */
1738 JobWriteShellCommands(job, gn, &run);
1739 (void)fflush(job->cmdFILE);
1740 } else if (!GNode_ShouldExecute(gn)) {
1742 * Just write all the commands to stdout in one fell swoop.
1743 * This still sets up job->tailCmds correctly.
1746 job->cmdFILE = stdout;
1748 JobWriteCommands(job);
1750 (void)fflush(job->cmdFILE);
1752 Job_Touch(gn, job->echo);
1756 /* If we're not supposed to execute a shell, don't. */
1760 /* Unlink and close the command file if we opened one */
1761 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1762 (void)fclose(job->cmdFILE);
1763 job->cmdFILE = NULL;
1767 * We only want to work our way up the graph if we aren't
1768 * here because the commands for the job were no good.
1770 if (cmdsOK && aborting == ABORT_NONE) {
1771 JobSaveCommands(job);
1772 job->node->made = MADE;
1773 Make_Update(job->node);
1775 job->status = JOB_ST_FREE;
1776 return cmdsOK ? JOB_FINISHED : JOB_ERROR;
1780 * Set up the control arguments to the shell. This is based on the
1781 * flags set earlier for this job.
1783 JobMakeArgv(job, argv);
1785 /* Create the pipe by which we'll get the shell's output. */
1786 JobCreatePipe(job, 3);
1793 * If the shell has an output filter (which only csh and ksh have by default),
1794 * print the output of the child process, skipping the noPrint text of the
1797 * Return the part of the output that the calling function needs to output by
1801 PrintFilteredOutput(char *cp, char *endp) /* XXX: should all be const */
1803 char *ecp; /* XXX: should be const */
1805 if (shell->noPrint == NULL || shell->noPrint[0] == '\0')
1809 * XXX: What happens if shell->noPrint occurs on the boundary of
1810 * the buffer? To work correctly in all cases, this should rather
1811 * be a proper stream filter instead of doing string matching on
1812 * selected chunks of the output.
1814 while ((ecp = strstr(cp, shell->noPrint)) != NULL) {
1816 *ecp = '\0'; /* XXX: avoid writing to the buffer */
1818 * The only way there wouldn't be a newline after
1819 * this line is if it were the last in the buffer.
1820 * however, since the noPrint output comes after it,
1821 * there must be a newline, so we don't print one.
1823 /* XXX: What about null bytes in the output? */
1824 (void)fprintf(stdout, "%s", cp);
1825 (void)fflush(stdout);
1827 cp = ecp + shell->noPrintLen;
1830 cp++; /* skip over the (XXX: assumed) newline */
1831 pp_skip_whitespace(&cp);
1837 * This function is called whenever there is something to read on the pipe.
1838 * We collect more output from the given job and store it in the job's
1839 * outBuf. If this makes up a line, we print it tagged by the job's
1840 * identifier, as necessary.
1842 * In the output of the shell, the 'noPrint' lines are removed. If the
1843 * command is not alone on the line (the character after it is not \0 or
1844 * \n), we do print whatever follows it.
1847 * job the job whose output needs printing
1848 * finish true if this is the last time we'll be called
1852 CollectOutput(Job *job, bool finish)
1854 bool gotNL; /* true if got a newline */
1855 bool fbuf; /* true if our buffer filled up */
1856 size_t nr; /* number of bytes read */
1857 size_t i; /* auxiliary index into outBuf */
1858 size_t max; /* limit for i (end of current data) */
1859 ssize_t nRead; /* (Temporary) number of bytes read */
1861 /* Read as many bytes as will fit in the buffer. */
1866 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1867 JOB_BUFSIZE - job->curPos);
1869 if (errno == EAGAIN)
1872 perror("CollectOutput(piperead)");
1878 finish = false; /* stop looping */
1881 * If we hit the end-of-file (the job is dead), we must flush its
1882 * remaining output, so pretend we read a newline if there's any
1883 * output remaining in the buffer.
1885 if (nr == 0 && job->curPos != 0) {
1886 job->outBuf[job->curPos] = '\n';
1890 max = job->curPos + nr;
1891 for (i = job->curPos; i < max; i++)
1892 if (job->outBuf[i] == '\0')
1893 job->outBuf[i] = ' ';
1895 /* Look for the last newline in the bytes we just got. */
1896 for (i = job->curPos + nr - 1;
1897 i >= job->curPos && i != (size_t)-1; i--) {
1898 if (job->outBuf[i] == '\n') {
1906 if (job->curPos == JOB_BUFSIZE) {
1908 * If we've run out of buffer space, we have no choice
1909 * but to print the stuff. sigh.
1915 if (gotNL || fbuf) {
1917 * Need to send the output to the screen. Null terminate it
1918 * first, overwriting the newline character if there was one.
1919 * So long as the line isn't one we should filter (according
1920 * to the shell description), we print the line, preceded
1921 * by a target banner if this target isn't the same as the
1922 * one for which we last printed something.
1923 * The rest of the data in the buffer are then shifted down
1924 * to the start of the buffer and curPos is set accordingly.
1926 job->outBuf[i] = '\0';
1927 if (i >= job->curPos) {
1931 * FIXME: SwitchOutputTo should be here, according to
1932 * the comment above. But since PrintOutput does not
1933 * do anything in the default shell, this bug has gone
1934 * unnoticed until now.
1936 cp = PrintFilteredOutput(job->outBuf, &job->outBuf[i]);
1939 * There's still more in the output buffer. This time,
1940 * though, we know there's no newline at the end, so
1941 * we add one of our own free will.
1945 SwitchOutputTo(job->node);
1948 meta_job_output(job, cp,
1952 (void)fprintf(stdout, "%s%s", cp,
1954 (void)fflush(stdout);
1958 * max is the last offset still in the buffer. Move any
1959 * remaining characters to the start of the buffer and
1960 * update the end marker curPos.
1963 (void)memmove(job->outBuf, &job->outBuf[i + 1],
1965 job->curPos = max - (i + 1);
1973 * If the finish flag is true, we must loop until we hit
1974 * end-of-file on the pipe. This is guaranteed to happen
1975 * eventually since the other end of the pipe is now closed
1976 * (we closed it explicitly and the child has exited). When
1977 * we do get an EOF, finish will be set false and we'll fall
1989 * Unfortunately it is too complicated to run .BEGIN, .END, and
1990 * .INTERRUPT job in the parallel job module. As of 2020-09-25,
1991 * unit-tests/deptgt-end-jobs.mk hangs in an endless loop.
1993 * Running these jobs in compat mode also guarantees that these
1994 * jobs do not overlap with other unrelated jobs.
1996 GNodeList lst = LST_INIT;
1997 Lst_Append(&lst, targ);
1998 (void)Make_Run(&lst);
2000 JobStart(targ, true);
2001 while (jobTokensRunning != 0) {
2005 Compat_Make(targ, targ);
2006 /* XXX: Replace with GNode_IsError(gn) */
2007 if (targ->made == ERROR) {
2008 PrintOnError(targ, "\n\nStop.\n");
2015 * Handle the exit of a child. Called from Make_Make.
2017 * The job descriptor is removed from the list of children.
2020 * We do waits, blocking or not, according to the wisdom of our
2021 * caller, until there are no more children to report. For each
2022 * job, call JobFinish to finish things off.
2025 Job_CatchChildren(void)
2027 int pid; /* pid of dead child */
2028 WAIT_T status; /* Exit/termination status */
2030 /* Don't even bother if we know there's no one around. */
2031 if (jobTokensRunning == 0)
2034 /* Have we received SIGCHLD since last call? */
2035 if (caught_sigchld == 0)
2039 while ((pid = waitpid((pid_t)-1, &status, WNOHANG | WUNTRACED)) > 0) {
2040 DEBUG2(JOB, "Process %d exited/stopped status %x.\n",
2041 pid, WAIT_STATUS(status));
2042 JobReapChild(pid, status, true);
2047 * It is possible that wait[pid]() was called from elsewhere,
2048 * this lets us reap jobs regardless.
2051 JobReapChild(pid_t pid, WAIT_T status, bool isJobs)
2053 Job *job; /* job descriptor for dead child */
2055 /* Don't even bother if we know there's no one around. */
2056 if (jobTokensRunning == 0)
2059 job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
2062 if (!lurking_children)
2063 Error("Child (%d) status %x not in table?",
2066 return; /* not ours */
2068 if (WIFSTOPPED(status)) {
2069 DEBUG2(JOB, "Process %d (%s) stopped.\n",
2070 job->pid, job->node->name);
2071 if (!make_suspended) {
2072 switch (WSTOPSIG(status)) {
2074 (void)printf("*** [%s] Suspended\n",
2078 (void)printf("*** [%s] Stopped\n",
2082 (void)printf("*** [%s] Stopped -- signal %d\n",
2083 job->node->name, WSTOPSIG(status));
2085 job->suspended = true;
2087 (void)fflush(stdout);
2091 job->status = JOB_ST_FINISHED;
2092 job->exit_status = WAIT_STATUS(status);
2094 JobFinish(job, status);
2098 * Catch the output from our children, if we're using pipes do so. Otherwise
2099 * just block time until we get a signal(most likely a SIGCHLD) since there's
2100 * no point in just spinning when there's nothing to do and the reaping of a
2101 * child can wait for a while.
2104 Job_CatchOutput(void)
2110 (void)fflush(stdout);
2112 /* The first fd in the list is the job token pipe */
2114 nready = poll(fds + 1 - wantToken, fdsLen - 1 + wantToken,
2116 } while (nready < 0 && errno == EINTR);
2119 Punt("poll: %s", strerror(errno));
2121 if (nready > 0 && readyfd(&childExitJob)) {
2124 count = read(childExitJob.inPipe, &token, 1);
2126 if (token == DO_JOB_RESUME[0])
2128 * Complete relay requested from our SIGCONT
2132 } else if (count == 0)
2133 Punt("unexpected eof on token pipe");
2134 else if (errno != EAGAIN)
2135 Punt("token pipe read: %s", strerror(errno));
2139 Job_CatchChildren();
2143 for (i = npseudojobs * nfds_per_job(); i < fdsLen; i++) {
2144 if (fds[i].revents == 0)
2146 job = jobByFdIndex[i];
2147 if (job->status == JOB_ST_RUNNING)
2148 CollectOutput(job, false);
2149 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2151 * With meta mode, we may have activity on the job's filemon
2152 * descriptor too, which at the moment is any pollfd other
2153 * than job->inPollfd.
2155 if (useMeta && job->inPollfd != &fds[i]) {
2156 if (meta_job_event(job) <= 0)
2157 fds[i].events = 0; /* never mind */
2166 * Start the creation of a target. Basically a front-end for JobStart used by
2172 (void)JobStart(gn, false);
2176 InitShellNameAndPath(void)
2178 shellName = shell->name;
2180 #ifdef DEFSHELL_CUSTOM
2181 if (shellName[0] == '/') {
2182 shellPath = shellName;
2183 shellName = str_basename(shellPath);
2187 #ifdef DEFSHELL_PATH
2188 shellPath = DEFSHELL_PATH;
2190 shellPath = str_concat3(_PATH_DEFSHELLDIR, "/", shellName);
2197 if (shellPath == NULL)
2198 InitShellNameAndPath();
2200 Var_SetWithFlags(SCOPE_CMDLINE, ".SHELL", shellPath, VAR_SET_READONLY);
2201 if (shell->errFlag == NULL)
2202 shell->errFlag = "";
2203 if (shell->echoFlag == NULL)
2204 shell->echoFlag = "";
2205 if (shell->hasErrCtl && shell->errFlag[0] != '\0') {
2206 if (shellErrFlag != NULL &&
2207 strcmp(shell->errFlag, &shellErrFlag[1]) != 0) {
2209 shellErrFlag = NULL;
2211 if (shellErrFlag == NULL)
2212 shellErrFlag = str_concat2("-", shell->errFlag);
2213 } else if (shellErrFlag != NULL) {
2215 shellErrFlag = NULL;
2220 * Return the string literal that is used in the current command shell
2221 * to produce a newline character.
2224 Shell_GetNewline(void)
2226 return shell->newline;
2232 if (targPrefix != NULL) {
2234 } else if (!Var_Exists(SCOPE_GLOBAL, ".MAKE.JOB.PREFIX")) {
2235 Global_Set(".MAKE.JOB.PREFIX", "---");
2238 targPrefix = Var_Subst("${.MAKE.JOB.PREFIX}",
2239 SCOPE_GLOBAL, VARE_WANTRES);
2240 /* TODO: handle errors */
2244 AddSig(int sig, SignalProc handler)
2246 if (bmake_signal(sig, SIG_IGN) != SIG_IGN) {
2247 sigaddset(&caught_signals, sig);
2248 (void)bmake_signal(sig, handler);
2252 /* Initialize the process module. */
2257 /* Allocate space for all the job info */
2258 job_table = bmake_malloc((size_t)opts.maxJobs * sizeof *job_table);
2259 memset(job_table, 0, (size_t)opts.maxJobs * sizeof *job_table);
2260 job_table_end = job_table + opts.maxJobs;
2264 aborting = ABORT_NONE;
2267 Always_pass_job_queue = GetBooleanExpr(MAKE_ALWAYS_PASS_JOB_QUEUE,
2268 Always_pass_job_queue);
2270 Job_error_token = GetBooleanExpr(MAKE_JOB_ERROR_TOKEN, Job_error_token);
2274 * There is a non-zero chance that we already have children.
2275 * eg after 'make -f- <<EOF'
2276 * Since their termination causes a 'Child (pid) not in table'
2277 * message, Collect the status of any that are already dead, and
2278 * suppress the error message if there are any undead ones.
2284 rval = waitpid((pid_t)-1, &status, WNOHANG);
2288 lurking_children = true;
2294 JobCreatePipe(&childExitJob, 3);
2297 /* Preallocate enough for the maximum number of jobs. */
2298 size_t nfds = (npseudojobs + (size_t)opts.maxJobs) *
2300 fds = bmake_malloc(sizeof *fds * nfds);
2301 jobByFdIndex = bmake_malloc(sizeof *jobByFdIndex * nfds);
2304 /* These are permanent entries and take slots 0 and 1 */
2305 watchfd(&tokenWaitJob);
2306 watchfd(&childExitJob);
2308 sigemptyset(&caught_signals);
2310 * Install a SIGCHLD handler.
2312 (void)bmake_signal(SIGCHLD, JobChildSig);
2313 sigaddset(&caught_signals, SIGCHLD);
2316 * Catch the four signals that POSIX specifies if they aren't ignored.
2317 * JobPassSig will take care of calling JobInterrupt if appropriate.
2319 AddSig(SIGINT, JobPassSig_int);
2320 AddSig(SIGHUP, JobPassSig_term);
2321 AddSig(SIGTERM, JobPassSig_term);
2322 AddSig(SIGQUIT, JobPassSig_term);
2325 * There are additional signals that need to be caught and passed if
2326 * either the export system wants to be told directly of signals or if
2327 * we're giving each job its own process group (since then it won't get
2328 * signals from the terminal driver as we own the terminal)
2330 AddSig(SIGTSTP, JobPassSig_suspend);
2331 AddSig(SIGTTOU, JobPassSig_suspend);
2332 AddSig(SIGTTIN, JobPassSig_suspend);
2333 AddSig(SIGWINCH, JobCondPassSig);
2334 AddSig(SIGCONT, JobContinueSig);
2336 (void)Job_RunTarget(".BEGIN", NULL);
2338 * Create the .END node now, even though no code in the unit tests
2339 * depends on it. See also Targ_GetEndNode in Compat_MakeAll.
2341 (void)Targ_GetEndNode();
2347 if (sigismember(&caught_signals, sig) != 0)
2348 (void)bmake_signal(sig, SIG_DFL);
2363 (void)bmake_signal(SIGCHLD, SIG_DFL);
2366 /* Find a shell in 'shells' given its name, or return NULL. */
2368 FindShellByName(const char *name)
2371 const Shell *shellsEnd = sh + sizeof shells / sizeof shells[0];
2373 for (sh = shells; sh < shellsEnd; sh++) {
2374 if (strcmp(name, sh->name) == 0)
2381 * Parse a shell specification and set up 'shell', shellPath and
2382 * shellName appropriately.
2385 * line The shell spec
2388 * false if the specification was incorrect.
2391 * 'shell' points to a Shell structure (either predefined or
2392 * created from the shell spec), shellPath is the full path of the
2393 * shell described by 'shell', while shellName is just the
2394 * final component of shellPath.
2397 * A shell specification consists of a .SHELL target, with dependency
2398 * operator, followed by a series of blank-separated words. Double
2399 * quotes can be used to use blanks in words. A backslash escapes
2400 * anything (most notably a double-quote and a space) and
2401 * provides the functionality it does in C. Each word consists of
2402 * keyword and value separated by an equal sign. There should be no
2403 * unnecessary spaces in the word. The keywords are as follows:
2404 * name Name of shell.
2405 * path Location of shell.
2406 * quiet Command to turn off echoing.
2407 * echo Command to turn echoing on
2408 * filter Result of turning off echoing that shouldn't be
2410 * echoFlag Flag to turn echoing on at the start
2411 * errFlag Flag to turn error checking on at the start
2412 * hasErrCtl True if shell has error checking control
2413 * newline String literal to represent a newline char
2414 * check Command to turn on error checking if hasErrCtl
2415 * is true or template of command to echo a command
2416 * for which error checking is off if hasErrCtl is
2418 * ignore Command to turn off error checking if hasErrCtl
2419 * is true or template of command to execute a
2420 * command so as to ignore any errors it returns if
2421 * hasErrCtl is false.
2424 Job_ParseShell(char *line)
2432 bool fullSpec = false;
2435 /* XXX: don't use line as an iterator variable */
2436 pp_skip_whitespace(&line);
2440 memset(&newShell, 0, sizeof newShell);
2443 * Parse the specification by keyword
2445 wordsList = Str_Words(line, true);
2446 words = wordsList.words;
2447 argc = wordsList.len;
2448 path = wordsList.freeIt;
2449 if (words == NULL) {
2450 Error("Unterminated quoted string [%s]", line);
2453 shell_freeIt = path;
2455 for (path = NULL, argv = words; argc != 0; argc--, argv++) {
2457 if (strncmp(arg, "path=", 5) == 0) {
2459 } else if (strncmp(arg, "name=", 5) == 0) {
2460 newShell.name = arg + 5;
2462 if (strncmp(arg, "quiet=", 6) == 0) {
2463 newShell.echoOff = arg + 6;
2464 } else if (strncmp(arg, "echo=", 5) == 0) {
2465 newShell.echoOn = arg + 5;
2466 } else if (strncmp(arg, "filter=", 7) == 0) {
2467 newShell.noPrint = arg + 7;
2468 newShell.noPrintLen = strlen(newShell.noPrint);
2469 } else if (strncmp(arg, "echoFlag=", 9) == 0) {
2470 newShell.echoFlag = arg + 9;
2471 } else if (strncmp(arg, "errFlag=", 8) == 0) {
2472 newShell.errFlag = arg + 8;
2473 } else if (strncmp(arg, "hasErrCtl=", 10) == 0) {
2475 newShell.hasErrCtl = c == 'Y' || c == 'y' ||
2476 c == 'T' || c == 't';
2477 } else if (strncmp(arg, "newline=", 8) == 0) {
2478 newShell.newline = arg + 8;
2479 } else if (strncmp(arg, "check=", 6) == 0) {
2481 * Before 2020-12-10, these two variables had
2482 * been a single variable.
2484 newShell.errOn = arg + 6;
2485 newShell.echoTmpl = arg + 6;
2486 } else if (strncmp(arg, "ignore=", 7) == 0) {
2488 * Before 2020-12-10, these two variables had
2489 * been a single variable.
2491 newShell.errOff = arg + 7;
2492 newShell.runIgnTmpl = arg + 7;
2493 } else if (strncmp(arg, "errout=", 7) == 0) {
2494 newShell.runChkTmpl = arg + 7;
2495 } else if (strncmp(arg, "comment=", 8) == 0) {
2496 newShell.commentChar = arg[8];
2498 Parse_Error(PARSE_FATAL,
2499 "Unknown keyword \"%s\"", arg);
2509 * If no path was given, the user wants one of the
2510 * pre-defined shells, yes? So we find the one s/he wants
2511 * with the help of FindShellByName and set things up the
2512 * right way. shellPath will be set up by Shell_Init.
2514 if (newShell.name == NULL) {
2515 Parse_Error(PARSE_FATAL,
2516 "Neither path nor name specified");
2520 if ((sh = FindShellByName(newShell.name)) == NULL) {
2521 Parse_Error(PARSE_WARNING,
2522 "%s: No matching shell", newShell.name);
2527 shellName = newShell.name;
2528 if (shellPath != NULL) {
2530 * Shell_Init has already been called!
2533 free(UNCONST(shellPath));
2540 * The user provided a path. If s/he gave nothing else
2541 * (fullSpec is false), try and find a matching shell in the
2542 * ones we know of. Else we just take the specification at
2543 * its word and copy it to a new location. In either case,
2544 * we need to record the path the user gave for the shell.
2547 path = strrchr(path, '/');
2549 path = UNCONST(shellPath);
2553 if (newShell.name != NULL) {
2554 shellName = newShell.name;
2559 if ((sh = FindShellByName(shellName)) == NULL) {
2560 Parse_Error(PARSE_WARNING,
2561 "%s: No matching shell", shellName);
2567 shell = bmake_malloc(sizeof *shell);
2570 /* this will take care of shellErrFlag */
2574 if (shell->echoOn != NULL && shell->echoOff != NULL)
2575 shell->hasEchoCtl = true;
2577 if (!shell->hasErrCtl) {
2578 if (shell->echoTmpl == NULL)
2579 shell->echoTmpl = "";
2580 if (shell->runIgnTmpl == NULL)
2581 shell->runIgnTmpl = "%s\n";
2585 * Do not free up the words themselves, since they might be in use
2586 * by the shell specification.
2593 * Handle the receipt of an interrupt.
2595 * All children are killed. Another job will be started if the .INTERRUPT
2596 * target is defined.
2599 * runINTERRUPT Non-zero if commands for the .INTERRUPT target
2600 * should be executed
2601 * signo signal received
2604 JobInterrupt(bool runINTERRUPT, int signo)
2606 Job *job; /* job descriptor in that element */
2607 GNode *interrupt; /* the node describing the .INTERRUPT target */
2611 aborting = ABORT_INTERRUPT;
2615 for (job = job_table; job < job_table_end; job++) {
2616 if (job->status != JOB_ST_RUNNING)
2621 JobDeleteTarget(gn);
2622 if (job->pid != 0) {
2624 "JobInterrupt passing signal %d to child %d.\n",
2626 KILLPG(job->pid, signo);
2630 JobSigUnlock(&mask);
2632 if (runINTERRUPT && !opts.touch) {
2633 interrupt = Targ_FindNode(".INTERRUPT");
2634 if (interrupt != NULL) {
2635 opts.ignoreErrors = false;
2639 Trace_Log(MAKEINTR, NULL);
2640 exit(signo); /* XXX: why signo? */
2644 * Do the final processing, i.e. run the commands attached to the .END target.
2646 * Return the number of errors reported.
2651 GNode *endNode = Targ_GetEndNode();
2652 if (!Lst_IsEmpty(&endNode->commands) ||
2653 !Lst_IsEmpty(&endNode->children)) {
2654 if (job_errors != 0) {
2655 Error("Errors reported so .END ignored");
2663 /* Clean up any memory used by the jobs module. */
2673 * Waits for all running jobs to finish and returns.
2674 * Sets 'aborting' to ABORT_WAIT to prevent other jobs from starting.
2679 aborting = ABORT_WAIT;
2680 while (jobTokensRunning != 0) {
2683 aborting = ABORT_NONE;
2687 * Abort all currently running jobs without handling output or anything.
2688 * This function is to be called only in the event of a major error.
2689 * Most definitely NOT to be called from JobInterrupt.
2691 * All children are killed, not just the firstborn.
2696 Job *job; /* the job descriptor in that element */
2699 aborting = ABORT_ERROR;
2701 if (jobTokensRunning != 0) {
2702 for (job = job_table; job < job_table_end; job++) {
2703 if (job->status != JOB_ST_RUNNING)
2706 * kill the child process with increasingly drastic
2707 * signals to make darn sure it's dead.
2709 KILLPG(job->pid, SIGINT);
2710 KILLPG(job->pid, SIGKILL);
2715 * Catch as many children as want to report in at first, then give up
2717 while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2722 * Tries to restart stopped jobs if there are slots available.
2723 * Called in process context in response to a SIGCONT.
2726 JobRestartJobs(void)
2730 for (job = job_table; job < job_table_end; job++) {
2731 if (job->status == JOB_ST_RUNNING &&
2732 (make_suspended || job->suspended)) {
2733 DEBUG1(JOB, "Restarting stopped job pid %d.\n",
2735 if (job->suspended) {
2736 (void)printf("*** [%s] Continued\n",
2738 (void)fflush(stdout);
2740 job->suspended = false;
2741 if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
2742 debug_printf("Failed to send SIGCONT to %d\n",
2746 if (job->status == JOB_ST_FINISHED) {
2748 * Job exit deferred after calling waitpid() in a
2751 JobFinish(job, job->exit_status);
2754 make_suspended = false;
2760 if (job->inPollfd != NULL)
2761 Punt("Watching watched job");
2763 fds[fdsLen].fd = job->inPipe;
2764 fds[fdsLen].events = POLLIN;
2765 jobByFdIndex[fdsLen] = job;
2766 job->inPollfd = &fds[fdsLen];
2768 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2770 fds[fdsLen].fd = meta_job_fd(job);
2771 fds[fdsLen].events = fds[fdsLen].fd == -1 ? 0 : POLLIN;
2772 jobByFdIndex[fdsLen] = job;
2782 if (job->inPollfd == NULL)
2783 Punt("Unwatching unwatched job");
2784 i = (size_t)(job->inPollfd - fds);
2786 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2789 * Sanity check: there should be two fds per job, so the job's
2790 * pollfd number should be even.
2792 assert(nfds_per_job() == 2);
2794 Punt("odd-numbered fd with meta");
2799 * Move last job in table into hole made by dead job.
2802 fds[i] = fds[fdsLen];
2803 jobByFdIndex[i] = jobByFdIndex[fdsLen];
2804 jobByFdIndex[i]->inPollfd = &fds[i];
2805 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2807 fds[i + 1] = fds[fdsLen + 1];
2808 jobByFdIndex[i + 1] = jobByFdIndex[fdsLen + 1];
2812 job->inPollfd = NULL;
2818 if (job->inPollfd == NULL)
2819 Punt("Polling unwatched job");
2820 return (job->inPollfd->revents & POLLIN) != 0;
2824 * Put a token (back) into the job pipe.
2825 * This allows a make process to start a build job.
2830 char tok = JOB_TOKENS[aborting], tok1;
2832 if (!Job_error_token && aborting == ABORT_ERROR) {
2833 if (jobTokensRunning == 0)
2835 tok = '+'; /* no error token */
2838 /* If we are depositing an error token flush everything else */
2839 while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2842 DEBUG3(JOB, "(%d) aborting %d, deposit token %c\n",
2843 getpid(), aborting, tok);
2844 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2848 /* Get a temp file */
2850 Job_TempFile(const char *pattern, char *tfile, size_t tfile_sz)
2856 fd = mkTempFile(pattern, tfile, tfile_sz);
2857 if (tfile != NULL && !DEBUG(SCRIPT))
2859 JobSigUnlock(&mask);
2864 /* Prep the job token pipe in the root make process. */
2866 Job_ServerStart(int max_tokens, int jp_0, int jp_1)
2871 if (jp_0 >= 0 && jp_1 >= 0) {
2872 /* Pipe passed in from parent */
2873 tokenWaitJob.inPipe = jp_0;
2874 tokenWaitJob.outPipe = jp_1;
2875 (void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
2876 (void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
2880 JobCreatePipe(&tokenWaitJob, 15);
2882 snprintf(jobarg, sizeof jobarg, "%d,%d",
2883 tokenWaitJob.inPipe, tokenWaitJob.outPipe);
2885 Global_Append(MAKEFLAGS, "-J");
2886 Global_Append(MAKEFLAGS, jobarg);
2889 * Preload the job pipe with one token per job, save the one
2890 * "extra" token for the primary job.
2892 * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
2893 * larger than the write buffer size of the pipe, we will
2896 for (i = 1; i < max_tokens; i++)
2900 /* Return a withdrawn token to the pool. */
2902 Job_TokenReturn(void)
2905 if (jobTokensRunning < 0)
2906 Punt("token botch");
2907 if (jobTokensRunning != 0 || JOB_TOKENS[aborting] != '+')
2912 * Attempt to withdraw a token from the pool.
2914 * If pool is empty, set wantToken so that we wake up when a token is
2917 * Returns true if a token was withdrawn, and false if the pool is currently
2921 Job_TokenWithdraw(void)
2927 DEBUG3(JOB, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
2928 getpid(), aborting, jobTokensRunning);
2930 if (aborting != ABORT_NONE || (jobTokensRunning >= opts.maxJobs))
2933 count = read(tokenWaitJob.inPipe, &tok, 1);
2935 Fatal("eof on job pipe!");
2936 if (count < 0 && jobTokensRunning != 0) {
2937 if (errno != EAGAIN) {
2938 Fatal("job pipe read: %s", strerror(errno));
2940 DEBUG1(JOB, "(%d) blocked for token\n", getpid());
2945 if (count == 1 && tok != '+') {
2946 /* make being aborted - remove any other job tokens */
2947 DEBUG2(JOB, "(%d) aborted by token %c\n", getpid(), tok);
2948 while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2950 /* And put the stopper back */
2951 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
2954 if (shouldDieQuietly(NULL, 1))
2955 exit(6); /* we aborted */
2956 Fatal("A failure has been detected "
2957 "in another branch of the parallel make");
2960 if (count == 1 && jobTokensRunning == 0)
2961 /* We didn't want the token really */
2962 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
2967 DEBUG1(JOB, "(%d) withdrew token\n", getpid());
2972 * Run the named target if found. If a filename is specified, then set that
2975 * Exits if the target fails.
2978 Job_RunTarget(const char *target, const char *fname)
2980 GNode *gn = Targ_FindNode(target);
2985 Var_Set(gn, ALLSRC, fname);
2988 /* XXX: Replace with GNode_IsError(gn) */
2989 if (gn->made == ERROR) {
2990 PrintOnError(gn, "\n\nStop.\n");
2998 emul_poll(struct pollfd *fd, int nfd, int timeout)
3001 int i, maxfd, nselect, npoll;
3002 struct timeval tv, *tvp;
3009 for (i = 0; i < nfd; i++) {
3012 if (fd[i].events & POLLIN)
3013 FD_SET(fd[i].fd, &rfds);
3015 if (fd[i].events & POLLOUT)
3016 FD_SET(fd[i].fd, &wfds);
3018 if (fd[i].fd > maxfd)
3022 if (maxfd >= FD_SETSIZE) {
3023 Punt("Ran out of fd_set slots; "
3024 "recompile with a larger FD_SETSIZE.");
3030 usecs = timeout * 1000;
3031 tv.tv_sec = usecs / 1000000;
3032 tv.tv_usec = usecs % 1000000;
3036 nselect = select(maxfd + 1, &rfds, &wfds, NULL, tvp);
3042 for (i = 0; i < nfd; i++) {
3043 if (FD_ISSET(fd[i].fd, &rfds))
3044 fd[i].revents |= POLLIN;
3046 if (FD_ISSET(fd[i].fd, &wfds))
3047 fd[i].revents |= POLLOUT;
3055 #endif /* USE_SELECT */