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