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