Home | History | Annotate | Line # | Download | only in make
job.c revision 1.345
      1 /*	$NetBSD: job.c,v 1.345 2020/12/08 00:23:30 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.345 2020/12/08 00:23:30 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 static void
    734 JobPrintSpecials(Job *const job, const char *const escCmd,
    735 		 Boolean const noSpecials, Boolean *const inout_shutUp,
    736 		 const char **const inout_cmdTemplate,
    737 		 Boolean *const inout_errOff)
    738 {
    739 	if (!noSpecials) {
    740 		if (commandShell->hasErrCtl) {
    741 			/*
    742 			 * we don't want the error-control commands
    743 			 * showing up either, so we turn off echoing
    744 			 * while executing them. We could put another
    745 			 * field in the shell structure to tell
    746 			 * JobDoOutput to look for this string too,
    747 			 * but why make it any more complex than
    748 			 * it already is?
    749 			 */
    750 			if (!(job->flags & JOB_SILENT) && !*inout_shutUp &&
    751 			    (commandShell->hasEchoCtl)) {
    752 				JobPrintln(job, commandShell->echoOff);
    753 				JobPrintln(job,
    754 				    commandShell->errOffOrExecIgnore);
    755 				JobPrintln(job, commandShell->echoOn);
    756 			} else {
    757 				JobPrintln(job,
    758 				    commandShell->errOffOrExecIgnore);
    759 			}
    760 		} else if (commandShell->errOffOrExecIgnore &&
    761 			   commandShell->errOffOrExecIgnore[0] !=
    762 			   '\0') {
    763 			/*
    764 			 * The shell has no error control, so we need
    765 			 * to be weird to get it to ignore any errors
    766 			 * from the command. If echoing is turned on,
    767 			 * we turn it off and use the errOnOrEcho
    768 			 * template to echo the command. Leave echoing
    769 			 * off so the user doesn't see the weirdness
    770 			 * we go through to ignore errors. Set
    771 			 * cmdTemplate to use the weirdness instead
    772 			 * of the simple "%s\n" template.
    773 			 */
    774 			job->flags |= JOB_IGNERR;
    775 			if (!(job->flags & JOB_SILENT) && !*inout_shutUp) {
    776 				if (commandShell->hasEchoCtl) {
    777 					JobPrintln(job,
    778 					    commandShell->echoOff);
    779 				}
    780 				JobPrintf(job,
    781 				    commandShell->errOnOrEcho, escCmd);
    782 				*inout_shutUp = TRUE;
    783 			} else {
    784 				if (!*inout_shutUp)
    785 					JobPrintf(job,
    786 					    commandShell->errOnOrEcho,
    787 					    escCmd);
    788 			}
    789 			*inout_cmdTemplate = commandShell->errOffOrExecIgnore;
    790 			/*
    791 			 * The error ignoration (hee hee) is already
    792 			 * taken care of by the errOffOrExecIgnore
    793 			 * template, so pretend error checking is
    794 			 * still on.
    795 			 */
    796 			*inout_errOff = FALSE;
    797 		} else {
    798 			*inout_errOff = FALSE;
    799 		}
    800 	} else {
    801 		*inout_errOff = FALSE;
    802 	}
    803 }
    804 
    805 /*
    806  * Put out another command for the given job. If the command starts with an
    807  * '@' or a '-' we process it specially. In the former case, so long as the
    808  * -s and -n flags weren't given to make, we stick a shell-specific echoOff
    809  * command in the script. In the latter, we ignore errors for the entire job,
    810  * unless the shell has error control.
    811  *
    812  * If the command is just "..." we take all future commands for this job to
    813  * be commands to be executed once the entire graph has been made and return
    814  * non-zero to signal that the end of the commands was reached. These commands
    815  * are later attached to the .END node and executed by Job_End when all things
    816  * are done.
    817  *
    818  * Side Effects:
    819  *	If the command begins with a '-' and the shell has no error control,
    820  *	the JOB_IGNERR flag is set in the job descriptor.
    821  *	numCommands is incremented if the command is actually printed.
    822  */
    823 static void
    824 JobPrintCommand(Job *job, char *cmd)
    825 {
    826 	const char *const cmdp = cmd;
    827 	/*
    828 	 * true if we shouldn't worry about inserting special commands into
    829 	 * the input stream.
    830 	 */
    831 	Boolean noSpecials;
    832 	/* true if we put a no echo command into the command file */
    833 	Boolean shutUp;
    834 	/*
    835 	 * true if we turned error checking off before printing the command
    836 	 * and need to turn it back on
    837 	 */
    838 	Boolean errOff;
    839 	Boolean runAlways;
    840 	/* Template to use when printing the command */
    841 	const char *cmdTemplate;
    842 	char *cmdStart;		/* Start of expanded command */
    843 	char *escCmd = NULL;	/* Command with quotes/backticks escaped */
    844 
    845 	noSpecials = !GNode_ShouldExecute(job->node);
    846 
    847 	numCommands++;
    848 
    849 	Var_Subst(cmd, job->node, VARE_WANTRES, &cmd);
    850 	/* TODO: handle errors */
    851 	cmdStart = cmd;
    852 
    853 	cmdTemplate = "%s\n";
    854 
    855 	ParseRunOptions(&cmd, &shutUp, &errOff, &runAlways);
    856 
    857 	if (runAlways && noSpecials) {
    858 		/*
    859 		 * We're not actually executing anything...
    860 		 * but this one needs to be - use compat mode just for it.
    861 		 */
    862 		Compat_RunCommand(cmdp, job->node);
    863 		free(cmdStart);
    864 		return;
    865 	}
    866 
    867 	/*
    868 	 * If the shell doesn't have error control the alternate echo'ing will
    869 	 * be done (to avoid showing additional error checking code)
    870 	 * and this will need the characters '$ ` \ "' escaped
    871 	 */
    872 
    873 	if (!commandShell->hasErrCtl)
    874 		escCmd = EscapeShellDblQuot(cmd);
    875 
    876 	if (shutUp) {
    877 		if (!(job->flags & JOB_SILENT) && !noSpecials &&
    878 		    commandShell->hasEchoCtl) {
    879 			JobPrintln(job, commandShell->echoOff);
    880 		} else {
    881 			if (commandShell->hasErrCtl)
    882 				shutUp = FALSE;
    883 		}
    884 	}
    885 
    886 	if (errOff) {
    887 		JobPrintSpecials(job, escCmd, noSpecials, &shutUp, &cmdTemplate,
    888 		    &errOff);
    889 	} else {
    890 
    891 		/*
    892 		 * If errors are being checked and the shell doesn't have
    893 		 * error control but does supply an errExit template, then
    894 		 * set up commands to run through it.
    895 		 */
    896 
    897 		if (!commandShell->hasErrCtl && commandShell->errExit &&
    898 		    commandShell->errExit[0] != '\0') {
    899 			if (!(job->flags & JOB_SILENT) && !shutUp) {
    900 				if (commandShell->hasEchoCtl)
    901 					JobPrintln(job, commandShell->echoOff);
    902 				JobPrintf(job, commandShell->errOnOrEcho,
    903 				    escCmd);
    904 				shutUp = TRUE;
    905 			}
    906 			/*
    907 			 * If it's a comment line or blank, treat as an
    908 			 * ignored error.
    909 			 */
    910 			if (escCmd[0] == commandShell->commentChar ||
    911 			    (escCmd[0] == '\0'))
    912 				cmdTemplate = commandShell->errOffOrExecIgnore;
    913 			else
    914 				cmdTemplate = commandShell->errExit;
    915 			errOff = FALSE;
    916 		}
    917 	}
    918 
    919 	if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0 &&
    920 	    !(job->flags & JOB_TRACED)) {
    921 		JobPrintln(job, "set -x");
    922 		job->flags |= JOB_TRACED;
    923 	}
    924 
    925 	JobPrintf(job, cmdTemplate, cmd);
    926 	free(cmdStart);
    927 	free(escCmd);
    928 	if (errOff) {
    929 		/*
    930 		 * If echoing is already off, there's no point in issuing the
    931 		 * echoOff command. Otherwise we issue it and pretend it was on
    932 		 * for the whole command...
    933 		 */
    934 		if (!shutUp && !(job->flags & JOB_SILENT) &&
    935 		    commandShell->hasEchoCtl) {
    936 			JobPrintln(job, commandShell->echoOff);
    937 			shutUp = TRUE;
    938 		}
    939 		JobPrintln(job, commandShell->errOnOrEcho);
    940 	}
    941 	if (shutUp && commandShell->hasEchoCtl)
    942 		JobPrintln(job, commandShell->echoOn);
    943 }
    944 
    945 /*
    946  * Print all commands to the shell file that is later executed.
    947  *
    948  * The special command "..." stops printing and saves the remaining commands
    949  * to be executed later.
    950  */
    951 static void
    952 JobPrintCommands(Job *job)
    953 {
    954 	StringListNode *ln;
    955 
    956 	for (ln = job->node->commands.first; ln != NULL; ln = ln->next) {
    957 		const char *cmd = ln->datum;
    958 
    959 		if (strcmp(cmd, "...") == 0) {
    960 			job->node->type |= OP_SAVE_CMDS;
    961 			job->tailCmds = ln->next;
    962 			break;
    963 		}
    964 
    965 		JobPrintCommand(job, ln->datum);
    966 	}
    967 }
    968 
    969 /* Save the delayed commands, to be executed when everything else is done. */
    970 static void
    971 JobSaveCommands(Job *job)
    972 {
    973 	StringListNode *ln;
    974 
    975 	for (ln = job->tailCmds; ln != NULL; ln = ln->next) {
    976 		const char *cmd = ln->datum;
    977 		char *expanded_cmd;
    978 		/* XXX: This Var_Subst is only intended to expand the dynamic
    979 		 * variables such as .TARGET, .IMPSRC.  It is not intended to
    980 		 * expand the other variables as well; see deptgt-end.mk. */
    981 		(void)Var_Subst(cmd, job->node, VARE_WANTRES, &expanded_cmd);
    982 		/* TODO: handle errors */
    983 		Lst_Append(&Targ_GetEndNode()->commands, expanded_cmd);
    984 	}
    985 }
    986 
    987 
    988 /* Called to close both input and output pipes when a job is finished. */
    989 static void
    990 JobClosePipes(Job *job)
    991 {
    992 	clearfd(job);
    993 	(void)close(job->outPipe);
    994 	job->outPipe = -1;
    995 
    996 	JobDoOutput(job, TRUE);
    997 	(void)close(job->inPipe);
    998 	job->inPipe = -1;
    999 }
   1000 
   1001 /*
   1002  * Do final processing for the given job including updating parent nodes and
   1003  * starting new jobs as available/necessary.
   1004  *
   1005  * Deferred commands for the job are placed on the .END node.
   1006  *
   1007  * If there was a serious error (job_errors != 0; not an ignored one), no more
   1008  * jobs will be started.
   1009  *
   1010  * Input:
   1011  *	job		job to finish
   1012  *	status		sub-why job went away
   1013  */
   1014 static void
   1015 JobFinish(Job *job, int status)
   1016 {
   1017 	Boolean done, return_job_token;
   1018 
   1019 	DEBUG3(JOB, "JobFinish: %d [%s], status %d\n",
   1020 	    job->pid, job->node->name, status);
   1021 
   1022 	if ((WIFEXITED(status) &&
   1023 	     ((WEXITSTATUS(status) != 0 && !(job->flags & JOB_IGNERR)))) ||
   1024 	    WIFSIGNALED(status)) {
   1025 		/*
   1026 		 * If it exited non-zero and either we're doing things our
   1027 		 * way or we're not ignoring errors, the job is finished.
   1028 		 * Similarly, if the shell died because of a signal
   1029 		 * the job is also finished. In these
   1030 		 * cases, finish out the job's output before printing the exit
   1031 		 * status...
   1032 		 */
   1033 		JobClosePipes(job);
   1034 		if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
   1035 			(void)fclose(job->cmdFILE);
   1036 			job->cmdFILE = NULL;
   1037 		}
   1038 		done = TRUE;
   1039 	} else if (WIFEXITED(status)) {
   1040 		/*
   1041 		 * Deal with ignored errors in -B mode. We need to print a
   1042 		 * message telling of the ignored error as well as to run
   1043 		 * the next command.
   1044 		 */
   1045 		done = WEXITSTATUS(status) != 0;
   1046 		JobClosePipes(job);
   1047 	} else {
   1048 		/*
   1049 		 * No need to close things down or anything.
   1050 		 */
   1051 		done = FALSE;
   1052 	}
   1053 
   1054 	if (done) {
   1055 		if (WIFEXITED(status)) {
   1056 			DEBUG2(JOB, "Process %d [%s] exited.\n",
   1057 			    job->pid, job->node->name);
   1058 			if (WEXITSTATUS(status) != 0) {
   1059 				SwitchOutputTo(job->node);
   1060 #ifdef USE_META
   1061 				if (useMeta) {
   1062 					meta_job_error(job, job->node,
   1063 					    job->flags, WEXITSTATUS(status));
   1064 				}
   1065 #endif
   1066 				if (!shouldDieQuietly(job->node, -1))
   1067 					(void)printf(
   1068 					    "*** [%s] Error code %d%s\n",
   1069 					    job->node->name,
   1070 					    WEXITSTATUS(status),
   1071 					    (job->flags & JOB_IGNERR)
   1072 						? " (ignored)" : "");
   1073 				if (job->flags & JOB_IGNERR) {
   1074 					status = 0;
   1075 				} else {
   1076 					if (deleteOnError) {
   1077 						JobDeleteTarget(job->node);
   1078 					}
   1079 					PrintOnError(job->node, NULL);
   1080 				}
   1081 			} else if (DEBUG(JOB)) {
   1082 				SwitchOutputTo(job->node);
   1083 				(void)printf(
   1084 				    "*** [%s] Completed successfully\n",
   1085 				    job->node->name);
   1086 			}
   1087 		} else {
   1088 			SwitchOutputTo(job->node);
   1089 			(void)printf("*** [%s] Signal %d\n",
   1090 			    job->node->name, WTERMSIG(status));
   1091 			if (deleteOnError) {
   1092 				JobDeleteTarget(job->node);
   1093 			}
   1094 		}
   1095 		(void)fflush(stdout);
   1096 	}
   1097 
   1098 #ifdef USE_META
   1099 	if (useMeta) {
   1100 		int meta_status = meta_job_finish(job);
   1101 		if (meta_status != 0 && status == 0)
   1102 			status = meta_status;
   1103 	}
   1104 #endif
   1105 
   1106 	return_job_token = FALSE;
   1107 
   1108 	Trace_Log(JOBEND, job);
   1109 	if (!(job->flags & JOB_SPECIAL)) {
   1110 		if (status != 0 ||
   1111 		    (aborting == ABORT_ERROR) || aborting == ABORT_INTERRUPT)
   1112 			return_job_token = TRUE;
   1113 	}
   1114 
   1115 	if (aborting != ABORT_ERROR && aborting != ABORT_INTERRUPT &&
   1116 	    (status == 0)) {
   1117 		/*
   1118 		 * As long as we aren't aborting and the job didn't return a
   1119 		 * non-zero status that we shouldn't ignore, we call
   1120 		 * Make_Update to update the parents.
   1121 		 */
   1122 		JobSaveCommands(job);
   1123 		job->node->made = MADE;
   1124 		if (!(job->flags & JOB_SPECIAL))
   1125 			return_job_token = TRUE;
   1126 		Make_Update(job->node);
   1127 		job->status = JOB_ST_FREE;
   1128 	} else if (status != 0) {
   1129 		job_errors++;
   1130 		job->status = JOB_ST_FREE;
   1131 	}
   1132 
   1133 	if (job_errors > 0 && !opts.keepgoing && aborting != ABORT_INTERRUPT) {
   1134 		/* Prevent more jobs from getting started. */
   1135 		aborting = ABORT_ERROR;
   1136 	}
   1137 
   1138 	if (return_job_token)
   1139 		Job_TokenReturn();
   1140 
   1141 	if (aborting == ABORT_ERROR && jobTokensRunning == 0)
   1142 		Finish(job_errors);
   1143 }
   1144 
   1145 static void
   1146 TouchRegular(GNode *gn)
   1147 {
   1148 	const char *file = GNode_Path(gn);
   1149 	struct utimbuf times = { now, now };
   1150 	int fd;
   1151 	char c;
   1152 
   1153 	if (utime(file, &times) >= 0)
   1154 		return;
   1155 
   1156 	fd = open(file, O_RDWR | O_CREAT, 0666);
   1157 	if (fd < 0) {
   1158 		(void)fprintf(stderr, "*** couldn't touch %s: %s\n",
   1159 		    file, strerror(errno));
   1160 		(void)fflush(stderr);
   1161 		return;		/* XXX: What about propagating the error? */
   1162 	}
   1163 
   1164 	/* Last resort: update the file's time stamps in the traditional way.
   1165 	 * XXX: This doesn't work for empty files, which are sometimes used
   1166 	 * as marker files. */
   1167 	if (read(fd, &c, 1) == 1) {
   1168 		(void)lseek(fd, 0, SEEK_SET);
   1169 		while (write(fd, &c, 1) == -1 && errno == EAGAIN)
   1170 			continue;
   1171 	}
   1172 	(void)close(fd);	/* XXX: What about propagating the error? */
   1173 }
   1174 
   1175 /* Touch the given target. Called by JobStart when the -t flag was given.
   1176  *
   1177  * The modification date of the file is changed.
   1178  * If the file did not exist, it is created. */
   1179 void
   1180 Job_Touch(GNode *gn, Boolean silent)
   1181 {
   1182 	if (gn->type &
   1183 	    (OP_JOIN | OP_USE | OP_USEBEFORE | OP_EXEC | OP_OPTIONAL |
   1184 	     OP_SPECIAL | OP_PHONY)) {
   1185 		/*
   1186 		 * These are "virtual" targets and should not really be
   1187 		 * created.
   1188 		 */
   1189 		return;
   1190 	}
   1191 
   1192 	if (!silent || !GNode_ShouldExecute(gn)) {
   1193 		(void)fprintf(stdout, "touch %s\n", gn->name);
   1194 		(void)fflush(stdout);
   1195 	}
   1196 
   1197 	if (!GNode_ShouldExecute(gn))
   1198 		return;
   1199 
   1200 	if (gn->type & OP_ARCHV) {
   1201 		Arch_Touch(gn);
   1202 		return;
   1203 	}
   1204 
   1205 	if (gn->type & OP_LIB) {
   1206 		Arch_TouchLib(gn);
   1207 		return;
   1208 	}
   1209 
   1210 	TouchRegular(gn);
   1211 }
   1212 
   1213 /* Make sure the given node has all the commands it needs.
   1214  *
   1215  * The node will have commands from the .DEFAULT rule added to it if it
   1216  * needs them.
   1217  *
   1218  * Input:
   1219  *	gn		The target whose commands need verifying
   1220  *	abortProc	Function to abort with message
   1221  *
   1222  * Results:
   1223  *	TRUE if the commands list is/was ok.
   1224  */
   1225 Boolean
   1226 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
   1227 {
   1228 	if (GNode_IsTarget(gn))
   1229 		return TRUE;
   1230 	if (!Lst_IsEmpty(&gn->commands))
   1231 		return TRUE;
   1232 	if ((gn->type & OP_LIB) && !Lst_IsEmpty(&gn->children))
   1233 		return TRUE;
   1234 
   1235 	/*
   1236 	 * No commands. Look for .DEFAULT rule from which we might infer
   1237 	 * commands.
   1238 	 */
   1239 	if (defaultNode != NULL && !Lst_IsEmpty(&defaultNode->commands) &&
   1240 	    !(gn->type & OP_SPECIAL)) {
   1241 		/*
   1242 		 * The traditional Make only looks for a .DEFAULT if the node
   1243 		 * was never the target of an operator, so that's what we do
   1244 		 * too.
   1245 		 *
   1246 		 * The .DEFAULT node acts like a transformation rule, in that
   1247 		 * gn also inherits any attributes or sources attached to
   1248 		 * .DEFAULT itself.
   1249 		 */
   1250 		Make_HandleUse(defaultNode, gn);
   1251 		Var_Set(IMPSRC, GNode_VarTarget(gn), gn);
   1252 		return TRUE;
   1253 	}
   1254 
   1255 	Dir_UpdateMTime(gn, FALSE);
   1256 	if (gn->mtime != 0 || (gn->type & OP_SPECIAL))
   1257 		return TRUE;
   1258 
   1259 	/*
   1260 	 * The node wasn't the target of an operator.  We have no .DEFAULT
   1261 	 * rule to go on and the target doesn't already exist. There's
   1262 	 * nothing more we can do for this branch. If the -k flag wasn't
   1263 	 * given, we stop in our tracks, otherwise we just don't update
   1264 	 * this node's parents so they never get examined.
   1265 	 */
   1266 
   1267 	if (gn->flags & FROM_DEPEND) {
   1268 		if (!Job_RunTarget(".STALE", gn->fname))
   1269 			fprintf(stdout,
   1270 			    "%s: %s, %d: ignoring stale %s for %s\n",
   1271 			    progname, gn->fname, gn->lineno, makeDependfile,
   1272 			    gn->name);
   1273 		return TRUE;
   1274 	}
   1275 
   1276 	if (gn->type & OP_OPTIONAL) {
   1277 		(void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
   1278 		    progname, gn->name, "ignored");
   1279 		(void)fflush(stdout);
   1280 		return TRUE;
   1281 	}
   1282 
   1283 	if (opts.keepgoing) {
   1284 		(void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
   1285 		    progname, gn->name, "continuing");
   1286 		(void)fflush(stdout);
   1287 		return FALSE;
   1288 	}
   1289 
   1290 	abortProc("%s: don't know how to make %s. Stop", progname, gn->name);
   1291 	return FALSE;
   1292 }
   1293 
   1294 /* Execute the shell for the given job.
   1295  *
   1296  * See Job_CatchOutput for handling the output of the shell. */
   1297 static void
   1298 JobExec(Job *job, char **argv)
   1299 {
   1300 	int cpid;		/* ID of new child */
   1301 	sigset_t mask;
   1302 
   1303 	job->flags &= ~JOB_TRACED;
   1304 
   1305 	if (DEBUG(JOB)) {
   1306 		int i;
   1307 
   1308 		debug_printf("Running %s\n", job->node->name);
   1309 		debug_printf("\tCommand: ");
   1310 		for (i = 0; argv[i] != NULL; i++) {
   1311 			debug_printf("%s ", argv[i]);
   1312 		}
   1313 		debug_printf("\n");
   1314 	}
   1315 
   1316 	/*
   1317 	 * Some jobs produce no output and it's disconcerting to have
   1318 	 * no feedback of their running (since they produce no output, the
   1319 	 * banner with their name in it never appears). This is an attempt to
   1320 	 * provide that feedback, even if nothing follows it.
   1321 	 */
   1322 	if (!(job->flags & JOB_SILENT))
   1323 		SwitchOutputTo(job->node);
   1324 
   1325 	/* No interruptions until this job is on the `jobs' list */
   1326 	JobSigLock(&mask);
   1327 
   1328 	/* Pre-emptively mark job running, pid still zero though */
   1329 	job->status = JOB_ST_RUNNING;
   1330 
   1331 	cpid = vFork();
   1332 	if (cpid == -1)
   1333 		Punt("Cannot vfork: %s", strerror(errno));
   1334 
   1335 	if (cpid == 0) {
   1336 		/* Child */
   1337 		sigset_t tmask;
   1338 
   1339 #ifdef USE_META
   1340 		if (useMeta) {
   1341 			meta_job_child(job);
   1342 		}
   1343 #endif
   1344 		/*
   1345 		 * Reset all signal handlers; this is necessary because we
   1346 		 * also need to unblock signals before we exec(2).
   1347 		 */
   1348 		JobSigReset();
   1349 
   1350 		/* Now unblock signals */
   1351 		sigemptyset(&tmask);
   1352 		JobSigUnlock(&tmask);
   1353 
   1354 		/*
   1355 		 * Must duplicate the input stream down to the child's input
   1356 		 * and reset it to the beginning (again). Since the stream
   1357 		 * was marked close-on-exec, we must clear that bit in the
   1358 		 * new input.
   1359 		 */
   1360 		if (dup2(fileno(job->cmdFILE), 0) == -1)
   1361 			execDie("dup2", "job->cmdFILE");
   1362 		if (fcntl(0, F_SETFD, 0) == -1)
   1363 			execDie("fcntl clear close-on-exec", "stdin");
   1364 		if (lseek(0, 0, SEEK_SET) == -1)
   1365 			execDie("lseek to 0", "stdin");
   1366 
   1367 		if (job->node->type & (OP_MAKE | OP_SUBMAKE)) {
   1368 			/*
   1369 			 * Pass job token pipe to submakes.
   1370 			 */
   1371 			if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1)
   1372 				execDie("clear close-on-exec",
   1373 				    "tokenWaitJob.inPipe");
   1374 			if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1)
   1375 				execDie("clear close-on-exec",
   1376 				    "tokenWaitJob.outPipe");
   1377 		}
   1378 
   1379 		/*
   1380 		 * Set up the child's output to be routed through the pipe
   1381 		 * we've created for it.
   1382 		 */
   1383 		if (dup2(job->outPipe, 1) == -1)
   1384 			execDie("dup2", "job->outPipe");
   1385 
   1386 		/*
   1387 		 * The output channels are marked close on exec. This bit
   1388 		 * was duplicated by the dup2(on some systems), so we have
   1389 		 * to clear it before routing the shell's error output to
   1390 		 * the same place as its standard output.
   1391 		 */
   1392 		if (fcntl(1, F_SETFD, 0) == -1)
   1393 			execDie("clear close-on-exec", "stdout");
   1394 		if (dup2(1, 2) == -1)
   1395 			execDie("dup2", "1, 2");
   1396 
   1397 		/*
   1398 		 * We want to switch the child into a different process
   1399 		 * family so we can kill it and all its descendants in
   1400 		 * one fell swoop, by killing its process family, but not
   1401 		 * commit suicide.
   1402 		 */
   1403 #if defined(MAKE_NATIVE) || defined(HAVE_SETPGID)
   1404 #  if defined(SYSV)
   1405 		/* XXX: dsl - I'm sure this should be setpgrp()... */
   1406 		(void)setsid();
   1407 #  else
   1408 		(void)setpgid(0, getpid());
   1409 #  endif
   1410 #endif
   1411 
   1412 		Var_ExportVars();
   1413 
   1414 		(void)execv(shellPath, argv);
   1415 		execDie("exec", shellPath);
   1416 	}
   1417 
   1418 	/* Parent, continuing after the child exec */
   1419 	job->pid = cpid;
   1420 
   1421 	Trace_Log(JOBSTART, job);
   1422 
   1423 #ifdef USE_META
   1424 	if (useMeta) {
   1425 		meta_job_parent(job, cpid);
   1426 	}
   1427 #endif
   1428 
   1429 	/*
   1430 	 * Set the current position in the buffer to the beginning
   1431 	 * and mark another stream to watch in the outputs mask
   1432 	 */
   1433 	job->curPos = 0;
   1434 
   1435 	watchfd(job);
   1436 
   1437 	if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
   1438 		(void)fclose(job->cmdFILE);
   1439 		job->cmdFILE = NULL;
   1440 	}
   1441 
   1442 	/*
   1443 	 * Now the job is actually running, add it to the table.
   1444 	 */
   1445 	if (DEBUG(JOB)) {
   1446 		debug_printf("JobExec(%s): pid %d added to jobs table\n",
   1447 		    job->node->name, job->pid);
   1448 		job_table_dump("job started");
   1449 	}
   1450 	JobSigUnlock(&mask);
   1451 }
   1452 
   1453 /* Create the argv needed to execute the shell for a given job. */
   1454 static void
   1455 JobMakeArgv(Job *job, char **argv)
   1456 {
   1457 	int argc;
   1458 	static char args[10];	/* For merged arguments */
   1459 
   1460 	argv[0] = UNCONST(shellName);
   1461 	argc = 1;
   1462 
   1463 	if ((commandShell->exit && commandShell->exit[0] != '-') ||
   1464 	    (commandShell->echo && commandShell->echo[0] != '-')) {
   1465 		/*
   1466 		 * At least one of the flags doesn't have a minus before it,
   1467 		 * so merge them together. Have to do this because the Bourne
   1468 		 * shell thinks its second argument is a file to source.
   1469 		 * Grrrr. Note the ten-character limitation on the combined
   1470 		 * arguments.
   1471 		 *
   1472 		 * TODO: Research until when the above comments were
   1473 		 * practically relevant.
   1474 		 */
   1475 		(void)snprintf(args, sizeof args, "-%s%s",
   1476 		    ((job->flags & JOB_IGNERR) ? "" :
   1477 			(commandShell->exit ? commandShell->exit : "")),
   1478 		    ((job->flags & JOB_SILENT) ? "" :
   1479 			(commandShell->echo ? commandShell->echo : "")));
   1480 
   1481 		if (args[1]) {
   1482 			argv[argc] = args;
   1483 			argc++;
   1484 		}
   1485 	} else {
   1486 		if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
   1487 			argv[argc] = UNCONST(commandShell->exit);
   1488 			argc++;
   1489 		}
   1490 		if (!(job->flags & JOB_SILENT) && commandShell->echo) {
   1491 			argv[argc] = UNCONST(commandShell->echo);
   1492 			argc++;
   1493 		}
   1494 	}
   1495 	argv[argc] = NULL;
   1496 }
   1497 
   1498 /*
   1499  * Start a target-creation process going for the target described by the
   1500  * graph node gn.
   1501  *
   1502  * Input:
   1503  *	gn		target to create
   1504  *	flags		flags for the job to override normal ones.
   1505  *	previous	The previous Job structure for this node, if any.
   1506  *
   1507  * Results:
   1508  *	JOB_ERROR if there was an error in the commands, JOB_FINISHED
   1509  *	if there isn't actually anything left to do for the job and
   1510  *	JOB_RUNNING if the job has been started.
   1511  *
   1512  * Side Effects:
   1513  *	A new Job node is created and added to the list of running
   1514  *	jobs. PMake is forked and a child shell created.
   1515  *
   1516  * NB: The return value is ignored by everyone.
   1517  */
   1518 static JobStartResult
   1519 JobStart(GNode *gn, JobFlags flags)
   1520 {
   1521 	Job *job;		/* new job descriptor */
   1522 	char *argv[10];		/* Argument vector to shell */
   1523 	Boolean cmdsOK;		/* true if the nodes commands were all right */
   1524 	Boolean noExec;		/* Set true if we decide not to run the job */
   1525 	int tfd;		/* File descriptor to the temp file */
   1526 
   1527 	for (job = job_table; job < job_table_end; job++) {
   1528 		if (job->status == JOB_ST_FREE)
   1529 			break;
   1530 	}
   1531 	if (job >= job_table_end)
   1532 		Punt("JobStart no job slots vacant");
   1533 
   1534 	memset(job, 0, sizeof *job);
   1535 	job->node = gn;
   1536 	job->tailCmds = NULL;
   1537 	job->status = JOB_ST_SET_UP;
   1538 
   1539 	if (gn->type & OP_SPECIAL)
   1540 		flags |= JOB_SPECIAL;
   1541 	if (Targ_Ignore(gn))
   1542 		flags |= JOB_IGNERR;
   1543 	if (Targ_Silent(gn))
   1544 		flags |= JOB_SILENT;
   1545 	job->flags = flags;
   1546 
   1547 	/*
   1548 	 * Check the commands now so any attributes from .DEFAULT have a
   1549 	 * chance to migrate to the node.
   1550 	 */
   1551 	cmdsOK = Job_CheckCommands(gn, Error);
   1552 
   1553 	job->inPollfd = NULL;
   1554 	/*
   1555 	 * If the -n flag wasn't given, we open up OUR (not the child's)
   1556 	 * temporary file to stuff commands in it. The thing is rd/wr so
   1557 	 * we don't need to reopen it to feed it to the shell. If the -n
   1558 	 * flag *was* given, we just set the file to be stdout. Cute, huh?
   1559 	 */
   1560 	if (((gn->type & OP_MAKE) && !opts.noRecursiveExecute) ||
   1561 	    (!opts.noExecute && !opts.touchFlag)) {
   1562 		/*
   1563 		 * tfile is the name of a file into which all shell commands
   1564 		 * are put. It is removed before the child shell is executed,
   1565 		 * unless DEBUG(SCRIPT) is set.
   1566 		 */
   1567 		char *tfile;
   1568 		sigset_t mask;
   1569 		/*
   1570 		 * We're serious here, but if the commands were bogus, we're
   1571 		 * also dead...
   1572 		 */
   1573 		if (!cmdsOK) {
   1574 			PrintOnError(gn, NULL); /* provide some clue */
   1575 			DieHorribly();
   1576 		}
   1577 
   1578 		JobSigLock(&mask);
   1579 		tfd = mkTempFile(TMPPAT, &tfile);
   1580 		if (!DEBUG(SCRIPT))
   1581 			(void)eunlink(tfile);
   1582 		JobSigUnlock(&mask);
   1583 
   1584 		job->cmdFILE = fdopen(tfd, "w+");
   1585 		if (job->cmdFILE == NULL)
   1586 			Punt("Could not fdopen %s", tfile);
   1587 
   1588 		(void)fcntl(fileno(job->cmdFILE), F_SETFD, FD_CLOEXEC);
   1589 		/*
   1590 		 * Send the commands to the command file, flush all its
   1591 		 * buffers then rewind and remove the thing.
   1592 		 */
   1593 		noExec = FALSE;
   1594 
   1595 #ifdef USE_META
   1596 		if (useMeta) {
   1597 			meta_job_start(job, gn);
   1598 			if (Targ_Silent(gn)) /* might have changed */
   1599 				job->flags |= JOB_SILENT;
   1600 		}
   1601 #endif
   1602 		/* We can do all the commands at once. hooray for sanity */
   1603 		numCommands = 0;
   1604 		JobPrintCommands(job);
   1605 
   1606 		/*
   1607 		 * If we didn't print out any commands to the shell script,
   1608 		 * there's not much point in executing the shell, is there?
   1609 		 */
   1610 		if (numCommands == 0) {
   1611 			noExec = TRUE;
   1612 		}
   1613 
   1614 		free(tfile);
   1615 	} else if (!GNode_ShouldExecute(gn)) {
   1616 		/*
   1617 		 * Not executing anything -- just print all the commands to
   1618 		 * stdout in one fell swoop. This will still set up
   1619 		 * job->tailCmds correctly.
   1620 		 */
   1621 		SwitchOutputTo(gn);
   1622 		job->cmdFILE = stdout;
   1623 		/*
   1624 		 * Only print the commands if they're ok, but don't die if
   1625 		 * they're not -- just let the user know they're bad and
   1626 		 * keep going. It doesn't do any harm in this case and may
   1627 		 * do some good.
   1628 		 */
   1629 		if (cmdsOK)
   1630 			JobPrintCommands(job);
   1631 		/* Don't execute the shell, thank you. */
   1632 		noExec = TRUE;
   1633 	} else {
   1634 		/*
   1635 		 * Just touch the target and note that no shell should be
   1636 		 * executed. Set cmdFILE to stdout to make life easier.
   1637 		 * Check the commands, too, but don't die if they're no
   1638 		 * good -- it does no harm to keep working up the graph.
   1639 		 */
   1640 		job->cmdFILE = stdout;
   1641 		Job_Touch(gn, job->flags & JOB_SILENT);
   1642 		noExec = TRUE;
   1643 	}
   1644 	/* Just in case it isn't already... */
   1645 	(void)fflush(job->cmdFILE);
   1646 
   1647 	/* If we're not supposed to execute a shell, don't. */
   1648 	if (noExec) {
   1649 		if (!(job->flags & JOB_SPECIAL))
   1650 			Job_TokenReturn();
   1651 		/* Unlink and close the command file if we opened one */
   1652 		if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
   1653 			(void)fclose(job->cmdFILE);
   1654 			job->cmdFILE = NULL;
   1655 		}
   1656 
   1657 		/*
   1658 		 * We only want to work our way up the graph if we aren't
   1659 		 * here because the commands for the job were no good.
   1660 		 */
   1661 		if (cmdsOK && aborting == ABORT_NONE) {
   1662 			JobSaveCommands(job);
   1663 			job->node->made = MADE;
   1664 			Make_Update(job->node);
   1665 		}
   1666 		job->status = JOB_ST_FREE;
   1667 		return cmdsOK ? JOB_FINISHED : JOB_ERROR;
   1668 	}
   1669 
   1670 	/*
   1671 	 * Set up the control arguments to the shell. This is based on the
   1672 	 * flags set earlier for this job.
   1673 	 */
   1674 	JobMakeArgv(job, argv);
   1675 
   1676 	/* Create the pipe by which we'll get the shell's output. */
   1677 	JobCreatePipe(job, 3);
   1678 
   1679 	JobExec(job, argv);
   1680 	return JOB_RUNNING;
   1681 }
   1682 
   1683 /*
   1684  * Print the output of the shell command, skipping the noPrint command of
   1685  * the shell, if any.
   1686  */
   1687 static char *
   1688 JobOutput(char *cp, char *endp)
   1689 {
   1690 	char *ecp;
   1691 
   1692 	if (commandShell->noPrint == NULL || commandShell->noPrint[0] == '\0')
   1693 		return cp;
   1694 
   1695 	while ((ecp = strstr(cp, commandShell->noPrint)) != NULL) {
   1696 		if (ecp != cp) {
   1697 			*ecp = '\0';
   1698 			/*
   1699 			 * The only way there wouldn't be a newline after
   1700 			 * this line is if it were the last in the buffer.
   1701 			 * however, since the non-printable comes after it,
   1702 			 * there must be a newline, so we don't print one.
   1703 			 */
   1704 			(void)fprintf(stdout, "%s", cp);
   1705 			(void)fflush(stdout);
   1706 		}
   1707 		cp = ecp + commandShell->noPrintLen;
   1708 		if (cp != endp) {
   1709 			/*
   1710 			 * Still more to print, look again after skipping
   1711 			 * the whitespace following the non-printable
   1712 			 * command.
   1713 			 */
   1714 			cp++;
   1715 			pp_skip_whitespace(&cp);
   1716 		} else {
   1717 			return cp;
   1718 		}
   1719 	}
   1720 	return cp;
   1721 }
   1722 
   1723 /*
   1724  * This function is called whenever there is something to read on the pipe.
   1725  * We collect more output from the given job and store it in the job's
   1726  * outBuf. If this makes up a line, we print it tagged by the job's
   1727  * identifier, as necessary.
   1728  *
   1729  * In the output of the shell, the 'noPrint' lines are removed. If the
   1730  * command is not alone on the line (the character after it is not \0 or
   1731  * \n), we do print whatever follows it.
   1732  *
   1733  * Input:
   1734  *	job		the job whose output needs printing
   1735  *	finish		TRUE if this is the last time we'll be called
   1736  *			for this job
   1737  */
   1738 static void
   1739 JobDoOutput(Job *job, Boolean finish)
   1740 {
   1741 	Boolean gotNL;		/* true if got a newline */
   1742 	Boolean fbuf;		/* true if our buffer filled up */
   1743 	size_t nr;		/* number of bytes read */
   1744 	size_t i;		/* auxiliary index into outBuf */
   1745 	size_t max;		/* limit for i (end of current data) */
   1746 	ssize_t nRead;		/* (Temporary) number of bytes read */
   1747 
   1748 	/* Read as many bytes as will fit in the buffer. */
   1749 again:
   1750 	gotNL = FALSE;
   1751 	fbuf = FALSE;
   1752 
   1753 	nRead = read(job->inPipe, &job->outBuf[job->curPos],
   1754 	    JOB_BUFSIZE - job->curPos);
   1755 	if (nRead < 0) {
   1756 		if (errno == EAGAIN)
   1757 			return;
   1758 		if (DEBUG(JOB)) {
   1759 			perror("JobDoOutput(piperead)");
   1760 		}
   1761 		nr = 0;
   1762 	} else {
   1763 		nr = (size_t)nRead;
   1764 	}
   1765 
   1766 	/*
   1767 	 * If we hit the end-of-file (the job is dead), we must flush its
   1768 	 * remaining output, so pretend we read a newline if there's any
   1769 	 * output remaining in the buffer.
   1770 	 * Also clear the 'finish' flag so we stop looping.
   1771 	 */
   1772 	if (nr == 0 && job->curPos != 0) {
   1773 		job->outBuf[job->curPos] = '\n';
   1774 		nr = 1;
   1775 		finish = FALSE;
   1776 	} else if (nr == 0) {
   1777 		finish = FALSE;
   1778 	}
   1779 
   1780 	/*
   1781 	 * Look for the last newline in the bytes we just got. If there is
   1782 	 * one, break out of the loop with 'i' as its index and gotNL set
   1783 	 * TRUE.
   1784 	 */
   1785 	max = job->curPos + nr;
   1786 	for (i = job->curPos + nr - 1;
   1787 	     i >= job->curPos && i != (size_t)-1; i--) {
   1788 		if (job->outBuf[i] == '\n') {
   1789 			gotNL = TRUE;
   1790 			break;
   1791 		} else if (job->outBuf[i] == '\0') {
   1792 			/*
   1793 			 * Why?
   1794 			 */
   1795 			job->outBuf[i] = ' ';
   1796 		}
   1797 	}
   1798 
   1799 	if (!gotNL) {
   1800 		job->curPos += nr;
   1801 		if (job->curPos == JOB_BUFSIZE) {
   1802 			/*
   1803 			 * If we've run out of buffer space, we have no choice
   1804 			 * but to print the stuff. sigh.
   1805 			 */
   1806 			fbuf = TRUE;
   1807 			i = job->curPos;
   1808 		}
   1809 	}
   1810 	if (gotNL || fbuf) {
   1811 		/*
   1812 		 * Need to send the output to the screen. Null terminate it
   1813 		 * first, overwriting the newline character if there was one.
   1814 		 * So long as the line isn't one we should filter (according
   1815 		 * to the shell description), we print the line, preceded
   1816 		 * by a target banner if this target isn't the same as the
   1817 		 * one for which we last printed something.
   1818 		 * The rest of the data in the buffer are then shifted down
   1819 		 * to the start of the buffer and curPos is set accordingly.
   1820 		 */
   1821 		job->outBuf[i] = '\0';
   1822 		if (i >= job->curPos) {
   1823 			char *cp;
   1824 
   1825 			cp = JobOutput(job->outBuf, &job->outBuf[i]);
   1826 
   1827 			/*
   1828 			 * There's still more in that thar buffer. This time,
   1829 			 * though, we know there's no newline at the end, so
   1830 			 * we add one of our own free will.
   1831 			 */
   1832 			if (*cp != '\0') {
   1833 				if (!opts.beSilent)
   1834 					SwitchOutputTo(job->node);
   1835 #ifdef USE_META
   1836 				if (useMeta) {
   1837 					meta_job_output(job, cp,
   1838 					    gotNL ? "\n" : "");
   1839 				}
   1840 #endif
   1841 				(void)fprintf(stdout, "%s%s", cp,
   1842 				    gotNL ? "\n" : "");
   1843 				(void)fflush(stdout);
   1844 			}
   1845 		}
   1846 		/*
   1847 		 * max is the last offset still in the buffer. Move any
   1848 		 * remaining characters to the start of the buffer and
   1849 		 * update the end marker curPos.
   1850 		 */
   1851 		if (i < max) {
   1852 			(void)memmove(job->outBuf, &job->outBuf[i + 1],
   1853 			    max - (i + 1));
   1854 			job->curPos = max - (i + 1);
   1855 		} else {
   1856 			assert(i == max);
   1857 			job->curPos = 0;
   1858 		}
   1859 	}
   1860 	if (finish) {
   1861 		/*
   1862 		 * If the finish flag is true, we must loop until we hit
   1863 		 * end-of-file on the pipe. This is guaranteed to happen
   1864 		 * eventually since the other end of the pipe is now closed
   1865 		 * (we closed it explicitly and the child has exited). When
   1866 		 * we do get an EOF, finish will be set FALSE and we'll fall
   1867 		 * through and out.
   1868 		 */
   1869 		goto again;
   1870 	}
   1871 }
   1872 
   1873 static void
   1874 JobRun(GNode *targ)
   1875 {
   1876 #if 0
   1877 	/*
   1878 	 * Unfortunately it is too complicated to run .BEGIN, .END, and
   1879 	 * .INTERRUPT job in the parallel job module.  As of 2020-09-25,
   1880 	 * unit-tests/deptgt-end-jobs.mk hangs in an endless loop.
   1881 	 *
   1882 	 * Running these jobs in compat mode also guarantees that these
   1883 	 * jobs do not overlap with other unrelated jobs.
   1884 	 */
   1885 	List *lst = Lst_New();
   1886 	Lst_Append(lst, targ);
   1887 	(void)Make_Run(lst);
   1888 	Lst_Destroy(lst, NULL);
   1889 	JobStart(targ, JOB_SPECIAL);
   1890 	while (jobTokensRunning != 0) {
   1891 		Job_CatchOutput();
   1892 	}
   1893 #else
   1894 	Compat_Make(targ, targ);
   1895 	/* XXX: Replace with GNode_IsError(gn) */
   1896 	if (targ->made == ERROR) {
   1897 		PrintOnError(targ, "\n\nStop.");
   1898 		exit(1);
   1899 	}
   1900 #endif
   1901 }
   1902 
   1903 /* Handle the exit of a child. Called from Make_Make.
   1904  *
   1905  * The job descriptor is removed from the list of children.
   1906  *
   1907  * Notes:
   1908  *	We do waits, blocking or not, according to the wisdom of our
   1909  *	caller, until there are no more children to report. For each
   1910  *	job, call JobFinish to finish things off.
   1911  */
   1912 void
   1913 Job_CatchChildren(void)
   1914 {
   1915 	int pid;		/* pid of dead child */
   1916 	int status;		/* Exit/termination status */
   1917 
   1918 	/* Don't even bother if we know there's no one around. */
   1919 	if (jobTokensRunning == 0)
   1920 		return;
   1921 
   1922 	while ((pid = waitpid((pid_t)-1, &status, WNOHANG | WUNTRACED)) > 0) {
   1923 		DEBUG2(JOB, "Process %d exited/stopped status %x.\n",
   1924 		    pid, status);
   1925 		JobReapChild(pid, status, TRUE);
   1926 	}
   1927 }
   1928 
   1929 /*
   1930  * It is possible that wait[pid]() was called from elsewhere,
   1931  * this lets us reap jobs regardless.
   1932  */
   1933 void
   1934 JobReapChild(pid_t pid, int status, Boolean isJobs)
   1935 {
   1936 	Job *job;		/* job descriptor for dead child */
   1937 
   1938 	/* Don't even bother if we know there's no one around. */
   1939 	if (jobTokensRunning == 0)
   1940 		return;
   1941 
   1942 	job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
   1943 	if (job == NULL) {
   1944 		if (isJobs) {
   1945 			if (!lurking_children)
   1946 				Error("Child (%d) status %x not in table?",
   1947 				    pid, status);
   1948 		}
   1949 		return;		/* not ours */
   1950 	}
   1951 	if (WIFSTOPPED(status)) {
   1952 		DEBUG2(JOB, "Process %d (%s) stopped.\n",
   1953 		    job->pid, job->node->name);
   1954 		if (!make_suspended) {
   1955 			switch (WSTOPSIG(status)) {
   1956 			case SIGTSTP:
   1957 				(void)printf("*** [%s] Suspended\n",
   1958 				    job->node->name);
   1959 				break;
   1960 			case SIGSTOP:
   1961 				(void)printf("*** [%s] Stopped\n",
   1962 				    job->node->name);
   1963 				break;
   1964 			default:
   1965 				(void)printf("*** [%s] Stopped -- signal %d\n",
   1966 				    job->node->name, WSTOPSIG(status));
   1967 			}
   1968 			job->suspended = TRUE;
   1969 		}
   1970 		(void)fflush(stdout);
   1971 		return;
   1972 	}
   1973 
   1974 	job->status = JOB_ST_FINISHED;
   1975 	job->exit_status = status;
   1976 
   1977 	JobFinish(job, status);
   1978 }
   1979 
   1980 /* Catch the output from our children, if we're using pipes do so. Otherwise
   1981  * just block time until we get a signal(most likely a SIGCHLD) since there's
   1982  * no point in just spinning when there's nothing to do and the reaping of a
   1983  * child can wait for a while. */
   1984 void
   1985 Job_CatchOutput(void)
   1986 {
   1987 	int nready;
   1988 	Job *job;
   1989 	unsigned int i;
   1990 
   1991 	(void)fflush(stdout);
   1992 
   1993 	/* The first fd in the list is the job token pipe */
   1994 	do {
   1995 		nready = poll(fds + 1 - wantToken, nJobs - 1 + wantToken,
   1996 		    POLL_MSEC);
   1997 	} while (nready < 0 && errno == EINTR);
   1998 
   1999 	if (nready < 0)
   2000 		Punt("poll: %s", strerror(errno));
   2001 
   2002 	if (nready > 0 && readyfd(&childExitJob)) {
   2003 		char token = 0;
   2004 		ssize_t count;
   2005 		count = read(childExitJob.inPipe, &token, 1);
   2006 		switch (count) {
   2007 		case 0:
   2008 			Punt("unexpected eof on token pipe");
   2009 		case -1:
   2010 			Punt("token pipe read: %s", strerror(errno));
   2011 		case 1:
   2012 			if (token == DO_JOB_RESUME[0])
   2013 				/*
   2014 				 * Complete relay requested from our SIGCONT
   2015 				 * handler
   2016 				 */
   2017 				JobRestartJobs();
   2018 			break;
   2019 		default:
   2020 			abort();
   2021 		}
   2022 		nready--;
   2023 	}
   2024 
   2025 	Job_CatchChildren();
   2026 	if (nready == 0)
   2027 		return;
   2028 
   2029 	for (i = npseudojobs * nfds_per_job(); i < nJobs; i++) {
   2030 		if (!fds[i].revents)
   2031 			continue;
   2032 		job = allJobs[i];
   2033 		if (job->status == JOB_ST_RUNNING)
   2034 			JobDoOutput(job, FALSE);
   2035 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
   2036 		/*
   2037 		 * With meta mode, we may have activity on the job's filemon
   2038 		 * descriptor too, which at the moment is any pollfd other
   2039 		 * than job->inPollfd.
   2040 		 */
   2041 		if (useMeta && job->inPollfd != &fds[i]) {
   2042 			if (meta_job_event(job) <= 0) {
   2043 				fds[i].events = 0; /* never mind */
   2044 			}
   2045 		}
   2046 #endif
   2047 		if (--nready == 0)
   2048 			return;
   2049 	}
   2050 }
   2051 
   2052 /* Start the creation of a target. Basically a front-end for JobStart used by
   2053  * the Make module. */
   2054 void
   2055 Job_Make(GNode *gn)
   2056 {
   2057 	(void)JobStart(gn, JOB_NONE);
   2058 }
   2059 
   2060 static void
   2061 InitShellNameAndPath(void)
   2062 {
   2063 	shellName = commandShell->name;
   2064 
   2065 #ifdef DEFSHELL_CUSTOM
   2066 	if (shellName[0] == '/') {
   2067 		shellPath = shellName;
   2068 		shellName = strrchr(shellPath, '/') + 1;
   2069 		return;
   2070 	}
   2071 #endif
   2072 
   2073 	shellPath = str_concat3(_PATH_DEFSHELLDIR, "/", shellName);
   2074 }
   2075 
   2076 void
   2077 Shell_Init(void)
   2078 {
   2079 	if (shellPath == NULL)
   2080 		InitShellNameAndPath();
   2081 
   2082 	Var_SetWithFlags(".SHELL", shellPath, VAR_CMDLINE, VAR_SET_READONLY);
   2083 	if (commandShell->exit == NULL) {
   2084 		commandShell->exit = "";
   2085 	}
   2086 	if (commandShell->echo == NULL) {
   2087 		commandShell->echo = "";
   2088 	}
   2089 	if (commandShell->hasErrCtl && commandShell->exit[0] != '\0') {
   2090 		if (shellErrFlag &&
   2091 		    strcmp(commandShell->exit, &shellErrFlag[1]) != 0) {
   2092 			free(shellErrFlag);
   2093 			shellErrFlag = NULL;
   2094 		}
   2095 		if (shellErrFlag == NULL) {
   2096 			size_t n = strlen(commandShell->exit) + 2;
   2097 
   2098 			shellErrFlag = bmake_malloc(n);
   2099 			if (shellErrFlag != NULL) {
   2100 				snprintf(shellErrFlag, n, "-%s",
   2101 				    commandShell->exit);
   2102 			}
   2103 		}
   2104 	} else if (shellErrFlag != NULL) {
   2105 		free(shellErrFlag);
   2106 		shellErrFlag = NULL;
   2107 	}
   2108 }
   2109 
   2110 /*
   2111  * Return the string literal that is used in the current command shell
   2112  * to produce a newline character.
   2113  */
   2114 const char *
   2115 Shell_GetNewline(void)
   2116 {
   2117 	return commandShell->newline;
   2118 }
   2119 
   2120 void
   2121 Job_SetPrefix(void)
   2122 {
   2123 	if (targPrefix != NULL) {
   2124 		free(targPrefix);
   2125 	} else if (!Var_Exists(MAKE_JOB_PREFIX, VAR_GLOBAL)) {
   2126 		Var_Set(MAKE_JOB_PREFIX, "---", VAR_GLOBAL);
   2127 	}
   2128 
   2129 	(void)Var_Subst("${" MAKE_JOB_PREFIX "}",
   2130 	    VAR_GLOBAL, VARE_WANTRES, &targPrefix);
   2131 	/* TODO: handle errors */
   2132 }
   2133 
   2134 static void
   2135 AddSig(int sig, SignalProc handler)
   2136 {
   2137 	if (bmake_signal(sig, SIG_IGN) != SIG_IGN) {
   2138 		sigaddset(&caught_signals, sig);
   2139 		(void)bmake_signal(sig, handler);
   2140 	}
   2141 }
   2142 
   2143 /* Initialize the process module. */
   2144 void
   2145 Job_Init(void)
   2146 {
   2147 	Job_SetPrefix();
   2148 	/* Allocate space for all the job info */
   2149 	job_table = bmake_malloc((size_t)opts.maxJobs * sizeof *job_table);
   2150 	memset(job_table, 0, (size_t)opts.maxJobs * sizeof *job_table);
   2151 	job_table_end = job_table + opts.maxJobs;
   2152 	wantToken = 0;
   2153 
   2154 	aborting = ABORT_NONE;
   2155 	job_errors = 0;
   2156 
   2157 	/*
   2158 	 * There is a non-zero chance that we already have children.
   2159 	 * eg after 'make -f- <<EOF'
   2160 	 * Since their termination causes a 'Child (pid) not in table'
   2161 	 * message, Collect the status of any that are already dead, and
   2162 	 * suppress the error message if there are any undead ones.
   2163 	 */
   2164 	for (;;) {
   2165 		int rval, status;
   2166 		rval = waitpid((pid_t)-1, &status, WNOHANG);
   2167 		if (rval > 0)
   2168 			continue;
   2169 		if (rval == 0)
   2170 			lurking_children = TRUE;
   2171 		break;
   2172 	}
   2173 
   2174 	Shell_Init();
   2175 
   2176 	JobCreatePipe(&childExitJob, 3);
   2177 
   2178 	/* Preallocate enough for the maximum number of jobs.  */
   2179 	fds = bmake_malloc(sizeof *fds *
   2180 			   (npseudojobs + (size_t)opts.maxJobs) *
   2181 			   nfds_per_job());
   2182 	allJobs = bmake_malloc(sizeof *allJobs *
   2183 			       (npseudojobs + (size_t)opts.maxJobs) *
   2184 			       nfds_per_job());
   2185 
   2186 	/* These are permanent entries and take slots 0 and 1 */
   2187 	watchfd(&tokenWaitJob);
   2188 	watchfd(&childExitJob);
   2189 
   2190 	sigemptyset(&caught_signals);
   2191 	/*
   2192 	 * Install a SIGCHLD handler.
   2193 	 */
   2194 	(void)bmake_signal(SIGCHLD, JobChildSig);
   2195 	sigaddset(&caught_signals, SIGCHLD);
   2196 
   2197 	/*
   2198 	 * Catch the four signals that POSIX specifies if they aren't ignored.
   2199 	 * JobPassSig will take care of calling JobInterrupt if appropriate.
   2200 	 */
   2201 	AddSig(SIGINT, JobPassSig_int);
   2202 	AddSig(SIGHUP, JobPassSig_term);
   2203 	AddSig(SIGTERM, JobPassSig_term);
   2204 	AddSig(SIGQUIT, JobPassSig_term);
   2205 
   2206 	/*
   2207 	 * There are additional signals that need to be caught and passed if
   2208 	 * either the export system wants to be told directly of signals or if
   2209 	 * we're giving each job its own process group (since then it won't get
   2210 	 * signals from the terminal driver as we own the terminal)
   2211 	 */
   2212 	AddSig(SIGTSTP, JobPassSig_suspend);
   2213 	AddSig(SIGTTOU, JobPassSig_suspend);
   2214 	AddSig(SIGTTIN, JobPassSig_suspend);
   2215 	AddSig(SIGWINCH, JobCondPassSig);
   2216 	AddSig(SIGCONT, JobContinueSig);
   2217 
   2218 	(void)Job_RunTarget(".BEGIN", NULL);
   2219 	/* Create the .END node now, even though no code in the unit tests
   2220 	 * depends on it.  See also Targ_GetEndNode in Compat_Run. */
   2221 	(void)Targ_GetEndNode();
   2222 }
   2223 
   2224 static void
   2225 DelSig(int sig)
   2226 {
   2227 	if (sigismember(&caught_signals, sig))
   2228 		(void)bmake_signal(sig, SIG_DFL);
   2229 }
   2230 
   2231 static void JobSigReset(void)
   2232 {
   2233 	DelSig(SIGINT);
   2234 	DelSig(SIGHUP);
   2235 	DelSig(SIGQUIT);
   2236 	DelSig(SIGTERM);
   2237 	DelSig(SIGTSTP);
   2238 	DelSig(SIGTTOU);
   2239 	DelSig(SIGTTIN);
   2240 	DelSig(SIGWINCH);
   2241 	DelSig(SIGCONT);
   2242 	(void)bmake_signal(SIGCHLD, SIG_DFL);
   2243 }
   2244 
   2245 /* Find a shell in 'shells' given its name, or return NULL. */
   2246 static Shell *
   2247 FindShellByName(const char *name)
   2248 {
   2249 	Shell *sh = shells;
   2250 	const Shell *shellsEnd = sh + sizeof shells / sizeof shells[0];
   2251 
   2252 	for (sh = shells; sh < shellsEnd; sh++) {
   2253 		if (strcmp(name, sh->name) == 0)
   2254 			return sh;
   2255 	}
   2256 	return NULL;
   2257 }
   2258 
   2259 /*
   2260  * Parse a shell specification and set up commandShell, shellPath and
   2261  * shellName appropriately.
   2262  *
   2263  * Input:
   2264  *	line		The shell spec
   2265  *
   2266  * Results:
   2267  *	FALSE if the specification was incorrect.
   2268  *
   2269  * Side Effects:
   2270  *	commandShell points to a Shell structure (either predefined or
   2271  *	created from the shell spec), shellPath is the full path of the
   2272  *	shell described by commandShell, while shellName is just the
   2273  *	final component of shellPath.
   2274  *
   2275  * Notes:
   2276  *	A shell specification consists of a .SHELL target, with dependency
   2277  *	operator, followed by a series of blank-separated words. Double
   2278  *	quotes can be used to use blanks in words. A backslash escapes
   2279  *	anything (most notably a double-quote and a space) and
   2280  *	provides the functionality it does in C. Each word consists of
   2281  *	keyword and value separated by an equal sign. There should be no
   2282  *	unnecessary spaces in the word. The keywords are as follows:
   2283  *	    name	Name of shell.
   2284  *	    path	Location of shell.
   2285  *	    quiet	Command to turn off echoing.
   2286  *	    echo	Command to turn echoing on
   2287  *	    filter	Result of turning off echoing that shouldn't be
   2288  *			printed.
   2289  *	    echoFlag	Flag to turn echoing on at the start
   2290  *	    errFlag	Flag to turn error checking on at the start
   2291  *	    hasErrCtl	True if shell has error checking control
   2292  *	    newline	String literal to represent a newline char
   2293  *	    check	Command to turn on error checking if hasErrCtl
   2294  *			is TRUE or template of command to echo a command
   2295  *			for which error checking is off if hasErrCtl is
   2296  *			FALSE.
   2297  *	    ignore	Command to turn off error checking if hasErrCtl
   2298  *			is TRUE or template of command to execute a
   2299  *			command so as to ignore any errors it returns if
   2300  *			hasErrCtl is FALSE.
   2301  */
   2302 Boolean
   2303 Job_ParseShell(char *line)
   2304 {
   2305 	Words wordsList;
   2306 	char **words;
   2307 	char **argv;
   2308 	size_t argc;
   2309 	char *path;
   2310 	Shell newShell;
   2311 	Boolean fullSpec = FALSE;
   2312 	Shell *sh;
   2313 
   2314 	pp_skip_whitespace(&line);
   2315 
   2316 	free(shellArgv);
   2317 
   2318 	memset(&newShell, 0, sizeof newShell);
   2319 
   2320 	/*
   2321 	 * Parse the specification by keyword
   2322 	 */
   2323 	wordsList = Str_Words(line, TRUE);
   2324 	words = wordsList.words;
   2325 	argc = wordsList.len;
   2326 	path = wordsList.freeIt;
   2327 	if (words == NULL) {
   2328 		Error("Unterminated quoted string [%s]", line);
   2329 		return FALSE;
   2330 	}
   2331 	shellArgv = path;
   2332 
   2333 	for (path = NULL, argv = words; argc != 0; argc--, argv++) {
   2334 		char *arg = *argv;
   2335 		if (strncmp(arg, "path=", 5) == 0) {
   2336 			path = arg + 5;
   2337 		} else if (strncmp(arg, "name=", 5) == 0) {
   2338 			newShell.name = arg + 5;
   2339 		} else {
   2340 			if (strncmp(arg, "quiet=", 6) == 0) {
   2341 				newShell.echoOff = arg + 6;
   2342 			} else if (strncmp(arg, "echo=", 5) == 0) {
   2343 				newShell.echoOn = arg + 5;
   2344 			} else if (strncmp(arg, "filter=", 7) == 0) {
   2345 				newShell.noPrint = arg + 7;
   2346 				newShell.noPrintLen = strlen(newShell.noPrint);
   2347 			} else if (strncmp(arg, "echoFlag=", 9) == 0) {
   2348 				newShell.echo = arg + 9;
   2349 			} else if (strncmp(arg, "errFlag=", 8) == 0) {
   2350 				newShell.exit = arg + 8;
   2351 			} else if (strncmp(arg, "hasErrCtl=", 10) == 0) {
   2352 				char c = arg[10];
   2353 				newShell.hasErrCtl = c == 'Y' || c == 'y' ||
   2354 						     c == 'T' || c == 't';
   2355 			} else if (strncmp(arg, "newline=", 8) == 0) {
   2356 				newShell.newline = arg + 8;
   2357 			} else if (strncmp(arg, "check=", 6) == 0) {
   2358 				newShell.errOnOrEcho = arg + 6;
   2359 			} else if (strncmp(arg, "ignore=", 7) == 0) {
   2360 				newShell.errOffOrExecIgnore = arg + 7;
   2361 			} else if (strncmp(arg, "errout=", 7) == 0) {
   2362 				newShell.errExit = arg + 7;
   2363 			} else if (strncmp(arg, "comment=", 8) == 0) {
   2364 				newShell.commentChar = arg[8];
   2365 			} else {
   2366 				Parse_Error(PARSE_FATAL,
   2367 				    "Unknown keyword \"%s\"", arg);
   2368 				free(words);
   2369 				return FALSE;
   2370 			}
   2371 			fullSpec = TRUE;
   2372 		}
   2373 	}
   2374 
   2375 	if (path == NULL) {
   2376 		/*
   2377 		 * If no path was given, the user wants one of the
   2378 		 * pre-defined shells, yes? So we find the one s/he wants
   2379 		 * with the help of FindShellByName and set things up the
   2380 		 * right way. shellPath will be set up by Shell_Init.
   2381 		 */
   2382 		if (newShell.name == NULL) {
   2383 			Parse_Error(PARSE_FATAL,
   2384 			    "Neither path nor name specified");
   2385 			free(words);
   2386 			return FALSE;
   2387 		} else {
   2388 			if ((sh = FindShellByName(newShell.name)) == NULL) {
   2389 				Parse_Error(PARSE_WARNING,
   2390 				    "%s: No matching shell", newShell.name);
   2391 				free(words);
   2392 				return FALSE;
   2393 			}
   2394 			commandShell = sh;
   2395 			shellName = newShell.name;
   2396 			if (shellPath != NULL) {
   2397 				/*
   2398 				 * Shell_Init has already been called!
   2399 				 * Do it again.
   2400 				 */
   2401 				free(UNCONST(shellPath));
   2402 				shellPath = NULL;
   2403 				Shell_Init();
   2404 			}
   2405 		}
   2406 	} else {
   2407 		/*
   2408 		 * The user provided a path. If s/he gave nothing else
   2409 		 * (fullSpec is FALSE), try and find a matching shell in the
   2410 		 * ones we know of. Else we just take the specification at
   2411 		 * its word and copy it to a new location. In either case,
   2412 		 * we need to record the path the user gave for the shell.
   2413 		 */
   2414 		shellPath = path;
   2415 		path = strrchr(path, '/');
   2416 		if (path == NULL) {
   2417 			path = UNCONST(shellPath);
   2418 		} else {
   2419 			path++;
   2420 		}
   2421 		if (newShell.name != NULL) {
   2422 			shellName = newShell.name;
   2423 		} else {
   2424 			shellName = path;
   2425 		}
   2426 		if (!fullSpec) {
   2427 			if ((sh = FindShellByName(shellName)) == NULL) {
   2428 				Parse_Error(PARSE_WARNING,
   2429 				    "%s: No matching shell", shellName);
   2430 				free(words);
   2431 				return FALSE;
   2432 			}
   2433 			commandShell = sh;
   2434 		} else {
   2435 			commandShell = bmake_malloc(sizeof *commandShell);
   2436 			*commandShell = newShell;
   2437 		}
   2438 		/* this will take care of shellErrFlag */
   2439 		Shell_Init();
   2440 	}
   2441 
   2442 	if (commandShell->echoOn && commandShell->echoOff) {
   2443 		commandShell->hasEchoCtl = TRUE;
   2444 	}
   2445 
   2446 	if (!commandShell->hasErrCtl) {
   2447 		if (commandShell->errOnOrEcho == NULL) {
   2448 			commandShell->errOnOrEcho = "";
   2449 		}
   2450 		if (commandShell->errOffOrExecIgnore == NULL) {
   2451 			commandShell->errOffOrExecIgnore = "%s\n";
   2452 		}
   2453 	}
   2454 
   2455 	/*
   2456 	 * Do not free up the words themselves, since they might be in use
   2457 	 * by the shell specification.
   2458 	 */
   2459 	free(words);
   2460 	return TRUE;
   2461 }
   2462 
   2463 /*
   2464  * Handle the receipt of an interrupt.
   2465  *
   2466  * All children are killed. Another job will be started if the .INTERRUPT
   2467  * target is defined.
   2468  *
   2469  * Input:
   2470  *	runINTERRUPT	Non-zero if commands for the .INTERRUPT target
   2471  *			should be executed
   2472  *	signo		signal received
   2473  */
   2474 static void
   2475 JobInterrupt(int runINTERRUPT, int signo)
   2476 {
   2477 	Job *job;		/* job descriptor in that element */
   2478 	GNode *interrupt;	/* the node describing the .INTERRUPT target */
   2479 	sigset_t mask;
   2480 	GNode *gn;
   2481 
   2482 	aborting = ABORT_INTERRUPT;
   2483 
   2484 	JobSigLock(&mask);
   2485 
   2486 	for (job = job_table; job < job_table_end; job++) {
   2487 		if (job->status != JOB_ST_RUNNING)
   2488 			continue;
   2489 
   2490 		gn = job->node;
   2491 
   2492 		JobDeleteTarget(gn);
   2493 		if (job->pid) {
   2494 			DEBUG2(JOB,
   2495 			    "JobInterrupt passing signal %d to child %d.\n",
   2496 			    signo, job->pid);
   2497 			KILLPG(job->pid, signo);
   2498 		}
   2499 	}
   2500 
   2501 	JobSigUnlock(&mask);
   2502 
   2503 	if (runINTERRUPT && !opts.touchFlag) {
   2504 		interrupt = Targ_FindNode(".INTERRUPT");
   2505 		if (interrupt != NULL) {
   2506 			opts.ignoreErrors = FALSE;
   2507 			JobRun(interrupt);
   2508 		}
   2509 	}
   2510 	Trace_Log(MAKEINTR, NULL);
   2511 	exit(signo);
   2512 }
   2513 
   2514 /*
   2515  * Do the final processing, i.e. run the commands attached to the .END target.
   2516  *
   2517  * Return the number of errors reported.
   2518  */
   2519 int
   2520 Job_Finish(void)
   2521 {
   2522 	GNode *endNode = Targ_GetEndNode();
   2523 	if (!Lst_IsEmpty(&endNode->commands) ||
   2524 	    !Lst_IsEmpty(&endNode->children)) {
   2525 		if (job_errors != 0) {
   2526 			Error("Errors reported so .END ignored");
   2527 		} else {
   2528 			JobRun(endNode);
   2529 		}
   2530 	}
   2531 	return job_errors;
   2532 }
   2533 
   2534 /* Clean up any memory used by the jobs module. */
   2535 void
   2536 Job_End(void)
   2537 {
   2538 #ifdef CLEANUP
   2539 	free(shellArgv);
   2540 #endif
   2541 }
   2542 
   2543 /*
   2544  * Waits for all running jobs to finish and returns.
   2545  * Sets 'aborting' to ABORT_WAIT to prevent other jobs from starting.
   2546  */
   2547 void
   2548 Job_Wait(void)
   2549 {
   2550 	aborting = ABORT_WAIT;
   2551 	while (jobTokensRunning != 0) {
   2552 		Job_CatchOutput();
   2553 	}
   2554 	aborting = ABORT_NONE;
   2555 }
   2556 
   2557 /*
   2558  * Abort all currently running jobs without handling output or anything.
   2559  * This function is to be called only in the event of a major error.
   2560  * Most definitely NOT to be called from JobInterrupt.
   2561  *
   2562  * All children are killed, not just the firstborn.
   2563  */
   2564 void
   2565 Job_AbortAll(void)
   2566 {
   2567 	Job *job;		/* the job descriptor in that element */
   2568 	int foo;
   2569 
   2570 	aborting = ABORT_ERROR;
   2571 
   2572 	if (jobTokensRunning != 0) {
   2573 		for (job = job_table; job < job_table_end; job++) {
   2574 			if (job->status != JOB_ST_RUNNING)
   2575 				continue;
   2576 			/*
   2577 			 * kill the child process with increasingly drastic
   2578 			 * signals to make darn sure it's dead.
   2579 			 */
   2580 			KILLPG(job->pid, SIGINT);
   2581 			KILLPG(job->pid, SIGKILL);
   2582 		}
   2583 	}
   2584 
   2585 	/*
   2586 	 * Catch as many children as want to report in at first, then give up
   2587 	 */
   2588 	while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
   2589 		continue;
   2590 }
   2591 
   2592 /*
   2593  * Tries to restart stopped jobs if there are slots available.
   2594  * Called in process context in response to a SIGCONT.
   2595  */
   2596 static void
   2597 JobRestartJobs(void)
   2598 {
   2599 	Job *job;
   2600 
   2601 	for (job = job_table; job < job_table_end; job++) {
   2602 		if (job->status == JOB_ST_RUNNING &&
   2603 		    (make_suspended || job->suspended)) {
   2604 			DEBUG1(JOB, "Restarting stopped job pid %d.\n",
   2605 			    job->pid);
   2606 			if (job->suspended) {
   2607 				(void)printf("*** [%s] Continued\n",
   2608 				    job->node->name);
   2609 				(void)fflush(stdout);
   2610 			}
   2611 			job->suspended = FALSE;
   2612 			if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
   2613 				debug_printf("Failed to send SIGCONT to %d\n",
   2614 				    job->pid);
   2615 			}
   2616 		}
   2617 		if (job->status == JOB_ST_FINISHED) {
   2618 			/*
   2619 			 * Job exit deferred after calling waitpid() in a
   2620 			 * signal handler
   2621 			 */
   2622 			JobFinish(job, job->exit_status);
   2623 		}
   2624 	}
   2625 	make_suspended = FALSE;
   2626 }
   2627 
   2628 static void
   2629 watchfd(Job *job)
   2630 {
   2631 	if (job->inPollfd != NULL)
   2632 		Punt("Watching watched job");
   2633 
   2634 	fds[nJobs].fd = job->inPipe;
   2635 	fds[nJobs].events = POLLIN;
   2636 	allJobs[nJobs] = job;
   2637 	job->inPollfd = &fds[nJobs];
   2638 	nJobs++;
   2639 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
   2640 	if (useMeta) {
   2641 		fds[nJobs].fd = meta_job_fd(job);
   2642 		fds[nJobs].events = fds[nJobs].fd == -1 ? 0 : POLLIN;
   2643 		allJobs[nJobs] = job;
   2644 		nJobs++;
   2645 	}
   2646 #endif
   2647 }
   2648 
   2649 static void
   2650 clearfd(Job *job)
   2651 {
   2652 	size_t i;
   2653 	if (job->inPollfd == NULL)
   2654 		Punt("Unwatching unwatched job");
   2655 	i = (size_t)(job->inPollfd - fds);
   2656 	nJobs--;
   2657 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
   2658 	if (useMeta) {
   2659 		/*
   2660 		 * Sanity check: there should be two fds per job, so the job's
   2661 		 * pollfd number should be even.
   2662 		 */
   2663 		assert(nfds_per_job() == 2);
   2664 		if (i % 2)
   2665 			Punt("odd-numbered fd with meta");
   2666 		nJobs--;
   2667 	}
   2668 #endif
   2669 	/*
   2670 	 * Move last job in table into hole made by dead job.
   2671 	 */
   2672 	if (nJobs != i) {
   2673 		fds[i] = fds[nJobs];
   2674 		allJobs[i] = allJobs[nJobs];
   2675 		allJobs[i]->inPollfd = &fds[i];
   2676 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
   2677 		if (useMeta) {
   2678 			fds[i + 1] = fds[nJobs + 1];
   2679 			allJobs[i + 1] = allJobs[nJobs + 1];
   2680 		}
   2681 #endif
   2682 	}
   2683 	job->inPollfd = NULL;
   2684 }
   2685 
   2686 static int
   2687 readyfd(Job *job)
   2688 {
   2689 	if (job->inPollfd == NULL)
   2690 		Punt("Polling unwatched job");
   2691 	return (job->inPollfd->revents & POLLIN) != 0;
   2692 }
   2693 
   2694 /* Put a token (back) into the job pipe.
   2695  * This allows a make process to start a build job. */
   2696 static void
   2697 JobTokenAdd(void)
   2698 {
   2699 	char tok = JOB_TOKENS[aborting], tok1;
   2700 
   2701 	/* If we are depositing an error token flush everything else */
   2702 	while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
   2703 		continue;
   2704 
   2705 	DEBUG3(JOB, "(%d) aborting %d, deposit token %c\n",
   2706 	    getpid(), aborting, JOB_TOKENS[aborting]);
   2707 	while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
   2708 		continue;
   2709 }
   2710 
   2711 /* Prep the job token pipe in the root make process. */
   2712 void
   2713 Job_ServerStart(int max_tokens, int jp_0, int jp_1)
   2714 {
   2715 	int i;
   2716 	char jobarg[64];
   2717 
   2718 	if (jp_0 >= 0 && jp_1 >= 0) {
   2719 		/* Pipe passed in from parent */
   2720 		tokenWaitJob.inPipe = jp_0;
   2721 		tokenWaitJob.outPipe = jp_1;
   2722 		(void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
   2723 		(void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
   2724 		return;
   2725 	}
   2726 
   2727 	JobCreatePipe(&tokenWaitJob, 15);
   2728 
   2729 	snprintf(jobarg, sizeof jobarg, "%d,%d",
   2730 	    tokenWaitJob.inPipe, tokenWaitJob.outPipe);
   2731 
   2732 	Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
   2733 	Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
   2734 
   2735 	/*
   2736 	 * Preload the job pipe with one token per job, save the one
   2737 	 * "extra" token for the primary job.
   2738 	 *
   2739 	 * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
   2740 	 * larger than the write buffer size of the pipe, we will
   2741 	 * deadlock here.
   2742 	 */
   2743 	for (i = 1; i < max_tokens; i++)
   2744 		JobTokenAdd();
   2745 }
   2746 
   2747 /* Return a withdrawn token to the pool. */
   2748 void
   2749 Job_TokenReturn(void)
   2750 {
   2751 	jobTokensRunning--;
   2752 	if (jobTokensRunning < 0)
   2753 		Punt("token botch");
   2754 	if (jobTokensRunning || JOB_TOKENS[aborting] != '+')
   2755 		JobTokenAdd();
   2756 }
   2757 
   2758 /*
   2759  * Attempt to withdraw a token from the pool.
   2760  *
   2761  * If pool is empty, set wantToken so that we wake up when a token is
   2762  * released.
   2763  *
   2764  * Returns TRUE if a token was withdrawn, and FALSE if the pool is currently
   2765  * empty.
   2766  */
   2767 Boolean
   2768 Job_TokenWithdraw(void)
   2769 {
   2770 	char tok, tok1;
   2771 	ssize_t count;
   2772 
   2773 	wantToken = 0;
   2774 	DEBUG3(JOB, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
   2775 	    getpid(), aborting, jobTokensRunning);
   2776 
   2777 	if (aborting != ABORT_NONE || (jobTokensRunning >= opts.maxJobs))
   2778 		return FALSE;
   2779 
   2780 	count = read(tokenWaitJob.inPipe, &tok, 1);
   2781 	if (count == 0)
   2782 		Fatal("eof on job pipe!");
   2783 	if (count < 0 && jobTokensRunning != 0) {
   2784 		if (errno != EAGAIN) {
   2785 			Fatal("job pipe read: %s", strerror(errno));
   2786 		}
   2787 		DEBUG1(JOB, "(%d) blocked for token\n", getpid());
   2788 		return FALSE;
   2789 	}
   2790 
   2791 	if (count == 1 && tok != '+') {
   2792 		/* make being aborted - remove any other job tokens */
   2793 		DEBUG2(JOB, "(%d) aborted by token %c\n", getpid(), tok);
   2794 		while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
   2795 			continue;
   2796 		/* And put the stopper back */
   2797 		while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
   2798 		       errno == EAGAIN)
   2799 			continue;
   2800 		if (shouldDieQuietly(NULL, 1))
   2801 			exit(2);
   2802 		Fatal("A failure has been detected "
   2803 		      "in another branch of the parallel make");
   2804 	}
   2805 
   2806 	if (count == 1 && jobTokensRunning == 0)
   2807 		/* We didn't want the token really */
   2808 		while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
   2809 		       errno == EAGAIN)
   2810 			continue;
   2811 
   2812 	jobTokensRunning++;
   2813 	DEBUG1(JOB, "(%d) withdrew token\n", getpid());
   2814 	return TRUE;
   2815 }
   2816 
   2817 /*
   2818  * Run the named target if found. If a filename is specified, then set that
   2819  * to the sources.
   2820  *
   2821  * Exits if the target fails.
   2822  */
   2823 Boolean
   2824 Job_RunTarget(const char *target, const char *fname)
   2825 {
   2826 	GNode *gn = Targ_FindNode(target);
   2827 	if (gn == NULL)
   2828 		return FALSE;
   2829 
   2830 	if (fname != NULL)
   2831 		Var_Set(ALLSRC, fname, gn);
   2832 
   2833 	JobRun(gn);
   2834 	/* XXX: Replace with GNode_IsError(gn) */
   2835 	if (gn->made == ERROR) {
   2836 		PrintOnError(gn, "\n\nStop.");
   2837 		exit(1);
   2838 	}
   2839 	return TRUE;
   2840 }
   2841 
   2842 #ifdef USE_SELECT
   2843 int
   2844 emul_poll(struct pollfd *fd, int nfd, int timeout)
   2845 {
   2846 	fd_set rfds, wfds;
   2847 	int i, maxfd, nselect, npoll;
   2848 	struct timeval tv, *tvp;
   2849 	long usecs;
   2850 
   2851 	FD_ZERO(&rfds);
   2852 	FD_ZERO(&wfds);
   2853 
   2854 	maxfd = -1;
   2855 	for (i = 0; i < nfd; i++) {
   2856 		fd[i].revents = 0;
   2857 
   2858 		if (fd[i].events & POLLIN)
   2859 			FD_SET(fd[i].fd, &rfds);
   2860 
   2861 		if (fd[i].events & POLLOUT)
   2862 			FD_SET(fd[i].fd, &wfds);
   2863 
   2864 		if (fd[i].fd > maxfd)
   2865 			maxfd = fd[i].fd;
   2866 	}
   2867 
   2868 	if (maxfd >= FD_SETSIZE) {
   2869 		Punt("Ran out of fd_set slots; "
   2870 		     "recompile with a larger FD_SETSIZE.");
   2871 	}
   2872 
   2873 	if (timeout < 0) {
   2874 		tvp = NULL;
   2875 	} else {
   2876 		usecs = timeout * 1000;
   2877 		tv.tv_sec = usecs / 1000000;
   2878 		tv.tv_usec = usecs % 1000000;
   2879 		tvp = &tv;
   2880 	}
   2881 
   2882 	nselect = select(maxfd + 1, &rfds, &wfds, NULL, tvp);
   2883 
   2884 	if (nselect <= 0)
   2885 		return nselect;
   2886 
   2887 	npoll = 0;
   2888 	for (i = 0; i < nfd; i++) {
   2889 		if (FD_ISSET(fd[i].fd, &rfds))
   2890 			fd[i].revents |= POLLIN;
   2891 
   2892 		if (FD_ISSET(fd[i].fd, &wfds))
   2893 			fd[i].revents |= POLLOUT;
   2894 
   2895 		if (fd[i].revents)
   2896 			npoll++;
   2897 	}
   2898 
   2899 	return npoll;
   2900 }
   2901 #endif /* USE_SELECT */
   2902