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