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