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