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