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