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