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