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