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