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