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