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