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