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