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