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