Home | History | Annotate | Line # | Download | only in make
job.c revision 1.346
      1 /*	$NetBSD: job.c,v 1.346 2020/12/08 00:50:04 rillig Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Adam de Boor.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     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.
     21  *
     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
     32  * SUCH DAMAGE.
     33  */
     34 
     35 /*
     36  * Copyright (c) 1988, 1989 by Adam de Boor
     37  * Copyright (c) 1989 by Berkeley Softworks
     38  * All rights reserved.
     39  *
     40  * This code is derived from software contributed to Berkeley by
     41  * Adam de Boor.
     42  *
     43  * Redistribution and use in source and binary forms, with or without
     44  * modification, are permitted provided that the following conditions
     45  * are met:
     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.
     58  *
     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
     69  * SUCH DAMAGE.
     70  */
     71 
     72 /*-
     73  * job.c --
     74  *	handle the creation etc. of our child processes.
     75  *
     76  * Interface:
     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.
     82  *
     83  *	Job_End		Clean up any memory used.
     84  *
     85  *	Job_Make	Start the creation of the given target.
     86  *
     87  *	Job_CatchChildren
     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.
     93  *
     94  *	Job_CatchOutput
     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.
    101  *
    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.
    105  *
    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.
    111  *
    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
    115  *			an emergency.
    116  *
    117  *	Job_CheckCommands
    118  *			Verify that the commands for a target are
    119  *			ok. Provide them if necessary and possible.
    120  *
    121  *	Job_Touch	Update a target without really updating it.
    122  *
    123  *	Job_Wait	Wait for all currently-running jobs to finish.
    124  */
    125 
    126 #include <sys/types.h>
    127 #include <sys/stat.h>
    128 #include <sys/file.h>
    129 #include <sys/time.h>
    130 #include <sys/wait.h>
    131 
    132 #include <errno.h>
    133 #ifndef USE_SELECT
    134 #include <poll.h>
    135 #endif
    136 #include <signal.h>
    137 #include <utime.h>
    138 
    139 #include "make.h"
    140 #include "dir.h"
    141 #include "job.h"
    142 #include "pathnames.h"
    143 #include "trace.h"
    144 
    145 /*	"@(#)job.c	8.2 (Berkeley) 3/19/94"	*/
    146 MAKE_RCSID("$NetBSD: job.c,v 1.346 2020/12/08 00:50:04 rillig Exp $");
    147 
    148 /*
    149  * A shell defines how the commands are run.  All commands for a target are
    150  * written into a single file, which is then given to the shell to execute
    151  * the commands from it.  The commands are written to the file using a few
    152  * templates for echo control and error control.
    153  *
    154  * The name of the shell is the basename for the predefined shells, such as
    155  * "sh", "csh", "bash".  For custom shells, it is the full pathname, and its
    156  * basename is used to select the type of shell; the longest match wins.
    157  * So /usr/pkg/bin/bash has type sh, /usr/local/bin/tcsh has type csh.
    158  *
    159  * The echoing of command lines is controlled using hasEchoCtl, echoOff,
    160  * echoOn, noPrint and noPrintLen.  When echoOff is executed by the shell, it
    161  * still outputs something, but this something is not interesting, therefore
    162  * it is filtered out using noPrint and noPrintLen.
    163  *
    164  * The error checking for individual commands is controlled using hasErrCtl,
    165  * errOnOrEcho, errOffOrExecIgnore and errExit.
    166  *
    167  * If a shell doesn't have error control, errOnOrEcho becomes a printf template
    168  * for echoing the command, should echoing be on; errOffOrExecIgnore becomes
    169  * another printf template for executing the command while ignoring the return
    170  * status. Finally errExit is a printf template for running the command and
    171  * causing the shell to exit on error. If any of these strings are empty when
    172  * hasErrCtl is FALSE, the command will be executed anyway as is, and if it
    173  * causes an error, so be it. Any templates set up to echo the command will
    174  * escape any '$ ` \ "' characters in the command string to avoid common
    175  * problems with echo "%s\n" as a template.
    176  *
    177  * The command-line flags "echo" and "exit" also control the behavior.  The
    178  * "echo" flag causes the shell to start echoing commands right away.  The
    179  * "exit" flag causes the shell to exit when an error is detected in one of
    180  * the commands.
    181  */
    182 typedef struct Shell {
    183 
    184 	/*
    185 	 * The name of the shell. For Bourne and C shells, this is used only
    186 	 * to find the shell description when used as the single source of a
    187 	 * .SHELL target. For user-defined shells, this is the full path of
    188 	 * the shell.
    189 	 */
    190 	const char *name;
    191 
    192 	Boolean hasEchoCtl;	/* True if both echoOff and echoOn defined */
    193 	const char *echoOff;	/* command to turn off echo */
    194 	const char *echoOn;	/* command to turn it back on again */
    195 	const char *noPrint;	/* text to skip when printing output from
    196 				 * shell. This is usually the same as echoOff */
    197 	size_t noPrintLen;	/* length of noPrint command */
    198 
    199 	Boolean hasErrCtl;	/* set if can control error checking for
    200 				 * individual commands */
    201 	/* XXX: split into errOn and echoCmd */
    202 	const char *errOnOrEcho; /* template to turn on error checking */
    203 	/*
    204 	 * template to turn off error checking
    205 	 * XXX: split into errOff and execIgnore
    206 	 */
    207 	const char *errOffOrExecIgnore;
    208 	const char *errExit;	/* template to use for testing exit code */
    209 
    210 	/* string literal that results in a newline character when it appears
    211 	 * outside of any 'quote' or "quote" characters */
    212 	const char *newline;
    213 	char commentChar;	/* character used by shell for comment lines */
    214 
    215 	/*
    216 	 * command-line flags
    217 	 */
    218 	const char *echo;	/* echo commands */
    219 	const char *exit;	/* exit on error */
    220 } Shell;
    221 
    222 /*
    223  * error handling variables
    224  */
    225 static int job_errors = 0;	/* number of errors reported */
    226 typedef enum AbortReason {	/* why is the make aborting? */
    227 	ABORT_NONE,
    228 	ABORT_ERROR,		/* Because of an error */
    229 	ABORT_INTERRUPT,	/* Because it was interrupted */
    230 	ABORT_WAIT		/* Waiting for jobs to finish */
    231 } AbortReason;
    232 static AbortReason aborting = ABORT_NONE;
    233 #define JOB_TOKENS "+EI+"	/* Token to requeue for each abort state */
    234 
    235 /*
    236  * this tracks the number of tokens currently "out" to build jobs.
    237  */
    238 int jobTokensRunning = 0;
    239 
    240 /* The number of commands actually printed to the shell commands file for
    241  * the current job.  Should this number be 0, no shell will be executed. */
    242 static int numCommands;
    243 
    244 typedef enum JobStartResult {
    245 	JOB_RUNNING,		/* Job is running */
    246 	JOB_ERROR,		/* Error in starting the job */
    247 	JOB_FINISHED		/* The job is already finished */
    248 } JobStartResult;
    249 
    250 /*
    251  * Descriptions for various shells.
    252  *
    253  * The build environment may set DEFSHELL_INDEX to one of
    254  * DEFSHELL_INDEX_SH, DEFSHELL_INDEX_KSH, or DEFSHELL_INDEX_CSH, to
    255  * select one of the predefined shells as the default shell.
    256  *
    257  * Alternatively, the build environment may set DEFSHELL_CUSTOM to the
    258  * name or the full path of a sh-compatible shell, which will be used as
    259  * the default shell.
    260  *
    261  * ".SHELL" lines in Makefiles can choose the default shell from the
    262  * set defined here, or add additional shells.
    263  */
    264 
    265 #ifdef DEFSHELL_CUSTOM
    266 #define DEFSHELL_INDEX_CUSTOM 0
    267 #define DEFSHELL_INDEX_SH     1
    268 #define DEFSHELL_INDEX_KSH    2
    269 #define DEFSHELL_INDEX_CSH    3
    270 #else /* !DEFSHELL_CUSTOM */
    271 #define DEFSHELL_INDEX_SH     0
    272 #define DEFSHELL_INDEX_KSH    1
    273 #define DEFSHELL_INDEX_CSH    2
    274 #endif /* !DEFSHELL_CUSTOM */
    275 
    276 #ifndef DEFSHELL_INDEX
    277 #define DEFSHELL_INDEX 0	/* DEFSHELL_INDEX_CUSTOM or DEFSHELL_INDEX_SH */
    278 #endif /* !DEFSHELL_INDEX */
    279 
    280 static Shell shells[] = {
    281 #ifdef DEFSHELL_CUSTOM
    282     /*
    283      * An sh-compatible shell with a non-standard name.
    284      *
    285      * Keep this in sync with the "sh" description below, but avoid
    286      * non-portable features that might not be supplied by all
    287      * sh-compatible shells.
    288      */
    289     {
    290 	DEFSHELL_CUSTOM,	/* .name */
    291 	FALSE,			/* .hasEchoCtl */
    292 	"",			/* .echoOff */
    293 	"",			/* .echoOn */
    294 	"",			/* .noPrint */
    295 	0,			/* .noPrintLen */
    296 	FALSE,			/* .hasErrCtl */
    297 	"echo \"%s\"\n",	/* .errOnOrEcho */
    298 	"%s\n",			/* .errOffOrExecIgnore */
    299 	"{ %s \n} || exit $?\n", /* .errExit */
    300 	"'\n'",			/* .newline */
    301 	'#',			/* .commentChar */
    302 	"",			/* .echo */
    303 	"",			/* .exit */
    304     },
    305 #endif /* DEFSHELL_CUSTOM */
    306     /*
    307      * SH description. Echo control is also possible and, under
    308      * sun UNIX anyway, one can even control error checking.
    309      */
    310     {
    311 	"sh",			/* .name */
    312 	FALSE,			/* .hasEchoCtl */
    313 	"",			/* .echoOff */
    314 	"",			/* .echoOn */
    315 	"",			/* .noPrint */
    316 	0,			/* .noPrintLen */
    317 	FALSE,			/* .hasErrCtl */
    318 	"echo \"%s\"\n",	/* .errOnOrEcho */
    319 	"%s\n",			/* .errOffOrExecIgnore */
    320 	"{ %s \n} || exit $?\n", /* .errExit */
    321 	"'\n'",			/* .newline */
    322 	'#',			/* .commentChar*/
    323 #if defined(MAKE_NATIVE) && defined(__NetBSD__)
    324 	"q",			/* .echo */
    325 #else
    326 	"",			/* .echo */
    327 #endif
    328 	"",			/* .exit */
    329     },
    330     /*
    331      * KSH description.
    332      */
    333     {
    334 	"ksh",			/* .name */
    335 	TRUE,			/* .hasEchoCtl */
    336 	"set +v",		/* .echoOff */
    337 	"set -v",		/* .echoOn */
    338 	"set +v",		/* .noPrint */
    339 	6,			/* .noPrintLen */
    340 	FALSE,			/* .hasErrCtl */
    341 	"echo \"%s\"\n",	/* .errOnOrEcho */
    342 	"%s\n",			/* .errOffOrExecIgnore */
    343 	"{ %s \n} || exit $?\n", /* .errExit */
    344 	"'\n'",			/* .newline */
    345 	'#',			/* .commentChar */
    346 	"v",			/* .echo */
    347 	"",			/* .exit */
    348     },
    349     /*
    350      * CSH description. The csh can do echo control by playing
    351      * with the setting of the 'echo' shell variable. Sadly,
    352      * however, it is unable to do error control nicely.
    353      */
    354     {
    355 	"csh",			/* .name */
    356 	TRUE,			/* .hasEchoCtl */
    357 	"unset verbose",	/* .echoOff */
    358 	"set verbose",		/* .echoOn */
    359 	"unset verbose",	/* .noPrint */
    360 	13,			/* .noPrintLen */
    361 	FALSE,			/* .hasErrCtl */
    362 	"echo \"%s\"\n",	/* .errOnOrEcho */
    363 	/* XXX: Mismatch between errOn and execIgnore */
    364 	"csh -c \"%s || exit 0\"\n", /* .errOffOrExecIgnore */
    365 	"",			/* .errExit */
    366 	"'\\\n'",		/* .newline */
    367 	'#',			/* .commentChar */
    368 	"v",			/* .echo */
    369 	"e",			/* .exit */
    370     }
    371 };
    372 
    373 /* This is the shell to which we pass all commands in the Makefile.
    374  * It is set by the Job_ParseShell function. */
    375 static Shell *commandShell = &shells[DEFSHELL_INDEX];
    376 const char *shellPath = NULL;	/* full pathname of executable image */
    377 const char *shellName = NULL;	/* last component of shellPath */
    378 char *shellErrFlag = NULL;
    379 static char *shellArgv = NULL;	/* Custom shell args */
    380 
    381 
    382 static Job *job_table;		/* The structures that describe them */
    383 static Job *job_table_end;	/* job_table + maxJobs */
    384 static unsigned int wantToken;	/* we want a token */
    385 static Boolean lurking_children = FALSE;
    386 static Boolean make_suspended = FALSE; /* Whether we've seen a SIGTSTP (etc) */
    387 
    388 /*
    389  * Set of descriptors of pipes connected to
    390  * the output channels of children
    391  */
    392 static struct pollfd *fds = NULL;
    393 static Job **allJobs = NULL;
    394 static nfds_t nJobs = 0;
    395 static void watchfd(Job *);
    396 static void clearfd(Job *);
    397 static int readyfd(Job *);
    398 
    399 static char *targPrefix = NULL; /* To identify a job change in the output. */
    400 static Job tokenWaitJob;	/* token wait pseudo-job */
    401 
    402 static Job childExitJob;	/* child exit pseudo-job */
    403 #define CHILD_EXIT "."
    404 #define DO_JOB_RESUME "R"
    405 
    406 enum {
    407 	npseudojobs = 2		/* number of pseudo-jobs */
    408 };
    409 
    410 static sigset_t caught_signals;	/* Set of signals we handle */
    411 
    412 static void JobDoOutput(Job *, Boolean);
    413 static void JobInterrupt(int, int) MAKE_ATTR_DEAD;
    414 static void JobRestartJobs(void);
    415 static void JobSigReset(void);
    416 
    417 static void
    418 SwitchOutputTo(GNode *gn)
    419 {
    420 	/* The node for which output was most recently produced. */
    421 	static GNode *lastNode = NULL;
    422 
    423 	if (gn == lastNode)
    424 		return;
    425 	lastNode = gn;
    426 
    427 	if (opts.maxJobs != 1 && targPrefix != NULL && targPrefix[0] != '\0')
    428 		(void)fprintf(stdout, "%s %s ---\n", targPrefix, gn->name);
    429 }
    430 
    431 static unsigned
    432 nfds_per_job(void)
    433 {
    434 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
    435 	if (useMeta)
    436 		return 2;
    437 #endif
    438 	return 1;
    439 }
    440 
    441 static void
    442 job_table_dump(const char *where)
    443 {
    444 	Job *job;
    445 
    446 	debug_printf("job table @ %s\n", where);
    447 	for (job = job_table; job < job_table_end; job++) {
    448 		debug_printf("job %d, status %d, flags %d, pid %d\n",
    449 		    (int)(job - job_table), job->status, job->flags, job->pid);
    450 	}
    451 }
    452 
    453 /*
    454  * Delete the target of a failed, interrupted, or otherwise
    455  * unsuccessful job unless inhibited by .PRECIOUS.
    456  */
    457 static void
    458 JobDeleteTarget(GNode *gn)
    459 {
    460 	const char *file;
    461 
    462 	if (gn->type & OP_JOIN)
    463 		return;
    464 	if (gn->type & OP_PHONY)
    465 		return;
    466 	if (Targ_Precious(gn))
    467 		return;
    468 	if (opts.noExecute)
    469 		return;
    470 
    471 	file = GNode_Path(gn);
    472 	if (eunlink(file) != -1)
    473 		Error("*** %s removed", file);
    474 }
    475 
    476 /*
    477  * JobSigLock/JobSigUnlock
    478  *
    479  * Signal lock routines to get exclusive access. Currently used to
    480  * protect `jobs' and `stoppedJobs' list manipulations.
    481  */
    482 static void JobSigLock(sigset_t *omaskp)
    483 {
    484 	if (sigprocmask(SIG_BLOCK, &caught_signals, omaskp) != 0) {
    485 		Punt("JobSigLock: sigprocmask: %s", strerror(errno));
    486 		sigemptyset(omaskp);
    487 	}
    488 }
    489 
    490 static void JobSigUnlock(sigset_t *omaskp)
    491 {
    492 	(void)sigprocmask(SIG_SETMASK, omaskp, NULL);
    493 }
    494 
    495 static void
    496 JobCreatePipe(Job *job, int minfd)
    497 {
    498 	int i, fd, flags;
    499 	int pipe_fds[2];
    500 
    501 	if (pipe(pipe_fds) == -1)
    502 		Punt("Cannot create pipe: %s", strerror(errno));
    503 
    504 	for (i = 0; i < 2; i++) {
    505 		/* Avoid using low numbered fds */
    506 		fd = fcntl(pipe_fds[i], F_DUPFD, minfd);
    507 		if (fd != -1) {
    508 			close(pipe_fds[i]);
    509 			pipe_fds[i] = fd;
    510 		}
    511 	}
    512 
    513 	job->inPipe = pipe_fds[0];
    514 	job->outPipe = pipe_fds[1];
    515 
    516 	/* Set close-on-exec flag for both */
    517 	if (fcntl(job->inPipe, F_SETFD, FD_CLOEXEC) == -1)
    518 		Punt("Cannot set close-on-exec: %s", strerror(errno));
    519 	if (fcntl(job->outPipe, F_SETFD, FD_CLOEXEC) == -1)
    520 		Punt("Cannot set close-on-exec: %s", strerror(errno));
    521 
    522 	/*
    523 	 * We mark the input side of the pipe non-blocking; we poll(2) the
    524 	 * pipe when we're waiting for a job token, but we might lose the
    525 	 * race for the token when a new one becomes available, so the read
    526 	 * from the pipe should not block.
    527 	 */
    528 	flags = fcntl(job->inPipe, F_GETFL, 0);
    529 	if (flags == -1)
    530 		Punt("Cannot get flags: %s", strerror(errno));
    531 	flags |= O_NONBLOCK;
    532 	if (fcntl(job->inPipe, F_SETFL, flags) == -1)
    533 		Punt("Cannot set flags: %s", strerror(errno));
    534 }
    535 
    536 /* Pass the signal to each running job. */
    537 static void
    538 JobCondPassSig(int signo)
    539 {
    540 	Job *job;
    541 
    542 	DEBUG1(JOB, "JobCondPassSig(%d) called.\n", signo);
    543 
    544 	for (job = job_table; job < job_table_end; job++) {
    545 		if (job->status != JOB_ST_RUNNING)
    546 			continue;
    547 		DEBUG2(JOB, "JobCondPassSig passing signal %d to child %d.\n",
    548 		    signo, job->pid);
    549 		KILLPG(job->pid, signo);
    550 	}
    551 }
    552 
    553 /*
    554  * SIGCHLD handler.
    555  *
    556  * Sends a token on the child exit pipe to wake us up from select()/poll().
    557  */
    558 static void
    559 JobChildSig(int signo MAKE_ATTR_UNUSED)
    560 {
    561 	while (write(childExitJob.outPipe, CHILD_EXIT, 1) == -1 &&
    562 	       errno == EAGAIN)
    563 		continue;
    564 }
    565 
    566 
    567 /* Resume all stopped jobs. */
    568 static void
    569 JobContinueSig(int signo MAKE_ATTR_UNUSED)
    570 {
    571 	/*
    572 	 * Defer sending SIGCONT to our stopped children until we return
    573 	 * from the signal handler.
    574 	 */
    575 	while (write(childExitJob.outPipe, DO_JOB_RESUME, 1) == -1 &&
    576 	       errno == EAGAIN)
    577 		continue;
    578 }
    579 
    580 /*
    581  * Pass a signal on to all jobs, then resend to ourselves.
    582  * We die by the same signal.
    583  */
    584 MAKE_ATTR_DEAD static void
    585 JobPassSig_int(int signo)
    586 {
    587 	/* Run .INTERRUPT target then exit */
    588 	JobInterrupt(TRUE, signo);
    589 }
    590 
    591 /*
    592  * Pass a signal on to all jobs, then resend to ourselves.
    593  * We die by the same signal.
    594  */
    595 MAKE_ATTR_DEAD static void
    596 JobPassSig_term(int signo)
    597 {
    598 	/* Dont run .INTERRUPT target then exit */
    599 	JobInterrupt(FALSE, signo);
    600 }
    601 
    602 static void
    603 JobPassSig_suspend(int signo)
    604 {
    605 	sigset_t nmask, omask;
    606 	struct sigaction act;
    607 
    608 	/* Suppress job started/continued messages */
    609 	make_suspended = TRUE;
    610 
    611 	/* Pass the signal onto every job */
    612 	JobCondPassSig(signo);
    613 
    614 	/*
    615 	 * Send ourselves the signal now we've given the message to everyone
    616 	 * else. Note we block everything else possible while we're getting
    617 	 * the signal. This ensures that all our jobs get continued when we
    618 	 * wake up before we take any other signal.
    619 	 */
    620 	sigfillset(&nmask);
    621 	sigdelset(&nmask, signo);
    622 	(void)sigprocmask(SIG_SETMASK, &nmask, &omask);
    623 
    624 	act.sa_handler = SIG_DFL;
    625 	sigemptyset(&act.sa_mask);
    626 	act.sa_flags = 0;
    627 	(void)sigaction(signo, &act, NULL);
    628 
    629 	DEBUG1(JOB, "JobPassSig passing signal %d to self.\n", signo);
    630 
    631 	(void)kill(getpid(), signo);
    632 
    633 	/*
    634 	 * We've been continued.
    635 	 *
    636 	 * A whole host of signals continue to happen!
    637 	 * SIGCHLD for any processes that actually suspended themselves.
    638 	 * SIGCHLD for any processes that exited while we were alseep.
    639 	 * The SIGCONT that actually caused us to wakeup.
    640 	 *
    641 	 * Since we defer passing the SIGCONT on to our children until
    642 	 * the main processing loop, we can be sure that all the SIGCHLD
    643 	 * events will have happened by then - and that the waitpid() will
    644 	 * collect the child 'suspended' events.
    645 	 * For correct sequencing we just need to ensure we process the
    646 	 * waitpid() before passing on the SIGCONT.
    647 	 *
    648 	 * In any case nothing else is needed here.
    649 	 */
    650 
    651 	/* Restore handler and signal mask */
    652 	act.sa_handler = JobPassSig_suspend;
    653 	(void)sigaction(signo, &act, NULL);
    654 	(void)sigprocmask(SIG_SETMASK, &omask, NULL);
    655 }
    656 
    657 static Job *
    658 JobFindPid(int pid, JobStatus status, Boolean isJobs)
    659 {
    660 	Job *job;
    661 
    662 	for (job = job_table; job < job_table_end; job++) {
    663 		if (job->status == status && job->pid == pid)
    664 			return job;
    665 	}
    666 	if (DEBUG(JOB) && isJobs)
    667 		job_table_dump("no pid");
    668 	return NULL;
    669 }
    670 
    671 /* Parse leading '@', '-' and '+', which control the exact execution mode. */
    672 static void
    673 ParseRunOptions(char **pp,
    674 		Boolean *out_shutUp, Boolean *out_errOff,
    675 		Boolean *out_runAlways)
    676 {
    677 	char *p = *pp;
    678 	*out_shutUp = FALSE;
    679 	*out_errOff = FALSE;
    680 	*out_runAlways = FALSE;
    681 
    682 	for (;;) {
    683 		if (*p == '@')
    684 			*out_shutUp = !DEBUG(LOUD);
    685 		else if (*p == '-')
    686 			*out_errOff = TRUE;
    687 		else if (*p == '+')
    688 			*out_runAlways = TRUE;
    689 		else
    690 			break;
    691 		p++;
    692 	}
    693 
    694 	pp_skip_whitespace(&p);
    695 
    696 	*pp = p;
    697 }
    698 
    699 /* Escape a string for a double-quoted string literal in sh, csh and ksh. */
    700 static char *
    701 EscapeShellDblQuot(const char *cmd)
    702 {
    703 	size_t i, j;
    704 
    705 	/* Worst that could happen is every char needs escaping. */
    706 	char *esc = bmake_malloc(strlen(cmd) * 2 + 1);
    707 	for (i = 0, j = 0; cmd[i] != '\0'; i++, j++) {
    708 		if (cmd[i] == '$' || cmd[i] == '`' || cmd[i] == '\\' ||
    709 		    cmd[i] == '"')
    710 			esc[j++] = '\\';
    711 		esc[j] = cmd[i];
    712 	}
    713 	esc[j] = '\0';
    714 
    715 	return esc;
    716 }
    717 
    718 static void
    719 JobPrintf(Job *job, const char *fmt, const char *arg)
    720 {
    721 	DEBUG1(JOB, fmt, arg);
    722 
    723 	(void)fprintf(job->cmdFILE, fmt, arg);
    724 	(void)fflush(job->cmdFILE);
    725 }
    726 
    727 static void
    728 JobPrintln(Job *job, const char *line)
    729 {
    730 	JobPrintf(job, "%s\n", line);
    731 }
    732 
    733 /*
    734  * We don't want the error-control commands showing up either, so we turn
    735  * off echoing while executing them. We could put another field in the shell
    736  * structure to tell JobDoOutput to look for this string too, but why make
    737  * it any more complex than it already is?
    738  */
    739 static void
    740 JobPrintSpecialsErrCtl(Job *job, Boolean shutUp)
    741 {
    742 	if (!(job->flags & JOB_SILENT) && !shutUp && commandShell->hasEchoCtl) {
    743 		JobPrintln(job, commandShell->echoOff);
    744 		JobPrintln(job, commandShell->errOffOrExecIgnore);
    745 		JobPrintln(job, commandShell->echoOn);
    746 	} else {
    747 		JobPrintln(job, commandShell->errOffOrExecIgnore);
    748 	}
    749 }
    750 
    751 /*
    752  * The shell has no error control, so we need to be weird to get it to
    753  * ignore any errors from the command. If echoing is turned on, we turn it
    754  * off and use the errOnOrEcho template to echo the command. Leave echoing
    755  * off so the user doesn't see the weirdness we go through to ignore errors.
    756  * Set cmdTemplate to use the weirdness instead of the simple "%s\n" template.
    757  */
    758 static void
    759 JobPrintSpecialsEchoCtl(Job *job, Boolean *inout_shutUp, const char *escCmd,
    760 			const char **inout_cmdTemplate, Boolean *out_errOff)
    761 {
    762 	job->flags |= JOB_IGNERR;
    763 
    764 	if (!(job->flags & JOB_SILENT) && !*inout_shutUp) {
    765 		if (commandShell->hasEchoCtl)
    766 			JobPrintln(job, commandShell->echoOff);
    767 		JobPrintf(job, commandShell->errOnOrEcho, escCmd);
    768 		*inout_shutUp = TRUE;
    769 	} else {
    770 		if (!*inout_shutUp)
    771 			JobPrintf(job, commandShell->errOnOrEcho, escCmd);
    772 	}
    773 	*inout_cmdTemplate = commandShell->errOffOrExecIgnore;
    774 
    775 	/*
    776 	 * The error ignoration (hee hee) is already taken care of by the
    777 	 * errOffOrExecIgnore template, so pretend error checking is still on.
    778 	 */
    779 	*out_errOff = FALSE;
    780 }
    781 
    782 static void
    783 JobPrintSpecials(Job *const job, const char *const escCmd,
    784 		 Boolean const noSpecials, Boolean *const inout_shutUp,
    785 		 const char **const inout_cmdTemplate,
    786 		 Boolean *const inout_errOff)
    787 {
    788 	if (noSpecials)
    789 		*inout_errOff = FALSE;
    790 	else if (commandShell->hasErrCtl)
    791 		JobPrintSpecialsErrCtl(job, *inout_shutUp);
    792 	else if (commandShell->errOffOrExecIgnore != NULL &&
    793 		 commandShell->errOffOrExecIgnore[0] != '\0') {
    794 		JobPrintSpecialsEchoCtl(job, inout_shutUp, escCmd,
    795 		    inout_cmdTemplate, inout_errOff);
    796 	} else
    797 		*inout_errOff = FALSE;
    798 }
    799 
    800 /*
    801  * Put out another command for the given job. If the command starts with an
    802  * '@' or a '-' we process it specially. In the former case, so long as the
    803  * -s and -n flags weren't given to make, we stick a shell-specific echoOff
    804  * command in the script. In the latter, we ignore errors for the entire job,
    805  * unless the shell has error control.
    806  *
    807  * If the command is just "..." we take all future commands for this job to
    808  * be commands to be executed once the entire graph has been made and return
    809  * non-zero to signal that the end of the commands was reached. These commands
    810  * are later attached to the .END node and executed by Job_End when all things
    811  * are done.
    812  *
    813  * Side Effects:
    814  *	If the command begins with a '-' and the shell has no error control,
    815  *	the JOB_IGNERR flag is set in the job descriptor.
    816  *	numCommands is incremented if the command is actually printed.
    817  */
    818 static void
    819 JobPrintCommand(Job *job, char *cmd)
    820 {
    821 	const char *const cmdp = cmd;
    822 	/*
    823 	 * true if we shouldn't worry about inserting special commands into
    824 	 * the input stream.
    825 	 */
    826 	Boolean noSpecials;
    827 	/* true if we put a no echo command into the command file */
    828 	Boolean shutUp;
    829 	/*
    830 	 * true if we turned error checking off before printing the command
    831 	 * and need to turn it back on
    832 	 */
    833 	Boolean errOff;
    834 	Boolean runAlways;
    835 	/* Template to use when printing the command */
    836 	const char *cmdTemplate;
    837 	char *cmdStart;		/* Start of expanded command */
    838 	char *escCmd = NULL;	/* Command with quotes/backticks escaped */
    839 
    840 	noSpecials = !GNode_ShouldExecute(job->node);
    841 
    842 	numCommands++;
    843 
    844 	Var_Subst(cmd, job->node, VARE_WANTRES, &cmd);
    845 	/* TODO: handle errors */
    846 	cmdStart = cmd;
    847 
    848 	cmdTemplate = "%s\n";
    849 
    850 	ParseRunOptions(&cmd, &shutUp, &errOff, &runAlways);
    851 
    852 	if (runAlways && noSpecials) {
    853 		/*
    854 		 * We're not actually executing anything...
    855 		 * but this one needs to be - use compat mode just for it.
    856 		 */
    857 		Compat_RunCommand(cmdp, job->node);
    858 		free(cmdStart);
    859 		return;
    860 	}
    861 
    862 	/*
    863 	 * If the shell doesn't have error control the alternate echo'ing will
    864 	 * be done (to avoid showing additional error checking code)
    865 	 * and this will need the characters '$ ` \ "' escaped
    866 	 */
    867 
    868 	if (!commandShell->hasErrCtl)
    869 		escCmd = EscapeShellDblQuot(cmd);
    870 
    871 	if (shutUp) {
    872 		if (!(job->flags & JOB_SILENT) && !noSpecials &&
    873 		    commandShell->hasEchoCtl) {
    874 			JobPrintln(job, commandShell->echoOff);
    875 		} else {
    876 			if (commandShell->hasErrCtl)
    877 				shutUp = FALSE;
    878 		}
    879 	}
    880 
    881 	if (errOff) {
    882 		JobPrintSpecials(job, escCmd, noSpecials, &shutUp, &cmdTemplate,
    883 		    &errOff);
    884 	} else {
    885 
    886 		/*
    887 		 * If errors are being checked and the shell doesn't have
    888 		 * error control but does supply an errExit template, then
    889 		 * set up commands to run through it.
    890 		 */
    891 
    892 		if (!commandShell->hasErrCtl && commandShell->errExit &&
    893 		    commandShell->errExit[0] != '\0') {
    894 			if (!(job->flags & JOB_SILENT) && !shutUp) {
    895 				if (commandShell->hasEchoCtl)
    896 					JobPrintln(job, commandShell->echoOff);
    897 				JobPrintf(job, commandShell->errOnOrEcho,
    898 				    escCmd);
    899 				shutUp = TRUE;
    900 			}
    901 			/*
    902 			 * If it's a comment line or blank, treat as an
    903 			 * ignored error.
    904 			 */
    905 			if (escCmd[0] == commandShell->commentChar ||
    906 			    (escCmd[0] == '\0'))
    907 				cmdTemplate = commandShell->errOffOrExecIgnore;
    908 			else
    909 				cmdTemplate = commandShell->errExit;
    910 			errOff = FALSE;
    911 		}
    912 	}
    913 
    914 	if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0 &&
    915 	    !(job->flags & JOB_TRACED)) {
    916 		JobPrintln(job, "set -x");
    917 		job->flags |= JOB_TRACED;
    918 	}
    919 
    920 	JobPrintf(job, cmdTemplate, cmd);
    921 	free(cmdStart);
    922 	free(escCmd);
    923 	if (errOff) {
    924 		/*
    925 		 * If echoing is already off, there's no point in issuing the
    926 		 * echoOff command. Otherwise we issue it and pretend it was on
    927 		 * for the whole command...
    928 		 */
    929 		if (!shutUp && !(job->flags & JOB_SILENT) &&
    930 		    commandShell->hasEchoCtl) {
    931 			JobPrintln(job, commandShell->echoOff);
    932 			shutUp = TRUE;
    933 		}
    934 		JobPrintln(job, commandShell->errOnOrEcho);
    935 	}
    936 	if (shutUp && commandShell->hasEchoCtl)
    937 		JobPrintln(job, commandShell->echoOn);
    938 }
    939 
    940 /*
    941  * Print all commands to the shell file that is later executed.
    942  *
    943  * The special command "..." stops printing and saves the remaining commands
    944  * to be executed later.
    945  */
    946 static void
    947 JobPrintCommands(Job *job)
    948 {
    949 	StringListNode *ln;
    950 
    951 	for (ln = job->node->commands.first; ln != NULL; ln = ln->next) {
    952 		const char *cmd = ln->datum;
    953 
    954 		if (strcmp(cmd, "...") == 0) {
    955 			job->node->type |= OP_SAVE_CMDS;
    956 			job->tailCmds = ln->next;
    957 			break;
    958 		}
    959 
    960 		JobPrintCommand(job, ln->datum);
    961 	}
    962 }
    963 
    964 /* Save the delayed commands, to be executed when everything else is done. */
    965 static void
    966 JobSaveCommands(Job *job)
    967 {
    968 	StringListNode *ln;
    969 
    970 	for (ln = job->tailCmds; ln != NULL; ln = ln->next) {
    971 		const char *cmd = ln->datum;
    972 		char *expanded_cmd;
    973 		/* XXX: This Var_Subst is only intended to expand the dynamic
    974 		 * variables such as .TARGET, .IMPSRC.  It is not intended to
    975 		 * expand the other variables as well; see deptgt-end.mk. */
    976 		(void)Var_Subst(cmd, job->node, VARE_WANTRES, &expanded_cmd);
    977 		/* TODO: handle errors */
    978 		Lst_Append(&Targ_GetEndNode()->commands, expanded_cmd);
    979 	}
    980 }
    981 
    982 
    983 /* Called to close both input and output pipes when a job is finished. */
    984 static void
    985 JobClosePipes(Job *job)
    986 {
    987 	clearfd(job);
    988 	(void)close(job->outPipe);
    989 	job->outPipe = -1;
    990 
    991 	JobDoOutput(job, TRUE);
    992 	(void)close(job->inPipe);
    993 	job->inPipe = -1;
    994 }
    995 
    996 /*
    997  * Do final processing for the given job including updating parent nodes and
    998  * starting new jobs as available/necessary.
    999  *
   1000  * Deferred commands for the job are placed on the .END node.
   1001  *
   1002  * If there was a serious error (job_errors != 0; not an ignored one), no more
   1003  * jobs will be started.
   1004  *
   1005  * Input:
   1006  *	job		job to finish
   1007  *	status		sub-why job went away
   1008  */
   1009 static void
   1010 JobFinish(Job *job, int status)
   1011 {
   1012 	Boolean done, return_job_token;
   1013 
   1014 	DEBUG3(JOB, "JobFinish: %d [%s], status %d\n",
   1015 	    job->pid, job->node->name, status);
   1016 
   1017 	if ((WIFEXITED(status) &&
   1018 	     ((WEXITSTATUS(status) != 0 && !(job->flags & JOB_IGNERR)))) ||
   1019 	    WIFSIGNALED(status)) {
   1020 		/*
   1021 		 * If it exited non-zero and either we're doing things our
   1022 		 * way or we're not ignoring errors, the job is finished.
   1023 		 * Similarly, if the shell died because of a signal
   1024 		 * the job is also finished. In these
   1025 		 * cases, finish out the job's output before printing the exit
   1026 		 * status...
   1027 		 */
   1028 		JobClosePipes(job);
   1029 		if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
   1030 			(void)fclose(job->cmdFILE);
   1031 			job->cmdFILE = NULL;
   1032 		}
   1033 		done = TRUE;
   1034 	} else if (WIFEXITED(status)) {
   1035 		/*
   1036 		 * Deal with ignored errors in -B mode. We need to print a
   1037 		 * message telling of the ignored error as well as to run
   1038 		 * the next command.
   1039 		 */
   1040 		done = WEXITSTATUS(status) != 0;
   1041 		JobClosePipes(job);
   1042 	} else {
   1043 		/*
   1044 		 * No need to close things down or anything.
   1045 		 */
   1046 		done = FALSE;
   1047 	}
   1048 
   1049 	if (done) {
   1050 		if (WIFEXITED(status)) {
   1051 			DEBUG2(JOB, "Process %d [%s] exited.\n",
   1052 			    job->pid, job->node->name);
   1053 			if (WEXITSTATUS(status) != 0) {
   1054 				SwitchOutputTo(job->node);
   1055 #ifdef USE_META
   1056 				if (useMeta) {
   1057 					meta_job_error(job, job->node,
   1058 					    job->flags, WEXITSTATUS(status));
   1059 				}
   1060 #endif
   1061 				if (!shouldDieQuietly(job->node, -1))
   1062 					(void)printf(
   1063 					    "*** [%s] Error code %d%s\n",
   1064 					    job->node->name,
   1065 					    WEXITSTATUS(status),
   1066 					    (job->flags & JOB_IGNERR)
   1067 						? " (ignored)" : "");
   1068 				if (job->flags & JOB_IGNERR) {
   1069 					status = 0;
   1070 				} else {
   1071 					if (deleteOnError) {
   1072 						JobDeleteTarget(job->node);
   1073 					}
   1074 					PrintOnError(job->node, NULL);
   1075 				}
   1076 			} else if (DEBUG(JOB)) {
   1077 				SwitchOutputTo(job->node);
   1078 				(void)printf(
   1079 				    "*** [%s] Completed successfully\n",
   1080 				    job->node->name);
   1081 			}
   1082 		} else {
   1083 			SwitchOutputTo(job->node);
   1084 			(void)printf("*** [%s] Signal %d\n",
   1085 			    job->node->name, WTERMSIG(status));
   1086 			if (deleteOnError) {
   1087 				JobDeleteTarget(job->node);
   1088 			}
   1089 		}
   1090 		(void)fflush(stdout);
   1091 	}
   1092 
   1093 #ifdef USE_META
   1094 	if (useMeta) {
   1095 		int meta_status = meta_job_finish(job);
   1096 		if (meta_status != 0 && status == 0)
   1097 			status = meta_status;
   1098 	}
   1099 #endif
   1100 
   1101 	return_job_token = FALSE;
   1102 
   1103 	Trace_Log(JOBEND, job);
   1104 	if (!(job->flags & JOB_SPECIAL)) {
   1105 		if (status != 0 ||
   1106 		    (aborting == ABORT_ERROR) || aborting == ABORT_INTERRUPT)
   1107 			return_job_token = TRUE;
   1108 	}
   1109 
   1110 	if (aborting != ABORT_ERROR && aborting != ABORT_INTERRUPT &&
   1111 	    (status == 0)) {
   1112 		/*
   1113 		 * As long as we aren't aborting and the job didn't return a
   1114 		 * non-zero status that we shouldn't ignore, we call
   1115 		 * Make_Update to update the parents.
   1116 		 */
   1117 		JobSaveCommands(job);
   1118 		job->node->made = MADE;
   1119 		if (!(job->flags & JOB_SPECIAL))
   1120 			return_job_token = TRUE;
   1121 		Make_Update(job->node);
   1122 		job->status = JOB_ST_FREE;
   1123 	} else if (status != 0) {
   1124 		job_errors++;
   1125 		job->status = JOB_ST_FREE;
   1126 	}
   1127 
   1128 	if (job_errors > 0 && !opts.keepgoing && aborting != ABORT_INTERRUPT) {
   1129 		/* Prevent more jobs from getting started. */
   1130 		aborting = ABORT_ERROR;
   1131 	}
   1132 
   1133 	if (return_job_token)
   1134 		Job_TokenReturn();
   1135 
   1136 	if (aborting == ABORT_ERROR && jobTokensRunning == 0)
   1137 		Finish(job_errors);
   1138 }
   1139 
   1140 static void
   1141 TouchRegular(GNode *gn)
   1142 {
   1143 	const char *file = GNode_Path(gn);
   1144 	struct utimbuf times = { now, now };
   1145 	int fd;
   1146 	char c;
   1147 
   1148 	if (utime(file, &times) >= 0)
   1149 		return;
   1150 
   1151 	fd = open(file, O_RDWR | O_CREAT, 0666);
   1152 	if (fd < 0) {
   1153 		(void)fprintf(stderr, "*** couldn't touch %s: %s\n",
   1154 		    file, strerror(errno));
   1155 		(void)fflush(stderr);
   1156 		return;		/* XXX: What about propagating the error? */
   1157 	}
   1158 
   1159 	/* Last resort: update the file's time stamps in the traditional way.
   1160 	 * XXX: This doesn't work for empty files, which are sometimes used
   1161 	 * as marker files. */
   1162 	if (read(fd, &c, 1) == 1) {
   1163 		(void)lseek(fd, 0, SEEK_SET);
   1164 		while (write(fd, &c, 1) == -1 && errno == EAGAIN)
   1165 			continue;
   1166 	}
   1167 	(void)close(fd);	/* XXX: What about propagating the error? */
   1168 }
   1169 
   1170 /* Touch the given target. Called by JobStart when the -t flag was given.
   1171  *
   1172  * The modification date of the file is changed.
   1173  * If the file did not exist, it is created. */
   1174 void
   1175 Job_Touch(GNode *gn, Boolean silent)
   1176 {
   1177 	if (gn->type &
   1178 	    (OP_JOIN | OP_USE | OP_USEBEFORE | OP_EXEC | OP_OPTIONAL |
   1179 	     OP_SPECIAL | OP_PHONY)) {
   1180 		/*
   1181 		 * These are "virtual" targets and should not really be
   1182 		 * created.
   1183 		 */
   1184 		return;
   1185 	}
   1186 
   1187 	if (!silent || !GNode_ShouldExecute(gn)) {
   1188 		(void)fprintf(stdout, "touch %s\n", gn->name);
   1189 		(void)fflush(stdout);
   1190 	}
   1191 
   1192 	if (!GNode_ShouldExecute(gn))
   1193 		return;
   1194 
   1195 	if (gn->type & OP_ARCHV) {
   1196 		Arch_Touch(gn);
   1197 		return;
   1198 	}
   1199 
   1200 	if (gn->type & OP_LIB) {
   1201 		Arch_TouchLib(gn);
   1202 		return;
   1203 	}
   1204 
   1205 	TouchRegular(gn);
   1206 }
   1207 
   1208 /* Make sure the given node has all the commands it needs.
   1209  *
   1210  * The node will have commands from the .DEFAULT rule added to it if it
   1211  * needs them.
   1212  *
   1213  * Input:
   1214  *	gn		The target whose commands need verifying
   1215  *	abortProc	Function to abort with message
   1216  *
   1217  * Results:
   1218  *	TRUE if the commands list is/was ok.
   1219  */
   1220 Boolean
   1221 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
   1222 {
   1223 	if (GNode_IsTarget(gn))
   1224 		return TRUE;
   1225 	if (!Lst_IsEmpty(&gn->commands))
   1226 		return TRUE;
   1227 	if ((gn->type & OP_LIB) && !Lst_IsEmpty(&gn->children))
   1228 		return TRUE;
   1229 
   1230 	/*
   1231 	 * No commands. Look for .DEFAULT rule from which we might infer
   1232 	 * commands.
   1233 	 */
   1234 	if (defaultNode != NULL && !Lst_IsEmpty(&defaultNode->commands) &&
   1235 	    !(gn->type & OP_SPECIAL)) {
   1236 		/*
   1237 		 * The traditional Make only looks for a .DEFAULT if the node
   1238 		 * was never the target of an operator, so that's what we do
   1239 		 * too.
   1240 		 *
   1241 		 * The .DEFAULT node acts like a transformation rule, in that
   1242 		 * gn also inherits any attributes or sources attached to
   1243 		 * .DEFAULT itself.
   1244 		 */
   1245 		Make_HandleUse(defaultNode, gn);
   1246 		Var_Set(IMPSRC, GNode_VarTarget(gn), gn);
   1247 		return TRUE;
   1248 	}
   1249 
   1250 	Dir_UpdateMTime(gn, FALSE);
   1251 	if (gn->mtime != 0 || (gn->type & OP_SPECIAL))
   1252 		return TRUE;
   1253 
   1254 	/*
   1255 	 * The node wasn't the target of an operator.  We have no .DEFAULT
   1256 	 * rule to go on and the target doesn't already exist. There's
   1257 	 * nothing more we can do for this branch. If the -k flag wasn't
   1258 	 * given, we stop in our tracks, otherwise we just don't update
   1259 	 * this node's parents so they never get examined.
   1260 	 */
   1261 
   1262 	if (gn->flags & FROM_DEPEND) {
   1263 		if (!Job_RunTarget(".STALE", gn->fname))
   1264 			fprintf(stdout,
   1265 			    "%s: %s, %d: ignoring stale %s for %s\n",
   1266 			    progname, gn->fname, gn->lineno, makeDependfile,
   1267 			    gn->name);
   1268 		return TRUE;
   1269 	}
   1270 
   1271 	if (gn->type & OP_OPTIONAL) {
   1272 		(void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
   1273 		    progname, gn->name, "ignored");
   1274 		(void)fflush(stdout);
   1275 		return TRUE;
   1276 	}
   1277 
   1278 	if (opts.keepgoing) {
   1279 		(void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
   1280 		    progname, gn->name, "continuing");
   1281 		(void)fflush(stdout);
   1282 		return FALSE;
   1283 	}
   1284 
   1285 	abortProc("%s: don't know how to make %s. Stop", progname, gn->name);
   1286 	return FALSE;
   1287 }
   1288 
   1289 /* Execute the shell for the given job.
   1290  *
   1291  * See Job_CatchOutput for handling the output of the shell. */
   1292 static void
   1293 JobExec(Job *job, char **argv)
   1294 {
   1295 	int cpid;		/* ID of new child */
   1296 	sigset_t mask;
   1297 
   1298 	job->flags &= ~JOB_TRACED;
   1299 
   1300 	if (DEBUG(JOB)) {
   1301 		int i;
   1302 
   1303 		debug_printf("Running %s\n", job->node->name);
   1304 		debug_printf("\tCommand: ");
   1305 		for (i = 0; argv[i] != NULL; i++) {
   1306 			debug_printf("%s ", argv[i]);
   1307 		}
   1308 		debug_printf("\n");
   1309 	}
   1310 
   1311 	/*
   1312 	 * Some jobs produce no output and it's disconcerting to have
   1313 	 * no feedback of their running (since they produce no output, the
   1314 	 * banner with their name in it never appears). This is an attempt to
   1315 	 * provide that feedback, even if nothing follows it.
   1316 	 */
   1317 	if (!(job->flags & JOB_SILENT))
   1318 		SwitchOutputTo(job->node);
   1319 
   1320 	/* No interruptions until this job is on the `jobs' list */
   1321 	JobSigLock(&mask);
   1322 
   1323 	/* Pre-emptively mark job running, pid still zero though */
   1324 	job->status = JOB_ST_RUNNING;
   1325 
   1326 	cpid = vFork();
   1327 	if (cpid == -1)
   1328 		Punt("Cannot vfork: %s", strerror(errno));
   1329 
   1330 	if (cpid == 0) {
   1331 		/* Child */
   1332 		sigset_t tmask;
   1333 
   1334 #ifdef USE_META
   1335 		if (useMeta) {
   1336 			meta_job_child(job);
   1337 		}
   1338 #endif
   1339 		/*
   1340 		 * Reset all signal handlers; this is necessary because we
   1341 		 * also need to unblock signals before we exec(2).
   1342 		 */
   1343 		JobSigReset();
   1344 
   1345 		/* Now unblock signals */
   1346 		sigemptyset(&tmask);
   1347 		JobSigUnlock(&tmask);
   1348 
   1349 		/*
   1350 		 * Must duplicate the input stream down to the child's input
   1351 		 * and reset it to the beginning (again). Since the stream
   1352 		 * was marked close-on-exec, we must clear that bit in the
   1353 		 * new input.
   1354 		 */
   1355 		if (dup2(fileno(job->cmdFILE), 0) == -1)
   1356 			execDie("dup2", "job->cmdFILE");
   1357 		if (fcntl(0, F_SETFD, 0) == -1)
   1358 			execDie("fcntl clear close-on-exec", "stdin");
   1359 		if (lseek(0, 0, SEEK_SET) == -1)
   1360 			execDie("lseek to 0", "stdin");
   1361 
   1362 		if (job->node->type & (OP_MAKE | OP_SUBMAKE)) {
   1363 			/*
   1364 			 * Pass job token pipe to submakes.
   1365 			 */
   1366 			if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1)
   1367 				execDie("clear close-on-exec",
   1368 				    "tokenWaitJob.inPipe");
   1369 			if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1)
   1370 				execDie("clear close-on-exec",
   1371 				    "tokenWaitJob.outPipe");
   1372 		}
   1373 
   1374 		/*
   1375 		 * Set up the child's output to be routed through the pipe
   1376 		 * we've created for it.
   1377 		 */
   1378 		if (dup2(job->outPipe, 1) == -1)
   1379 			execDie("dup2", "job->outPipe");
   1380 
   1381 		/*
   1382 		 * The output channels are marked close on exec. This bit
   1383 		 * was duplicated by the dup2(on some systems), so we have
   1384 		 * to clear it before routing the shell's error output to
   1385 		 * the same place as its standard output.
   1386 		 */
   1387 		if (fcntl(1, F_SETFD, 0) == -1)
   1388 			execDie("clear close-on-exec", "stdout");
   1389 		if (dup2(1, 2) == -1)
   1390 			execDie("dup2", "1, 2");
   1391 
   1392 		/*
   1393 		 * We want to switch the child into a different process
   1394 		 * family so we can kill it and all its descendants in
   1395 		 * one fell swoop, by killing its process family, but not
   1396 		 * commit suicide.
   1397 		 */
   1398 #if defined(MAKE_NATIVE) || defined(HAVE_SETPGID)
   1399 #  if defined(SYSV)
   1400 		/* XXX: dsl - I'm sure this should be setpgrp()... */
   1401 		(void)setsid();
   1402 #  else
   1403 		(void)setpgid(0, getpid());
   1404 #  endif
   1405 #endif
   1406 
   1407 		Var_ExportVars();
   1408 
   1409 		(void)execv(shellPath, argv);
   1410 		execDie("exec", shellPath);
   1411 	}
   1412 
   1413 	/* Parent, continuing after the child exec */
   1414 	job->pid = cpid;
   1415 
   1416 	Trace_Log(JOBSTART, job);
   1417 
   1418 #ifdef USE_META
   1419 	if (useMeta) {
   1420 		meta_job_parent(job, cpid);
   1421 	}
   1422 #endif
   1423 
   1424 	/*
   1425 	 * Set the current position in the buffer to the beginning
   1426 	 * and mark another stream to watch in the outputs mask
   1427 	 */
   1428 	job->curPos = 0;
   1429 
   1430 	watchfd(job);
   1431 
   1432 	if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
   1433 		(void)fclose(job->cmdFILE);
   1434 		job->cmdFILE = NULL;
   1435 	}
   1436 
   1437 	/*
   1438 	 * Now the job is actually running, add it to the table.
   1439 	 */
   1440 	if (DEBUG(JOB)) {
   1441 		debug_printf("JobExec(%s): pid %d added to jobs table\n",
   1442 		    job->node->name, job->pid);
   1443 		job_table_dump("job started");
   1444 	}
   1445 	JobSigUnlock(&mask);
   1446 }
   1447 
   1448 /* Create the argv needed to execute the shell for a given job. */
   1449 static void
   1450 JobMakeArgv(Job *job, char **argv)
   1451 {
   1452 	int argc;
   1453 	static char args[10];	/* For merged arguments */
   1454 
   1455 	argv[0] = UNCONST(shellName);
   1456 	argc = 1;
   1457 
   1458 	if ((commandShell->exit && commandShell->exit[0] != '-') ||
   1459 	    (commandShell->echo && commandShell->echo[0] != '-')) {
   1460 		/*
   1461 		 * At least one of the flags doesn't have a minus before it,
   1462 		 * so merge them together. Have to do this because the Bourne
   1463 		 * shell thinks its second argument is a file to source.
   1464 		 * Grrrr. Note the ten-character limitation on the combined
   1465 		 * arguments.
   1466 		 *
   1467 		 * TODO: Research until when the above comments were
   1468 		 * practically relevant.
   1469 		 */
   1470 		(void)snprintf(args, sizeof args, "-%s%s",
   1471 		    ((job->flags & JOB_IGNERR) ? "" :
   1472 			(commandShell->exit ? commandShell->exit : "")),
   1473 		    ((job->flags & JOB_SILENT) ? "" :
   1474 			(commandShell->echo ? commandShell->echo : "")));
   1475 
   1476 		if (args[1]) {
   1477 			argv[argc] = args;
   1478 			argc++;
   1479 		}
   1480 	} else {
   1481 		if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
   1482 			argv[argc] = UNCONST(commandShell->exit);
   1483 			argc++;
   1484 		}
   1485 		if (!(job->flags & JOB_SILENT) && commandShell->echo) {
   1486 			argv[argc] = UNCONST(commandShell->echo);
   1487 			argc++;
   1488 		}
   1489 	}
   1490 	argv[argc] = NULL;
   1491 }
   1492 
   1493 /*
   1494  * Start a target-creation process going for the target described by the
   1495  * graph node gn.
   1496  *
   1497  * Input:
   1498  *	gn		target to create
   1499  *	flags		flags for the job to override normal ones.
   1500  *	previous	The previous Job structure for this node, if any.
   1501  *
   1502  * Results:
   1503  *	JOB_ERROR if there was an error in the commands, JOB_FINISHED
   1504  *	if there isn't actually anything left to do for the job and
   1505  *	JOB_RUNNING if the job has been started.
   1506  *
   1507  * Side Effects:
   1508  *	A new Job node is created and added to the list of running
   1509  *	jobs. PMake is forked and a child shell created.
   1510  *
   1511  * NB: The return value is ignored by everyone.
   1512  */
   1513 static JobStartResult
   1514 JobStart(GNode *gn, JobFlags flags)
   1515 {
   1516 	Job *job;		/* new job descriptor */
   1517 	char *argv[10];		/* Argument vector to shell */
   1518 	Boolean cmdsOK;		/* true if the nodes commands were all right */
   1519 	Boolean noExec;		/* Set true if we decide not to run the job */
   1520 	int tfd;		/* File descriptor to the temp file */
   1521 
   1522 	for (job = job_table; job < job_table_end; job++) {
   1523 		if (job->status == JOB_ST_FREE)
   1524 			break;
   1525 	}
   1526 	if (job >= job_table_end)
   1527 		Punt("JobStart no job slots vacant");
   1528 
   1529 	memset(job, 0, sizeof *job);
   1530 	job->node = gn;
   1531 	job->tailCmds = NULL;
   1532 	job->status = JOB_ST_SET_UP;
   1533 
   1534 	if (gn->type & OP_SPECIAL)
   1535 		flags |= JOB_SPECIAL;
   1536 	if (Targ_Ignore(gn))
   1537 		flags |= JOB_IGNERR;
   1538 	if (Targ_Silent(gn))
   1539 		flags |= JOB_SILENT;
   1540 	job->flags = flags;
   1541 
   1542 	/*
   1543 	 * Check the commands now so any attributes from .DEFAULT have a
   1544 	 * chance to migrate to the node.
   1545 	 */
   1546 	cmdsOK = Job_CheckCommands(gn, Error);
   1547 
   1548 	job->inPollfd = NULL;
   1549 	/*
   1550 	 * If the -n flag wasn't given, we open up OUR (not the child's)
   1551 	 * temporary file to stuff commands in it. The thing is rd/wr so
   1552 	 * we don't need to reopen it to feed it to the shell. If the -n
   1553 	 * flag *was* given, we just set the file to be stdout. Cute, huh?
   1554 	 */
   1555 	if (((gn->type & OP_MAKE) && !opts.noRecursiveExecute) ||
   1556 	    (!opts.noExecute && !opts.touchFlag)) {
   1557 		/*
   1558 		 * tfile is the name of a file into which all shell commands
   1559 		 * are put. It is removed before the child shell is executed,
   1560 		 * unless DEBUG(SCRIPT) is set.
   1561 		 */
   1562 		char *tfile;
   1563 		sigset_t mask;
   1564 		/*
   1565 		 * We're serious here, but if the commands were bogus, we're
   1566 		 * also dead...
   1567 		 */
   1568 		if (!cmdsOK) {
   1569 			PrintOnError(gn, NULL); /* provide some clue */
   1570 			DieHorribly();
   1571 		}
   1572 
   1573 		JobSigLock(&mask);
   1574 		tfd = mkTempFile(TMPPAT, &tfile);
   1575 		if (!DEBUG(SCRIPT))
   1576 			(void)eunlink(tfile);
   1577 		JobSigUnlock(&mask);
   1578 
   1579 		job->cmdFILE = fdopen(tfd, "w+");
   1580 		if (job->cmdFILE == NULL)
   1581 			Punt("Could not fdopen %s", tfile);
   1582 
   1583 		(void)fcntl(fileno(job->cmdFILE), F_SETFD, FD_CLOEXEC);
   1584 		/*
   1585 		 * Send the commands to the command file, flush all its
   1586 		 * buffers then rewind and remove the thing.
   1587 		 */
   1588 		noExec = FALSE;
   1589 
   1590 #ifdef USE_META
   1591 		if (useMeta) {
   1592 			meta_job_start(job, gn);
   1593 			if (Targ_Silent(gn)) /* might have changed */
   1594 				job->flags |= JOB_SILENT;
   1595 		}
   1596 #endif
   1597 		/* We can do all the commands at once. hooray for sanity */
   1598 		numCommands = 0;
   1599 		JobPrintCommands(job);
   1600 
   1601 		/*
   1602 		 * If we didn't print out any commands to the shell script,
   1603 		 * there's not much point in executing the shell, is there?
   1604 		 */
   1605 		if (numCommands == 0) {
   1606 			noExec = TRUE;
   1607 		}
   1608 
   1609 		free(tfile);
   1610 	} else if (!GNode_ShouldExecute(gn)) {
   1611 		/*
   1612 		 * Not executing anything -- just print all the commands to
   1613 		 * stdout in one fell swoop. This will still set up
   1614 		 * job->tailCmds correctly.
   1615 		 */
   1616 		SwitchOutputTo(gn);
   1617 		job->cmdFILE = stdout;
   1618 		/*
   1619 		 * Only print the commands if they're ok, but don't die if
   1620 		 * they're not -- just let the user know they're bad and
   1621 		 * keep going. It doesn't do any harm in this case and may
   1622 		 * do some good.
   1623 		 */
   1624 		if (cmdsOK)
   1625 			JobPrintCommands(job);
   1626 		/* Don't execute the shell, thank you. */
   1627 		noExec = TRUE;
   1628 	} else {
   1629 		/*
   1630 		 * Just touch the target and note that no shell should be
   1631 		 * executed. Set cmdFILE to stdout to make life easier.
   1632 		 * Check the commands, too, but don't die if they're no
   1633 		 * good -- it does no harm to keep working up the graph.
   1634 		 */
   1635 		job->cmdFILE = stdout;
   1636 		Job_Touch(gn, job->flags & JOB_SILENT);
   1637 		noExec = TRUE;
   1638 	}
   1639 	/* Just in case it isn't already... */
   1640 	(void)fflush(job->cmdFILE);
   1641 
   1642 	/* If we're not supposed to execute a shell, don't. */
   1643 	if (noExec) {
   1644 		if (!(job->flags & JOB_SPECIAL))
   1645 			Job_TokenReturn();
   1646 		/* Unlink and close the command file if we opened one */
   1647 		if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
   1648 			(void)fclose(job->cmdFILE);
   1649 			job->cmdFILE = NULL;
   1650 		}
   1651 
   1652 		/*
   1653 		 * We only want to work our way up the graph if we aren't
   1654 		 * here because the commands for the job were no good.
   1655 		 */
   1656 		if (cmdsOK && aborting == ABORT_NONE) {
   1657 			JobSaveCommands(job);
   1658 			job->node->made = MADE;
   1659 			Make_Update(job->node);
   1660 		}
   1661 		job->status = JOB_ST_FREE;
   1662 		return cmdsOK ? JOB_FINISHED : JOB_ERROR;
   1663 	}
   1664 
   1665 	/*
   1666 	 * Set up the control arguments to the shell. This is based on the
   1667 	 * flags set earlier for this job.
   1668 	 */
   1669 	JobMakeArgv(job, argv);
   1670 
   1671 	/* Create the pipe by which we'll get the shell's output. */
   1672 	JobCreatePipe(job, 3);
   1673 
   1674 	JobExec(job, argv);
   1675 	return JOB_RUNNING;
   1676 }
   1677 
   1678 /*
   1679  * Print the output of the shell command, skipping the noPrint command of
   1680  * the shell, if any.
   1681  */
   1682 static char *
   1683 JobOutput(char *cp, char *endp)
   1684 {
   1685 	char *ecp;
   1686 
   1687 	if (commandShell->noPrint == NULL || commandShell->noPrint[0] == '\0')
   1688 		return cp;
   1689 
   1690 	while ((ecp = strstr(cp, commandShell->noPrint)) != NULL) {
   1691 		if (ecp != cp) {
   1692 			*ecp = '\0';
   1693 			/*
   1694 			 * The only way there wouldn't be a newline after
   1695 			 * this line is if it were the last in the buffer.
   1696 			 * however, since the non-printable comes after it,
   1697 			 * there must be a newline, so we don't print one.
   1698 			 */
   1699 			(void)fprintf(stdout, "%s", cp);
   1700 			(void)fflush(stdout);
   1701 		}
   1702 		cp = ecp + commandShell->noPrintLen;
   1703 		if (cp != endp) {
   1704 			/*
   1705 			 * Still more to print, look again after skipping
   1706 			 * the whitespace following the non-printable
   1707 			 * command.
   1708 			 */
   1709 			cp++;
   1710 			pp_skip_whitespace(&cp);
   1711 		} else {
   1712 			return cp;
   1713 		}
   1714 	}
   1715 	return cp;
   1716 }
   1717 
   1718 /*
   1719  * This function is called whenever there is something to read on the pipe.
   1720  * We collect more output from the given job and store it in the job's
   1721  * outBuf. If this makes up a line, we print it tagged by the job's
   1722  * identifier, as necessary.
   1723  *
   1724  * In the output of the shell, the 'noPrint' lines are removed. If the
   1725  * command is not alone on the line (the character after it is not \0 or
   1726  * \n), we do print whatever follows it.
   1727  *
   1728  * Input:
   1729  *	job		the job whose output needs printing
   1730  *	finish		TRUE if this is the last time we'll be called
   1731  *			for this job
   1732  */
   1733 static void
   1734 JobDoOutput(Job *job, Boolean finish)
   1735 {
   1736 	Boolean gotNL;		/* true if got a newline */
   1737 	Boolean fbuf;		/* true if our buffer filled up */
   1738 	size_t nr;		/* number of bytes read */
   1739 	size_t i;		/* auxiliary index into outBuf */
   1740 	size_t max;		/* limit for i (end of current data) */
   1741 	ssize_t nRead;		/* (Temporary) number of bytes read */
   1742 
   1743 	/* Read as many bytes as will fit in the buffer. */
   1744 again:
   1745 	gotNL = FALSE;
   1746 	fbuf = FALSE;
   1747 
   1748 	nRead = read(job->inPipe, &job->outBuf[job->curPos],
   1749 	    JOB_BUFSIZE - job->curPos);
   1750 	if (nRead < 0) {
   1751 		if (errno == EAGAIN)
   1752 			return;
   1753 		if (DEBUG(JOB)) {
   1754 			perror("JobDoOutput(piperead)");
   1755 		}
   1756 		nr = 0;
   1757 	} else {
   1758 		nr = (size_t)nRead;
   1759 	}
   1760 
   1761 	/*
   1762 	 * If we hit the end-of-file (the job is dead), we must flush its
   1763 	 * remaining output, so pretend we read a newline if there's any
   1764 	 * output remaining in the buffer.
   1765 	 * Also clear the 'finish' flag so we stop looping.
   1766 	 */
   1767 	if (nr == 0 && job->curPos != 0) {
   1768 		job->outBuf[job->curPos] = '\n';
   1769 		nr = 1;
   1770 		finish = FALSE;
   1771 	} else if (nr == 0) {
   1772 		finish = FALSE;
   1773 	}
   1774 
   1775 	/*
   1776 	 * Look for the last newline in the bytes we just got. If there is
   1777 	 * one, break out of the loop with 'i' as its index and gotNL set
   1778 	 * TRUE.
   1779 	 */
   1780 	max = job->curPos + nr;
   1781 	for (i = job->curPos + nr - 1;
   1782 	     i >= job->curPos && i != (size_t)-1; i--) {
   1783 		if (job->outBuf[i] == '\n') {
   1784 			gotNL = TRUE;
   1785 			break;
   1786 		} else if (job->outBuf[i] == '\0') {
   1787 			/*
   1788 			 * Why?
   1789 			 */
   1790 			job->outBuf[i] = ' ';
   1791 		}
   1792 	}
   1793 
   1794 	if (!gotNL) {
   1795 		job->curPos += nr;
   1796 		if (job->curPos == JOB_BUFSIZE) {
   1797 			/*
   1798 			 * If we've run out of buffer space, we have no choice
   1799 			 * but to print the stuff. sigh.
   1800 			 */
   1801 			fbuf = TRUE;
   1802 			i = job->curPos;
   1803 		}
   1804 	}
   1805 	if (gotNL || fbuf) {
   1806 		/*
   1807 		 * Need to send the output to the screen. Null terminate it
   1808 		 * first, overwriting the newline character if there was one.
   1809 		 * So long as the line isn't one we should filter (according
   1810 		 * to the shell description), we print the line, preceded
   1811 		 * by a target banner if this target isn't the same as the
   1812 		 * one for which we last printed something.
   1813 		 * The rest of the data in the buffer are then shifted down
   1814 		 * to the start of the buffer and curPos is set accordingly.
   1815 		 */
   1816 		job->outBuf[i] = '\0';
   1817 		if (i >= job->curPos) {
   1818 			char *cp;
   1819 
   1820 			cp = JobOutput(job->outBuf, &job->outBuf[i]);
   1821 
   1822 			/*
   1823 			 * There's still more in that thar buffer. This time,
   1824 			 * though, we know there's no newline at the end, so
   1825 			 * we add one of our own free will.
   1826 			 */
   1827 			if (*cp != '\0') {
   1828 				if (!opts.beSilent)
   1829 					SwitchOutputTo(job->node);
   1830 #ifdef USE_META
   1831 				if (useMeta) {
   1832 					meta_job_output(job, cp,
   1833 					    gotNL ? "\n" : "");
   1834 				}
   1835 #endif
   1836 				(void)fprintf(stdout, "%s%s", cp,
   1837 				    gotNL ? "\n" : "");
   1838 				(void)fflush(stdout);
   1839 			}
   1840 		}
   1841 		/*
   1842 		 * max is the last offset still in the buffer. Move any
   1843 		 * remaining characters to the start of the buffer and
   1844 		 * update the end marker curPos.
   1845 		 */
   1846 		if (i < max) {
   1847 			(void)memmove(job->outBuf, &job->outBuf[i + 1],
   1848 			    max - (i + 1));
   1849 			job->curPos = max - (i + 1);
   1850 		} else {
   1851 			assert(i == max);
   1852 			job->curPos = 0;
   1853 		}
   1854 	}
   1855 	if (finish) {
   1856 		/*
   1857 		 * If the finish flag is true, we must loop until we hit
   1858 		 * end-of-file on the pipe. This is guaranteed to happen
   1859 		 * eventually since the other end of the pipe is now closed
   1860 		 * (we closed it explicitly and the child has exited). When
   1861 		 * we do get an EOF, finish will be set FALSE and we'll fall
   1862 		 * through and out.
   1863 		 */
   1864 		goto again;
   1865 	}
   1866 }
   1867 
   1868 static void
   1869 JobRun(GNode *targ)
   1870 {
   1871 #if 0
   1872 	/*
   1873 	 * Unfortunately it is too complicated to run .BEGIN, .END, and
   1874 	 * .INTERRUPT job in the parallel job module.  As of 2020-09-25,
   1875 	 * unit-tests/deptgt-end-jobs.mk hangs in an endless loop.
   1876 	 *
   1877 	 * Running these jobs in compat mode also guarantees that these
   1878 	 * jobs do not overlap with other unrelated jobs.
   1879 	 */
   1880 	List *lst = Lst_New();
   1881 	Lst_Append(lst, targ);
   1882 	(void)Make_Run(lst);
   1883 	Lst_Destroy(lst, NULL);
   1884 	JobStart(targ, JOB_SPECIAL);
   1885 	while (jobTokensRunning != 0) {
   1886 		Job_CatchOutput();
   1887 	}
   1888 #else
   1889 	Compat_Make(targ, targ);
   1890 	/* XXX: Replace with GNode_IsError(gn) */
   1891 	if (targ->made == ERROR) {
   1892 		PrintOnError(targ, "\n\nStop.");
   1893 		exit(1);
   1894 	}
   1895 #endif
   1896 }
   1897 
   1898 /* Handle the exit of a child. Called from Make_Make.
   1899  *
   1900  * The job descriptor is removed from the list of children.
   1901  *
   1902  * Notes:
   1903  *	We do waits, blocking or not, according to the wisdom of our
   1904  *	caller, until there are no more children to report. For each
   1905  *	job, call JobFinish to finish things off.
   1906  */
   1907 void
   1908 Job_CatchChildren(void)
   1909 {
   1910 	int pid;		/* pid of dead child */
   1911 	int status;		/* Exit/termination status */
   1912 
   1913 	/* Don't even bother if we know there's no one around. */
   1914 	if (jobTokensRunning == 0)
   1915 		return;
   1916 
   1917 	while ((pid = waitpid((pid_t)-1, &status, WNOHANG | WUNTRACED)) > 0) {
   1918 		DEBUG2(JOB, "Process %d exited/stopped status %x.\n",
   1919 		    pid, status);
   1920 		JobReapChild(pid, status, TRUE);
   1921 	}
   1922 }
   1923 
   1924 /*
   1925  * It is possible that wait[pid]() was called from elsewhere,
   1926  * this lets us reap jobs regardless.
   1927  */
   1928 void
   1929 JobReapChild(pid_t pid, int status, Boolean isJobs)
   1930 {
   1931 	Job *job;		/* job descriptor for dead child */
   1932 
   1933 	/* Don't even bother if we know there's no one around. */
   1934 	if (jobTokensRunning == 0)
   1935 		return;
   1936 
   1937 	job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
   1938 	if (job == NULL) {
   1939 		if (isJobs) {
   1940 			if (!lurking_children)
   1941 				Error("Child (%d) status %x not in table?",
   1942 				    pid, status);
   1943 		}
   1944 		return;		/* not ours */
   1945 	}
   1946 	if (WIFSTOPPED(status)) {
   1947 		DEBUG2(JOB, "Process %d (%s) stopped.\n",
   1948 		    job->pid, job->node->name);
   1949 		if (!make_suspended) {
   1950 			switch (WSTOPSIG(status)) {
   1951 			case SIGTSTP:
   1952 				(void)printf("*** [%s] Suspended\n",
   1953 				    job->node->name);
   1954 				break;
   1955 			case SIGSTOP:
   1956 				(void)printf("*** [%s] Stopped\n",
   1957 				    job->node->name);
   1958 				break;
   1959 			default:
   1960 				(void)printf("*** [%s] Stopped -- signal %d\n",
   1961 				    job->node->name, WSTOPSIG(status));
   1962 			}
   1963 			job->suspended = TRUE;
   1964 		}
   1965 		(void)fflush(stdout);
   1966 		return;
   1967 	}
   1968 
   1969 	job->status = JOB_ST_FINISHED;
   1970 	job->exit_status = status;
   1971 
   1972 	JobFinish(job, status);
   1973 }
   1974 
   1975 /* Catch the output from our children, if we're using pipes do so. Otherwise
   1976  * just block time until we get a signal(most likely a SIGCHLD) since there's
   1977  * no point in just spinning when there's nothing to do and the reaping of a
   1978  * child can wait for a while. */
   1979 void
   1980 Job_CatchOutput(void)
   1981 {
   1982 	int nready;
   1983 	Job *job;
   1984 	unsigned int i;
   1985 
   1986 	(void)fflush(stdout);
   1987 
   1988 	/* The first fd in the list is the job token pipe */
   1989 	do {
   1990 		nready = poll(fds + 1 - wantToken, nJobs - 1 + wantToken,
   1991 		    POLL_MSEC);
   1992 	} while (nready < 0 && errno == EINTR);
   1993 
   1994 	if (nready < 0)
   1995 		Punt("poll: %s", strerror(errno));
   1996 
   1997 	if (nready > 0 && readyfd(&childExitJob)) {
   1998 		char token = 0;
   1999 		ssize_t count;
   2000 		count = read(childExitJob.inPipe, &token, 1);
   2001 		switch (count) {
   2002 		case 0:
   2003 			Punt("unexpected eof on token pipe");
   2004 		case -1:
   2005 			Punt("token pipe read: %s", strerror(errno));
   2006 		case 1:
   2007 			if (token == DO_JOB_RESUME[0])
   2008 				/*
   2009 				 * Complete relay requested from our SIGCONT
   2010 				 * handler
   2011 				 */
   2012 				JobRestartJobs();
   2013 			break;
   2014 		default:
   2015 			abort();
   2016 		}
   2017 		nready--;
   2018 	}
   2019 
   2020 	Job_CatchChildren();
   2021 	if (nready == 0)
   2022 		return;
   2023 
   2024 	for (i = npseudojobs * nfds_per_job(); i < nJobs; i++) {
   2025 		if (!fds[i].revents)
   2026 			continue;
   2027 		job = allJobs[i];
   2028 		if (job->status == JOB_ST_RUNNING)
   2029 			JobDoOutput(job, FALSE);
   2030 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
   2031 		/*
   2032 		 * With meta mode, we may have activity on the job's filemon
   2033 		 * descriptor too, which at the moment is any pollfd other
   2034 		 * than job->inPollfd.
   2035 		 */
   2036 		if (useMeta && job->inPollfd != &fds[i]) {
   2037 			if (meta_job_event(job) <= 0) {
   2038 				fds[i].events = 0; /* never mind */
   2039 			}
   2040 		}
   2041 #endif
   2042 		if (--nready == 0)
   2043 			return;
   2044 	}
   2045 }
   2046 
   2047 /* Start the creation of a target. Basically a front-end for JobStart used by
   2048  * the Make module. */
   2049 void
   2050 Job_Make(GNode *gn)
   2051 {
   2052 	(void)JobStart(gn, JOB_NONE);
   2053 }
   2054 
   2055 static void
   2056 InitShellNameAndPath(void)
   2057 {
   2058 	shellName = commandShell->name;
   2059 
   2060 #ifdef DEFSHELL_CUSTOM
   2061 	if (shellName[0] == '/') {
   2062 		shellPath = shellName;
   2063 		shellName = strrchr(shellPath, '/') + 1;
   2064 		return;
   2065 	}
   2066 #endif
   2067 
   2068 	shellPath = str_concat3(_PATH_DEFSHELLDIR, "/", shellName);
   2069 }
   2070 
   2071 void
   2072 Shell_Init(void)
   2073 {
   2074 	if (shellPath == NULL)
   2075 		InitShellNameAndPath();
   2076 
   2077 	Var_SetWithFlags(".SHELL", shellPath, VAR_CMDLINE, VAR_SET_READONLY);
   2078 	if (commandShell->exit == NULL) {
   2079 		commandShell->exit = "";
   2080 	}
   2081 	if (commandShell->echo == NULL) {
   2082 		commandShell->echo = "";
   2083 	}
   2084 	if (commandShell->hasErrCtl && commandShell->exit[0] != '\0') {
   2085 		if (shellErrFlag &&
   2086 		    strcmp(commandShell->exit, &shellErrFlag[1]) != 0) {
   2087 			free(shellErrFlag);
   2088 			shellErrFlag = NULL;
   2089 		}
   2090 		if (shellErrFlag == NULL) {
   2091 			size_t n = strlen(commandShell->exit) + 2;
   2092 
   2093 			shellErrFlag = bmake_malloc(n);
   2094 			if (shellErrFlag != NULL) {
   2095 				snprintf(shellErrFlag, n, "-%s",
   2096 				    commandShell->exit);
   2097 			}
   2098 		}
   2099 	} else if (shellErrFlag != NULL) {
   2100 		free(shellErrFlag);
   2101 		shellErrFlag = NULL;
   2102 	}
   2103 }
   2104 
   2105 /*
   2106  * Return the string literal that is used in the current command shell
   2107  * to produce a newline character.
   2108  */
   2109 const char *
   2110 Shell_GetNewline(void)
   2111 {
   2112 	return commandShell->newline;
   2113 }
   2114 
   2115 void
   2116 Job_SetPrefix(void)
   2117 {
   2118 	if (targPrefix != NULL) {
   2119 		free(targPrefix);
   2120 	} else if (!Var_Exists(MAKE_JOB_PREFIX, VAR_GLOBAL)) {
   2121 		Var_Set(MAKE_JOB_PREFIX, "---", VAR_GLOBAL);
   2122 	}
   2123 
   2124 	(void)Var_Subst("${" MAKE_JOB_PREFIX "}",
   2125 	    VAR_GLOBAL, VARE_WANTRES, &targPrefix);
   2126 	/* TODO: handle errors */
   2127 }
   2128 
   2129 static void
   2130 AddSig(int sig, SignalProc handler)
   2131 {
   2132 	if (bmake_signal(sig, SIG_IGN) != SIG_IGN) {
   2133 		sigaddset(&caught_signals, sig);
   2134 		(void)bmake_signal(sig, handler);
   2135 	}
   2136 }
   2137 
   2138 /* Initialize the process module. */
   2139 void
   2140 Job_Init(void)
   2141 {
   2142 	Job_SetPrefix();
   2143 	/* Allocate space for all the job info */
   2144 	job_table = bmake_malloc((size_t)opts.maxJobs * sizeof *job_table);
   2145 	memset(job_table, 0, (size_t)opts.maxJobs * sizeof *job_table);
   2146 	job_table_end = job_table + opts.maxJobs;
   2147 	wantToken = 0;
   2148 
   2149 	aborting = ABORT_NONE;
   2150 	job_errors = 0;
   2151 
   2152 	/*
   2153 	 * There is a non-zero chance that we already have children.
   2154 	 * eg after 'make -f- <<EOF'
   2155 	 * Since their termination causes a 'Child (pid) not in table'
   2156 	 * message, Collect the status of any that are already dead, and
   2157 	 * suppress the error message if there are any undead ones.
   2158 	 */
   2159 	for (;;) {
   2160 		int rval, status;
   2161 		rval = waitpid((pid_t)-1, &status, WNOHANG);
   2162 		if (rval > 0)
   2163 			continue;
   2164 		if (rval == 0)
   2165 			lurking_children = TRUE;
   2166 		break;
   2167 	}
   2168 
   2169 	Shell_Init();
   2170 
   2171 	JobCreatePipe(&childExitJob, 3);
   2172 
   2173 	/* Preallocate enough for the maximum number of jobs.  */
   2174 	fds = bmake_malloc(sizeof *fds *
   2175 			   (npseudojobs + (size_t)opts.maxJobs) *
   2176 			   nfds_per_job());
   2177 	allJobs = bmake_malloc(sizeof *allJobs *
   2178 			       (npseudojobs + (size_t)opts.maxJobs) *
   2179 			       nfds_per_job());
   2180 
   2181 	/* These are permanent entries and take slots 0 and 1 */
   2182 	watchfd(&tokenWaitJob);
   2183 	watchfd(&childExitJob);
   2184 
   2185 	sigemptyset(&caught_signals);
   2186 	/*
   2187 	 * Install a SIGCHLD handler.
   2188 	 */
   2189 	(void)bmake_signal(SIGCHLD, JobChildSig);
   2190 	sigaddset(&caught_signals, SIGCHLD);
   2191 
   2192 	/*
   2193 	 * Catch the four signals that POSIX specifies if they aren't ignored.
   2194 	 * JobPassSig will take care of calling JobInterrupt if appropriate.
   2195 	 */
   2196 	AddSig(SIGINT, JobPassSig_int);
   2197 	AddSig(SIGHUP, JobPassSig_term);
   2198 	AddSig(SIGTERM, JobPassSig_term);
   2199 	AddSig(SIGQUIT, JobPassSig_term);
   2200 
   2201 	/*
   2202 	 * There are additional signals that need to be caught and passed if
   2203 	 * either the export system wants to be told directly of signals or if
   2204 	 * we're giving each job its own process group (since then it won't get
   2205 	 * signals from the terminal driver as we own the terminal)
   2206 	 */
   2207 	AddSig(SIGTSTP, JobPassSig_suspend);
   2208 	AddSig(SIGTTOU, JobPassSig_suspend);
   2209 	AddSig(SIGTTIN, JobPassSig_suspend);
   2210 	AddSig(SIGWINCH, JobCondPassSig);
   2211 	AddSig(SIGCONT, JobContinueSig);
   2212 
   2213 	(void)Job_RunTarget(".BEGIN", NULL);
   2214 	/* Create the .END node now, even though no code in the unit tests
   2215 	 * depends on it.  See also Targ_GetEndNode in Compat_Run. */
   2216 	(void)Targ_GetEndNode();
   2217 }
   2218 
   2219 static void
   2220 DelSig(int sig)
   2221 {
   2222 	if (sigismember(&caught_signals, sig))
   2223 		(void)bmake_signal(sig, SIG_DFL);
   2224 }
   2225 
   2226 static void JobSigReset(void)
   2227 {
   2228 	DelSig(SIGINT);
   2229 	DelSig(SIGHUP);
   2230 	DelSig(SIGQUIT);
   2231 	DelSig(SIGTERM);
   2232 	DelSig(SIGTSTP);
   2233 	DelSig(SIGTTOU);
   2234 	DelSig(SIGTTIN);
   2235 	DelSig(SIGWINCH);
   2236 	DelSig(SIGCONT);
   2237 	(void)bmake_signal(SIGCHLD, SIG_DFL);
   2238 }
   2239 
   2240 /* Find a shell in 'shells' given its name, or return NULL. */
   2241 static Shell *
   2242 FindShellByName(const char *name)
   2243 {
   2244 	Shell *sh = shells;
   2245 	const Shell *shellsEnd = sh + sizeof shells / sizeof shells[0];
   2246 
   2247 	for (sh = shells; sh < shellsEnd; sh++) {
   2248 		if (strcmp(name, sh->name) == 0)
   2249 			return sh;
   2250 	}
   2251 	return NULL;
   2252 }
   2253 
   2254 /*
   2255  * Parse a shell specification and set up commandShell, shellPath and
   2256  * shellName appropriately.
   2257  *
   2258  * Input:
   2259  *	line		The shell spec
   2260  *
   2261  * Results:
   2262  *	FALSE if the specification was incorrect.
   2263  *
   2264  * Side Effects:
   2265  *	commandShell points to a Shell structure (either predefined or
   2266  *	created from the shell spec), shellPath is the full path of the
   2267  *	shell described by commandShell, while shellName is just the
   2268  *	final component of shellPath.
   2269  *
   2270  * Notes:
   2271  *	A shell specification consists of a .SHELL target, with dependency
   2272  *	operator, followed by a series of blank-separated words. Double
   2273  *	quotes can be used to use blanks in words. A backslash escapes
   2274  *	anything (most notably a double-quote and a space) and
   2275  *	provides the functionality it does in C. Each word consists of
   2276  *	keyword and value separated by an equal sign. There should be no
   2277  *	unnecessary spaces in the word. The keywords are as follows:
   2278  *	    name	Name of shell.
   2279  *	    path	Location of shell.
   2280  *	    quiet	Command to turn off echoing.
   2281  *	    echo	Command to turn echoing on
   2282  *	    filter	Result of turning off echoing that shouldn't be
   2283  *			printed.
   2284  *	    echoFlag	Flag to turn echoing on at the start
   2285  *	    errFlag	Flag to turn error checking on at the start
   2286  *	    hasErrCtl	True if shell has error checking control
   2287  *	    newline	String literal to represent a newline char
   2288  *	    check	Command to turn on error checking if hasErrCtl
   2289  *			is TRUE or template of command to echo a command
   2290  *			for which error checking is off if hasErrCtl is
   2291  *			FALSE.
   2292  *	    ignore	Command to turn off error checking if hasErrCtl
   2293  *			is TRUE or template of command to execute a
   2294  *			command so as to ignore any errors it returns if
   2295  *			hasErrCtl is FALSE.
   2296  */
   2297 Boolean
   2298 Job_ParseShell(char *line)
   2299 {
   2300 	Words wordsList;
   2301 	char **words;
   2302 	char **argv;
   2303 	size_t argc;
   2304 	char *path;
   2305 	Shell newShell;
   2306 	Boolean fullSpec = FALSE;
   2307 	Shell *sh;
   2308 
   2309 	pp_skip_whitespace(&line);
   2310 
   2311 	free(shellArgv);
   2312 
   2313 	memset(&newShell, 0, sizeof newShell);
   2314 
   2315 	/*
   2316 	 * Parse the specification by keyword
   2317 	 */
   2318 	wordsList = Str_Words(line, TRUE);
   2319 	words = wordsList.words;
   2320 	argc = wordsList.len;
   2321 	path = wordsList.freeIt;
   2322 	if (words == NULL) {
   2323 		Error("Unterminated quoted string [%s]", line);
   2324 		return FALSE;
   2325 	}
   2326 	shellArgv = path;
   2327 
   2328 	for (path = NULL, argv = words; argc != 0; argc--, argv++) {
   2329 		char *arg = *argv;
   2330 		if (strncmp(arg, "path=", 5) == 0) {
   2331 			path = arg + 5;
   2332 		} else if (strncmp(arg, "name=", 5) == 0) {
   2333 			newShell.name = arg + 5;
   2334 		} else {
   2335 			if (strncmp(arg, "quiet=", 6) == 0) {
   2336 				newShell.echoOff = arg + 6;
   2337 			} else if (strncmp(arg, "echo=", 5) == 0) {
   2338 				newShell.echoOn = arg + 5;
   2339 			} else if (strncmp(arg, "filter=", 7) == 0) {
   2340 				newShell.noPrint = arg + 7;
   2341 				newShell.noPrintLen = strlen(newShell.noPrint);
   2342 			} else if (strncmp(arg, "echoFlag=", 9) == 0) {
   2343 				newShell.echo = arg + 9;
   2344 			} else if (strncmp(arg, "errFlag=", 8) == 0) {
   2345 				newShell.exit = arg + 8;
   2346 			} else if (strncmp(arg, "hasErrCtl=", 10) == 0) {
   2347 				char c = arg[10];
   2348 				newShell.hasErrCtl = c == 'Y' || c == 'y' ||
   2349 						     c == 'T' || c == 't';
   2350 			} else if (strncmp(arg, "newline=", 8) == 0) {
   2351 				newShell.newline = arg + 8;
   2352 			} else if (strncmp(arg, "check=", 6) == 0) {
   2353 				newShell.errOnOrEcho = arg + 6;
   2354 			} else if (strncmp(arg, "ignore=", 7) == 0) {
   2355 				newShell.errOffOrExecIgnore = arg + 7;
   2356 			} else if (strncmp(arg, "errout=", 7) == 0) {
   2357 				newShell.errExit = arg + 7;
   2358 			} else if (strncmp(arg, "comment=", 8) == 0) {
   2359 				newShell.commentChar = arg[8];
   2360 			} else {
   2361 				Parse_Error(PARSE_FATAL,
   2362 				    "Unknown keyword \"%s\"", arg);
   2363 				free(words);
   2364 				return FALSE;
   2365 			}
   2366 			fullSpec = TRUE;
   2367 		}
   2368 	}
   2369 
   2370 	if (path == NULL) {
   2371 		/*
   2372 		 * If no path was given, the user wants one of the
   2373 		 * pre-defined shells, yes? So we find the one s/he wants
   2374 		 * with the help of FindShellByName and set things up the
   2375 		 * right way. shellPath will be set up by Shell_Init.
   2376 		 */
   2377 		if (newShell.name == NULL) {
   2378 			Parse_Error(PARSE_FATAL,
   2379 			    "Neither path nor name specified");
   2380 			free(words);
   2381 			return FALSE;
   2382 		} else {
   2383 			if ((sh = FindShellByName(newShell.name)) == NULL) {
   2384 				Parse_Error(PARSE_WARNING,
   2385 				    "%s: No matching shell", newShell.name);
   2386 				free(words);
   2387 				return FALSE;
   2388 			}
   2389 			commandShell = sh;
   2390 			shellName = newShell.name;
   2391 			if (shellPath != NULL) {
   2392 				/*
   2393 				 * Shell_Init has already been called!
   2394 				 * Do it again.
   2395 				 */
   2396 				free(UNCONST(shellPath));
   2397 				shellPath = NULL;
   2398 				Shell_Init();
   2399 			}
   2400 		}
   2401 	} else {
   2402 		/*
   2403 		 * The user provided a path. If s/he gave nothing else
   2404 		 * (fullSpec is FALSE), try and find a matching shell in the
   2405 		 * ones we know of. Else we just take the specification at
   2406 		 * its word and copy it to a new location. In either case,
   2407 		 * we need to record the path the user gave for the shell.
   2408 		 */
   2409 		shellPath = path;
   2410 		path = strrchr(path, '/');
   2411 		if (path == NULL) {
   2412 			path = UNCONST(shellPath);
   2413 		} else {
   2414 			path++;
   2415 		}
   2416 		if (newShell.name != NULL) {
   2417 			shellName = newShell.name;
   2418 		} else {
   2419 			shellName = path;
   2420 		}
   2421 		if (!fullSpec) {
   2422 			if ((sh = FindShellByName(shellName)) == NULL) {
   2423 				Parse_Error(PARSE_WARNING,
   2424 				    "%s: No matching shell", shellName);
   2425 				free(words);
   2426 				return FALSE;
   2427 			}
   2428 			commandShell = sh;
   2429 		} else {
   2430 			commandShell = bmake_malloc(sizeof *commandShell);
   2431 			*commandShell = newShell;
   2432 		}
   2433 		/* this will take care of shellErrFlag */
   2434 		Shell_Init();
   2435 	}
   2436 
   2437 	if (commandShell->echoOn && commandShell->echoOff) {
   2438 		commandShell->hasEchoCtl = TRUE;
   2439 	}
   2440 
   2441 	if (!commandShell->hasErrCtl) {
   2442 		if (commandShell->errOnOrEcho == NULL) {
   2443 			commandShell->errOnOrEcho = "";
   2444 		}
   2445 		if (commandShell->errOffOrExecIgnore == NULL) {
   2446 			commandShell->errOffOrExecIgnore = "%s\n";
   2447 		}
   2448 	}
   2449 
   2450 	/*
   2451 	 * Do not free up the words themselves, since they might be in use
   2452 	 * by the shell specification.
   2453 	 */
   2454 	free(words);
   2455 	return TRUE;
   2456 }
   2457 
   2458 /*
   2459  * Handle the receipt of an interrupt.
   2460  *
   2461  * All children are killed. Another job will be started if the .INTERRUPT
   2462  * target is defined.
   2463  *
   2464  * Input:
   2465  *	runINTERRUPT	Non-zero if commands for the .INTERRUPT target
   2466  *			should be executed
   2467  *	signo		signal received
   2468  */
   2469 static void
   2470 JobInterrupt(int runINTERRUPT, int signo)
   2471 {
   2472 	Job *job;		/* job descriptor in that element */
   2473 	GNode *interrupt;	/* the node describing the .INTERRUPT target */
   2474 	sigset_t mask;
   2475 	GNode *gn;
   2476 
   2477 	aborting = ABORT_INTERRUPT;
   2478 
   2479 	JobSigLock(&mask);
   2480 
   2481 	for (job = job_table; job < job_table_end; job++) {
   2482 		if (job->status != JOB_ST_RUNNING)
   2483 			continue;
   2484 
   2485 		gn = job->node;
   2486 
   2487 		JobDeleteTarget(gn);
   2488 		if (job->pid) {
   2489 			DEBUG2(JOB,
   2490 			    "JobInterrupt passing signal %d to child %d.\n",
   2491 			    signo, job->pid);
   2492 			KILLPG(job->pid, signo);
   2493 		}
   2494 	}
   2495 
   2496 	JobSigUnlock(&mask);
   2497 
   2498 	if (runINTERRUPT && !opts.touchFlag) {
   2499 		interrupt = Targ_FindNode(".INTERRUPT");
   2500 		if (interrupt != NULL) {
   2501 			opts.ignoreErrors = FALSE;
   2502 			JobRun(interrupt);
   2503 		}
   2504 	}
   2505 	Trace_Log(MAKEINTR, NULL);
   2506 	exit(signo);
   2507 }
   2508 
   2509 /*
   2510  * Do the final processing, i.e. run the commands attached to the .END target.
   2511  *
   2512  * Return the number of errors reported.
   2513  */
   2514 int
   2515 Job_Finish(void)
   2516 {
   2517 	GNode *endNode = Targ_GetEndNode();
   2518 	if (!Lst_IsEmpty(&endNode->commands) ||
   2519 	    !Lst_IsEmpty(&endNode->children)) {
   2520 		if (job_errors != 0) {
   2521 			Error("Errors reported so .END ignored");
   2522 		} else {
   2523 			JobRun(endNode);
   2524 		}
   2525 	}
   2526 	return job_errors;
   2527 }
   2528 
   2529 /* Clean up any memory used by the jobs module. */
   2530 void
   2531 Job_End(void)
   2532 {
   2533 #ifdef CLEANUP
   2534 	free(shellArgv);
   2535 #endif
   2536 }
   2537 
   2538 /*
   2539  * Waits for all running jobs to finish and returns.
   2540  * Sets 'aborting' to ABORT_WAIT to prevent other jobs from starting.
   2541  */
   2542 void
   2543 Job_Wait(void)
   2544 {
   2545 	aborting = ABORT_WAIT;
   2546 	while (jobTokensRunning != 0) {
   2547 		Job_CatchOutput();
   2548 	}
   2549 	aborting = ABORT_NONE;
   2550 }
   2551 
   2552 /*
   2553  * Abort all currently running jobs without handling output or anything.
   2554  * This function is to be called only in the event of a major error.
   2555  * Most definitely NOT to be called from JobInterrupt.
   2556  *
   2557  * All children are killed, not just the firstborn.
   2558  */
   2559 void
   2560 Job_AbortAll(void)
   2561 {
   2562 	Job *job;		/* the job descriptor in that element */
   2563 	int foo;
   2564 
   2565 	aborting = ABORT_ERROR;
   2566 
   2567 	if (jobTokensRunning != 0) {
   2568 		for (job = job_table; job < job_table_end; job++) {
   2569 			if (job->status != JOB_ST_RUNNING)
   2570 				continue;
   2571 			/*
   2572 			 * kill the child process with increasingly drastic
   2573 			 * signals to make darn sure it's dead.
   2574 			 */
   2575 			KILLPG(job->pid, SIGINT);
   2576 			KILLPG(job->pid, SIGKILL);
   2577 		}
   2578 	}
   2579 
   2580 	/*
   2581 	 * Catch as many children as want to report in at first, then give up
   2582 	 */
   2583 	while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
   2584 		continue;
   2585 }
   2586 
   2587 /*
   2588  * Tries to restart stopped jobs if there are slots available.
   2589  * Called in process context in response to a SIGCONT.
   2590  */
   2591 static void
   2592 JobRestartJobs(void)
   2593 {
   2594 	Job *job;
   2595 
   2596 	for (job = job_table; job < job_table_end; job++) {
   2597 		if (job->status == JOB_ST_RUNNING &&
   2598 		    (make_suspended || job->suspended)) {
   2599 			DEBUG1(JOB, "Restarting stopped job pid %d.\n",
   2600 			    job->pid);
   2601 			if (job->suspended) {
   2602 				(void)printf("*** [%s] Continued\n",
   2603 				    job->node->name);
   2604 				(void)fflush(stdout);
   2605 			}
   2606 			job->suspended = FALSE;
   2607 			if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
   2608 				debug_printf("Failed to send SIGCONT to %d\n",
   2609 				    job->pid);
   2610 			}
   2611 		}
   2612 		if (job->status == JOB_ST_FINISHED) {
   2613 			/*
   2614 			 * Job exit deferred after calling waitpid() in a
   2615 			 * signal handler
   2616 			 */
   2617 			JobFinish(job, job->exit_status);
   2618 		}
   2619 	}
   2620 	make_suspended = FALSE;
   2621 }
   2622 
   2623 static void
   2624 watchfd(Job *job)
   2625 {
   2626 	if (job->inPollfd != NULL)
   2627 		Punt("Watching watched job");
   2628 
   2629 	fds[nJobs].fd = job->inPipe;
   2630 	fds[nJobs].events = POLLIN;
   2631 	allJobs[nJobs] = job;
   2632 	job->inPollfd = &fds[nJobs];
   2633 	nJobs++;
   2634 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
   2635 	if (useMeta) {
   2636 		fds[nJobs].fd = meta_job_fd(job);
   2637 		fds[nJobs].events = fds[nJobs].fd == -1 ? 0 : POLLIN;
   2638 		allJobs[nJobs] = job;
   2639 		nJobs++;
   2640 	}
   2641 #endif
   2642 }
   2643 
   2644 static void
   2645 clearfd(Job *job)
   2646 {
   2647 	size_t i;
   2648 	if (job->inPollfd == NULL)
   2649 		Punt("Unwatching unwatched job");
   2650 	i = (size_t)(job->inPollfd - fds);
   2651 	nJobs--;
   2652 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
   2653 	if (useMeta) {
   2654 		/*
   2655 		 * Sanity check: there should be two fds per job, so the job's
   2656 		 * pollfd number should be even.
   2657 		 */
   2658 		assert(nfds_per_job() == 2);
   2659 		if (i % 2)
   2660 			Punt("odd-numbered fd with meta");
   2661 		nJobs--;
   2662 	}
   2663 #endif
   2664 	/*
   2665 	 * Move last job in table into hole made by dead job.
   2666 	 */
   2667 	if (nJobs != i) {
   2668 		fds[i] = fds[nJobs];
   2669 		allJobs[i] = allJobs[nJobs];
   2670 		allJobs[i]->inPollfd = &fds[i];
   2671 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
   2672 		if (useMeta) {
   2673 			fds[i + 1] = fds[nJobs + 1];
   2674 			allJobs[i + 1] = allJobs[nJobs + 1];
   2675 		}
   2676 #endif
   2677 	}
   2678 	job->inPollfd = NULL;
   2679 }
   2680 
   2681 static int
   2682 readyfd(Job *job)
   2683 {
   2684 	if (job->inPollfd == NULL)
   2685 		Punt("Polling unwatched job");
   2686 	return (job->inPollfd->revents & POLLIN) != 0;
   2687 }
   2688 
   2689 /* Put a token (back) into the job pipe.
   2690  * This allows a make process to start a build job. */
   2691 static void
   2692 JobTokenAdd(void)
   2693 {
   2694 	char tok = JOB_TOKENS[aborting], tok1;
   2695 
   2696 	/* If we are depositing an error token flush everything else */
   2697 	while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
   2698 		continue;
   2699 
   2700 	DEBUG3(JOB, "(%d) aborting %d, deposit token %c\n",
   2701 	    getpid(), aborting, JOB_TOKENS[aborting]);
   2702 	while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
   2703 		continue;
   2704 }
   2705 
   2706 /* Prep the job token pipe in the root make process. */
   2707 void
   2708 Job_ServerStart(int max_tokens, int jp_0, int jp_1)
   2709 {
   2710 	int i;
   2711 	char jobarg[64];
   2712 
   2713 	if (jp_0 >= 0 && jp_1 >= 0) {
   2714 		/* Pipe passed in from parent */
   2715 		tokenWaitJob.inPipe = jp_0;
   2716 		tokenWaitJob.outPipe = jp_1;
   2717 		(void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
   2718 		(void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
   2719 		return;
   2720 	}
   2721 
   2722 	JobCreatePipe(&tokenWaitJob, 15);
   2723 
   2724 	snprintf(jobarg, sizeof jobarg, "%d,%d",
   2725 	    tokenWaitJob.inPipe, tokenWaitJob.outPipe);
   2726 
   2727 	Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
   2728 	Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
   2729 
   2730 	/*
   2731 	 * Preload the job pipe with one token per job, save the one
   2732 	 * "extra" token for the primary job.
   2733 	 *
   2734 	 * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
   2735 	 * larger than the write buffer size of the pipe, we will
   2736 	 * deadlock here.
   2737 	 */
   2738 	for (i = 1; i < max_tokens; i++)
   2739 		JobTokenAdd();
   2740 }
   2741 
   2742 /* Return a withdrawn token to the pool. */
   2743 void
   2744 Job_TokenReturn(void)
   2745 {
   2746 	jobTokensRunning--;
   2747 	if (jobTokensRunning < 0)
   2748 		Punt("token botch");
   2749 	if (jobTokensRunning || JOB_TOKENS[aborting] != '+')
   2750 		JobTokenAdd();
   2751 }
   2752 
   2753 /*
   2754  * Attempt to withdraw a token from the pool.
   2755  *
   2756  * If pool is empty, set wantToken so that we wake up when a token is
   2757  * released.
   2758  *
   2759  * Returns TRUE if a token was withdrawn, and FALSE if the pool is currently
   2760  * empty.
   2761  */
   2762 Boolean
   2763 Job_TokenWithdraw(void)
   2764 {
   2765 	char tok, tok1;
   2766 	ssize_t count;
   2767 
   2768 	wantToken = 0;
   2769 	DEBUG3(JOB, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
   2770 	    getpid(), aborting, jobTokensRunning);
   2771 
   2772 	if (aborting != ABORT_NONE || (jobTokensRunning >= opts.maxJobs))
   2773 		return FALSE;
   2774 
   2775 	count = read(tokenWaitJob.inPipe, &tok, 1);
   2776 	if (count == 0)
   2777 		Fatal("eof on job pipe!");
   2778 	if (count < 0 && jobTokensRunning != 0) {
   2779 		if (errno != EAGAIN) {
   2780 			Fatal("job pipe read: %s", strerror(errno));
   2781 		}
   2782 		DEBUG1(JOB, "(%d) blocked for token\n", getpid());
   2783 		return FALSE;
   2784 	}
   2785 
   2786 	if (count == 1 && tok != '+') {
   2787 		/* make being aborted - remove any other job tokens */
   2788 		DEBUG2(JOB, "(%d) aborted by token %c\n", getpid(), tok);
   2789 		while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
   2790 			continue;
   2791 		/* And put the stopper back */
   2792 		while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
   2793 		       errno == EAGAIN)
   2794 			continue;
   2795 		if (shouldDieQuietly(NULL, 1))
   2796 			exit(2);
   2797 		Fatal("A failure has been detected "
   2798 		      "in another branch of the parallel make");
   2799 	}
   2800 
   2801 	if (count == 1 && jobTokensRunning == 0)
   2802 		/* We didn't want the token really */
   2803 		while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
   2804 		       errno == EAGAIN)
   2805 			continue;
   2806 
   2807 	jobTokensRunning++;
   2808 	DEBUG1(JOB, "(%d) withdrew token\n", getpid());
   2809 	return TRUE;
   2810 }
   2811 
   2812 /*
   2813  * Run the named target if found. If a filename is specified, then set that
   2814  * to the sources.
   2815  *
   2816  * Exits if the target fails.
   2817  */
   2818 Boolean
   2819 Job_RunTarget(const char *target, const char *fname)
   2820 {
   2821 	GNode *gn = Targ_FindNode(target);
   2822 	if (gn == NULL)
   2823 		return FALSE;
   2824 
   2825 	if (fname != NULL)
   2826 		Var_Set(ALLSRC, fname, gn);
   2827 
   2828 	JobRun(gn);
   2829 	/* XXX: Replace with GNode_IsError(gn) */
   2830 	if (gn->made == ERROR) {
   2831 		PrintOnError(gn, "\n\nStop.");
   2832 		exit(1);
   2833 	}
   2834 	return TRUE;
   2835 }
   2836 
   2837 #ifdef USE_SELECT
   2838 int
   2839 emul_poll(struct pollfd *fd, int nfd, int timeout)
   2840 {
   2841 	fd_set rfds, wfds;
   2842 	int i, maxfd, nselect, npoll;
   2843 	struct timeval tv, *tvp;
   2844 	long usecs;
   2845 
   2846 	FD_ZERO(&rfds);
   2847 	FD_ZERO(&wfds);
   2848 
   2849 	maxfd = -1;
   2850 	for (i = 0; i < nfd; i++) {
   2851 		fd[i].revents = 0;
   2852 
   2853 		if (fd[i].events & POLLIN)
   2854 			FD_SET(fd[i].fd, &rfds);
   2855 
   2856 		if (fd[i].events & POLLOUT)
   2857 			FD_SET(fd[i].fd, &wfds);
   2858 
   2859 		if (fd[i].fd > maxfd)
   2860 			maxfd = fd[i].fd;
   2861 	}
   2862 
   2863 	if (maxfd >= FD_SETSIZE) {
   2864 		Punt("Ran out of fd_set slots; "
   2865 		     "recompile with a larger FD_SETSIZE.");
   2866 	}
   2867 
   2868 	if (timeout < 0) {
   2869 		tvp = NULL;
   2870 	} else {
   2871 		usecs = timeout * 1000;
   2872 		tv.tv_sec = usecs / 1000000;
   2873 		tv.tv_usec = usecs % 1000000;
   2874 		tvp = &tv;
   2875 	}
   2876 
   2877 	nselect = select(maxfd + 1, &rfds, &wfds, NULL, tvp);
   2878 
   2879 	if (nselect <= 0)
   2880 		return nselect;
   2881 
   2882 	npoll = 0;
   2883 	for (i = 0; i < nfd; i++) {
   2884 		if (FD_ISSET(fd[i].fd, &rfds))
   2885 			fd[i].revents |= POLLIN;
   2886 
   2887 		if (FD_ISSET(fd[i].fd, &wfds))
   2888 			fd[i].revents |= POLLOUT;
   2889 
   2890 		if (fd[i].revents)
   2891 			npoll++;
   2892 	}
   2893 
   2894 	return npoll;
   2895 }
   2896 #endif /* USE_SELECT */
   2897