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