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