/*-
 * job.c --
 *	handle the creation etc. of our child processes.
 *
 * Copyright (c) 1988, 1989 by the Regents of the University of California
 * Copyright (c) 1988, 1989 by Adam de Boor
 * Copyright (c) 1989 by Berkeley Softworks
 *
 * Permission to use, copy, modify, and distribute this
 * software and its documentation for any non-commercial purpose
 * and without fee is hereby granted, provided that the above copyright
 * notice appears in all copies.  The University of California,
 * Berkeley Softworks and Adam de Boor make no representations about
 * the suitability of this software for any purpose.  It is provided
 * "as is" without express or implied warranty.
 *
 * Interface:
 *	Job_Make  	    	Start the creation of the given target.
 *
 *	Job_CatchChildren   	Check for and handle the termination of any
 *	    	  	    	children. This must be called reasonably
 *	    	  	    	frequently to keep the whole make going at
 *	    	  	    	a decent clip, since job table entries aren't
 *	    	  	    	removed until their process is caught this way.
 *	    	  	    	Its single argument is TRUE if the function
 *	    	  	    	should block waiting for a child to terminate.
 *
 *	Job_CatchOutput	    	Print any output our children have produced.
 *	    	  	    	Should also be called fairly frequently to
 *	    	  	    	keep the user informed of what's going on.
 *	    	  	    	If no output is waiting, it will block for
 *	    	  	    	a time given by the SEL_* constants, below,
 *	    	  	    	or until output is ready.
 *
 *	Job_ShellPath	    	Returns the current shell path.
 *
 *	Job_Init  	    	Called to intialize this module. in addition,
 *	    	  	    	any commands attached to the .BEGIN target
 *	    	  	    	are executed before this function returns.
 *	    	  	    	Hence, the makefile must have been parsed
 *	    	  	    	before this function is called.
 *
 *	Job_Full  	    	Return TRUE if the job table is filled.
 *
 *	Job_Empty 	    	Return TRUE if the job table is completely
 *	    	  	    	empty.
 *
 *	Job_ParseShell	    	Given the line following a .SHELL target, parse
 *	    	  	    	the line as a shell specification. Returns
 *	    	  	    	FAILURE if the spec was incorrect.
 *
 *	Job_End	  	    	Perform any final processing which needs doing.
 *	    	  	    	This includes the execution of any commands
 *	    	  	    	which have been/were attached to the .END
 *	    	  	    	target. It should only be called when the
 *	    	  	    	job table is empty.
 *
 *	Job_AbortAll	    	Abort all currently running jobs. It doesn't
 *	    	  	    	handle output or do anything for the jobs,
 *	    	  	    	just kills them. It should only be called in
 *	    	  	    	an emergency, as it were.
 *
 *	Job_CheckCommands   	Verify that the commands for a target are
 *	    	  	    	ok. Provide them if necessary and possible.
 *
 *	Job_Touch 	    	Update a target without really updating it.
 *
 *	Job_Wait  	    	Wait for all currently-running jobs to finish.
 *
 *	Job_PrintTarget  	Print banner identifying current job.
 */
#ifndef lint
static char     *rcsid = "$Id: job.c,v 1.96 1995/12/31 04:25:40 stolcke Exp $ ICSI (Berkeley)";
#endif /* not lint */

#include    <stdio.h>
#include    <string.h>
#include    <sys/types.h>
#include    <signal.h>
#include    <sys/stat.h>
#include    <fcntl.h>
#include    <sys/file.h>
#include    <sys/time.h>
#include    <sys/wait.h>
#include    <sys/param.h>
#include    <ctype.h>
#include    <errno.h>
extern int  errno;

#include    "sprite.h"
#include    "make.h"
#include    "job.h"

/*
 * Some systems define the fd_set we use, but not the macros to deal with it
 * (SunOS 3.5, e.g.)
 */
#ifndef FD_SET

# ifdef NEED_FD_SET
/*
 * Then there are the systems that don't even define fd_set...
 */
#  ifndef	FD_SETSIZE
#  define	FD_SETSIZE	256
#  endif
#  ifndef NBBY
#  define NBBY 8
#  endif

typedef long	fd_mask;
#define NFDBITS	(sizeof(fd_mask) * NBBY)	/* bits per mask */
#ifndef howmany
#define	howmany(x, y)	((unsigned int)(((x)+((y)-1)))/(unsigned int)(y))
#endif

typedef	struct fd_set {
	fd_mask	fds_bits[howmany(FD_SETSIZE, NFDBITS)];
} fd_set;

# endif /* NEED_FD_SET */

#define	FD_SET(n, p)	((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
#define	FD_CLR(n, p)	((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
#define	FD_ISSET(n, p)	((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
#define FD_ZERO(p)	memset(p, 0, sizeof(*(p)))

#endif /* FD_SET */


/*
 * error handling variables 
 */
int         	errors = 0;	    /* number of errors reported */
int  	    	aborting = 0;	    /* why is the make aborting? */
static int	signals = 0;	    /* number of unprocessed signals */


/*
 * post-make command processing. The node postCommands is really just the
 * .END target but we keep it around to avoid having to search for it
 * all the time.
 */
static GNode   	  *postCommands;    /* node containing commands to execute when
				     * everything else is done */
static int     	  numCommands; 	    /* The number of commands actually printed
				     * for a target. Should this number be
				     * 0, no shell will be executed. */


/*
 * Return values from JobStart.
 */
#define JOB_RUNNING	0   	/* Job is running */
#define JOB_ERROR 	1   	/* Error in starting the job */
#define JOB_FINISHED	2   	/* The job is already finished */
#define JOB_STOPPED	3   	/* The job is stopped (XXX: unused) */
#define JOB_NOTNOW	4   	/* Resource shortage -- try again later */

/*
 * tfile is the name of a file into which all shell commands are put. It is
 * used over by removing it before the child shell is executed. The XXXXX in
 * the string are replaced by the pid of the make process in a 5-character
 * field with leading zeroes. 
 */
static char     tfile[] = TMPPAT;


/*
 * Descriptions for various shells.
 */
static Shell    shells[] = {
    /*
     * CSH description. The csh can do echo control by playing
     * with the setting of the 'echo' shell variable. Sadly,
     * however, it is unable to do error control nicely.
     */
{
    "csh",
    TRUE, "unset verbose", "set verbose",
          "unset verbose", sizeof("unset verbose") - 1,
    FALSE, "echo \"%s\"\n", "/bin/csh -fc \"%s || exit 0\"\n",
    "fv", "fe",
},
    /*
     * SH description. Echo control is also possible and, under
     * sun UNIX anyway, one can even control error checking.
     */
{
    "sh",
    TRUE, "set -", "set -v",
          "set -", sizeof("set -") - 1,
    /*
     * set +e seems to work fine on Suns and System V machines, but is broken
     * on many others. Override in system.mk if necessary.
     */
    TRUE, "set -e", "set +e",
    "v", "e",
},
    /*
     * UNKNOWN.
     */
{
    (char *)0,
    FALSE, (char *)0, (char *)0, (char *)0, 0,
    FALSE, (char *)0, (char *)0,
    (char *)0, (char *)0,
}
};

Shell       	*commandShell = &shells[DEFSHELL]; /* this is the shell to
						   * which we pass all
						   * commands in the Makefile.
						   * It is set by the
						   * Job_ParseShell function */
char        	*shellPath = (char *) NULL,	  /* full pathname of
						   * executable image */
               	*shellName;	      	      	  /* last component of shell */
Boolean		shellChanged = FALSE;		  /* the shell path needs to
						   * to be recomputed from
						   * the SHELL variable.  Set
						   * by the makefile parser */

static int  	maxJobs;    	/* The most children we can run at once */
int  		maxLocal;    	/* The most local ones we can have */
int  	    	nJobs;	    	/* The number of children currently running */
int  	    	nLocal;    	/* The number of local children */
Lst  	    	jobs;		/* The structures that describe them */
Boolean	    	jobFull;    	/* Flag to tell when the job table is full. It
				 * is set TRUE when (1) the total number of
				 * running jobs equals the maximum allowed or
				 * (2) a job can only be run locally, but
				 * nLocal equals maxLocal or (3) a job can
				 * only be run remotely but no suitable host
				 * is currently available or (4) job creation
				 * fails due to a resource limitation. */
static Boolean	making;		/* Jobs have been started */
#ifndef RMT_WILL_WATCH
static fd_set  	outputs;    	/* Set of descriptors of pipes connected to
				 * the output channels of children */
#endif

static char	*targFmt;   	/* Format string to use to head output from a
				 * job when it's not the most-recent job heard
				 * from */
#define TARG_FMT  "--- %s ---\n" /* Default format */

/*
 * When JobStart attempts to run a job remotely but can't, and isn't allowed
 * to run the job locally, or when Job_CatchChildren detects a job that has
 * been migrated home, the job is placed on the stoppedJobs queue to be run
 * when the next job finishes. 
 */
Lst  	    stoppedJobs;	/* Lst of Job structures describing
				 * jobs that were stopped due to concurrency
				 * limits or migration home */

#if defined(USE_PGRP)
#define KILL(pid,sig)	KILLPG((pid),(sig))
#else
#define KILL(pid,sig)	kill((pid),(sig))
#endif

static int  JobStart();
static void JobInterrupt();
static Boolean JobSendSig();

/*-
 *-----------------------------------------------------------------------
 * Job_PrintTarget --
 *	Print a banner identifying target to stream, unless the current
 *	target is already identified by the previously printed banner.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	lastNode is set.
 *
 *-----------------------------------------------------------------------
 */
void
Job_PrintTarget (job, stream)
    Job		*job;		/* Job for target */
    FILE	*stream;	/* stream to print on */
{
    static GNode *lastNode = NILGNODE;
				/* The node for which output was most recently
				 * produced. */
    static char  *lastHost = (char *) 0;
				/* Last remote host */
    if (job->node != lastNode || job->rmtHost != lastHost) {
	if ((job->flags & JOB_REMOTE) && job->rmtHost) {
	    char banner[80]; 

	    sprintf (banner, "%.*s (%.*s)",
		             sizeof(banner) - 4, job->node->name,
		             sizeof(banner) - 4 - strlen(job->node->name),
		             job->rmtHost);
	    fprintf (stream, targFmt, banner);
	} else {
	    fprintf (stream, targFmt, job->node->name);
	}
	fflush (stream);
	lastNode = job->node;
	lastHost = job->rmtHost;
    }
}

/*-
 *-----------------------------------------------------------------------
 * JobCondPassSig --
 *	Pass a signal to a job if the job is remote or if USE_PGRP
 *	is defined.
 *
 * Results:
 *	=== 0
 *
 * Side Effects:
 *	None, except the job may bite it.
 *
 *-----------------------------------------------------------------------
 */
static int
JobCondPassSig(job, signo)
    Job	    	*job;	    /* Job to biff */
    int	    	signo;	    /* Signal to send it */
{
    if (!JobIsValid(job)) {
	return (0);
    }

#if defined(SYSV) && defined(USE_PGRP)
    /*
     * Some systems kill background processes with SIGHUP if one tries
     * to send them terminal stop signals. So turn them into SIGSTOP's.
     * This has some drawbacks, like sub-makes cannot catch them and pass
     * them on, but it's better than nothing.
     */
    if ((signo == SIGTSTP) || (signo == SIGTTIN) || (signo == SIGTTOU))
	signo = SIGSTOP;
#endif /* SYSV && USE_PGRP */

#ifdef RMT_WANTS_SIGNALS
    if (job->flags & JOB_REMOTE) {
	/*
	 * If job is remote, let the Rmt module do the killing.
	 * We ignore errors since the most likely cause is a remote
	 * job exit notification that hasn't reached us yet.
	 */
	if (DEBUG(JOB)) {
	    Debug ("Remote signal %d to %s...\n", signo, job->node->name);
	}
	(void)Rmt_Signal(job, signo);
    } else if (job->pid) {
	if (DEBUG(JOB)) {
	    Debug ("Sending signal %d to %s...\n", signo, job->node->name);
	}
	KILL(job->pid, signo);
    }
#else /* !RMT_WANTS_SIGNALS */
    /*
     * Assume that sending the signal to job->pid will signal any remote
     * job as well.
     */
    if (job->pid) {
	if (DEBUG(JOB)) {
	    Debug ("Sending signal %d to %s...\n", signo, job->node->name);
	}
	KILL(job->pid, signo);
    }
#endif /* RMT_WANTS_SIGNALS */
    return(0);
}

/*-
 *-----------------------------------------------------------------------
 * JobPassSig --
 *	Catch a signal and schedule an event that will pass them on.
 *	However, this will work only with RMT_WILL_WATCH, when we can rely
 *	on the RPC system running virtually continuously.  If this is not
 *	the case we just call JobSendSig ourselves.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	An rpc event is scheduled to do the job.
 *	
 *-----------------------------------------------------------------------
 */
static SIGRET
JobPassSig(signo)
    int	    signo;	/* The signal number we've received */
{
    signals++;

    /*
     * XXX: Do this early to narrow window for back-to-back signals.
     */
    SIGRESTORE(signo, JobPassSig);

#ifdef RMT_WILL_WATCH
    if (making) {
	Rmt_Event(JobSendSig, (char *)signo);
    } else
#endif /* RMT_WILL_WATCH */
	(void)JobSendSig(signo);
}

/*-
 *-----------------------------------------------------------------------
 * JobSendSig --
 *	Pass a signal on to all remote jobs and to all local jobs if
 *	USE_PGRP is defined, then die ourselves.
 *
 * Results:
 *	TRUE.
 *
 * Side Effects:
 *	We die by the same signal.
 *	
 *-----------------------------------------------------------------------
 */
static Boolean
JobSendSig(signo)
    int	    signo;	/* The signal number we've received */
{
    Lst     oldJobs;		/* List of all jobs to signal */
    int     wasAborting;	/* Saved aborting status */
    Boolean interrupt;		/* Do .INTERRUPT processing */
    SIGSET_T mask, oldmask;
    
    if (signals > 0) {
	signals--;
    }

    /*
     * Save the aborting status (in case the signal interrupted .INTERRUPT
     * targets) to restore it later.
     * Set aborting here (not just later in JobInterrupt) to prevent new
     * jobs from starting as a side-effect exit handling.
     */
    wasAborting = aborting;
    if (signo == SIGINT) {
	aborting = ABORT_INTERRUPT;
	interrupt = TRUE;
    } else if ((signo == SIGHUP) || (signo == SIGTERM) || (signo == SIGQUIT)
#ifdef SIGXCPU
               || (signo == SIGXCPU)
#endif
              ) {
	aborting = ABORT_INTERRUPT;
	interrupt = FALSE;
    }
    else {
	aborting = ABORT_WAIT;
    }
    
    /*
     * Make a scratch list of all jobs to signal.
     * We can't just walk down the current list because it is likely to
     * change as a result of this very operation.
     */
    oldJobs = Lst_Init(FALSE);
    Lst_Concat(oldJobs, stoppedJobs, LST_CONCNEW);
    Lst_Concat(oldJobs, jobs, LST_CONCNEW);

    if (signo != SIGCONT && signo != SIGKILL && signo != SIGSTOP &&
	signo != SIGTSTP && signo != SIGTTIN && signo != SIGTTOU)
    {
	/*
	 * Make sure interrupts reach their targets.
	 * Stopped jobs have to be awakened to be able to react to the signal,
	 * lest they hang around indefinitely.
	 */
        Lst_ForEach(oldJobs, JobCondPassSig, (ClientData)SIGCONT);
    }
    Lst_ForEach(oldJobs, JobCondPassSig, (ClientData)signo);
    Lst_Destroy(oldJobs, NOFREE);

    /*
     * Deal with proper cleanup based on the signal received. We only run
     * the .INTERRUPT target if the signal was in fact an interrupt. The other
     * three termination signals are more of a "get out *now*" command.
     */
    if (wasAborting != ABORT_INTERRUPT &&
	aborting == ABORT_INTERRUPT)
    {
	JobInterrupt (interrupt);
    }

    /*
     * Update local jobs before changing our state.
     */
    Job_CatchChildren (FALSE);

    /*
     * Try to core dump in COREDIR to avoid garbling children's cores.
     */
    if (signo == SIGQUIT) {
#ifdef COREDIR
	if (chdir(COREDIR) >= 0) {
	    Error("Dumping core in %s", COREDIR);
	}
	else
#endif /* COREDIR */
	    Finish(errors);
    }
    
    /*
     * Send ourselves the signal now we've given the message to everyone else.
     * Note we block everything else possible while we're getting the signal.
     * This ensures that all our jobs get continued when we wake up before
     * we take any other signal.
     */
    SIGNAL(signo, SIG_DFL);

    SIGFILLSET(mask);
    SIGDELSET(mask, signo);
    SIGSETMASK(mask, oldmask);

    kill(getpid(), signo);

    SIGSETMASK(oldmask, mask);

    SIGNAL(signo, JobPassSig);

    /*
     * While we were suspended children might have terminated from external
     * causes. To avoid 'no such process' errors from trying to restarting them
     * we update our local job list one more time.
     */
    Job_CatchChildren (FALSE);

    /*
     * Rather than just sending everybody a SIGCONT, let the job scheduler
     * restart 'em.  This will ensure the job lists are updated properly.
     */
    aborting = wasAborting;
    JobRestartAll("JobSendSig", TRUE);

    return (TRUE);
}

/*-
 *-----------------------------------------------------------------------
 * JobCmpPid  --
 *	Compare the pid of the job with the given pid and return 0 if they
 *	are equal. This function is called from Job_CatchChildren via
 *	Lst_Find to find the job descriptor of the finished job.
 *
 * Results:
 *	0 if the pid's match
 *
 * Side Effects:
 *	None
 *-----------------------------------------------------------------------
 */
static int
JobCmpPid (job, pid)
    int             pid;	/* process id desired */
    Job            *job;	/* job to examine */
{
    return (pid - job->pid);
}

/*-
 *-----------------------------------------------------------------------
 * JobPrintCommand  --
 *	Put out another command for the given job. If the command starts
 *	with an @ or a - we process it specially. In the former case,
 *	so long as the -s and -n flags weren't given to make, we stick
 *	a shell-specific echoOff command in the script. In the latter,
 *	we ignore errors for the entire job, unless the shell has error
 *	control.
 *	If the command is just "..." we take all future commands for this
 *	job to be commands to be executed once the entire graph has been
 *	made and return non-zero to signal that the end of the commands
 *	was reached. These commands are later attached to the postCommands
 *	node and executed by Job_End when all things are done.
 *	This function is called from JobStart via Lst_ForEach.
 *
 * Results:
 *	Always 0, unless the command was "..."
 *
 * Side Effects:
 *	If the command begins with a '-' and the shell has no error control,
 *	the JOB_IGNERR flag is set in the job descriptor.
 *	If the command is "..." and we're not ignoring such things,
 *	tailCmds is set to the successor node of the cmd.
 *	numCommands is incremented if the command is actually printed.
 *-----------------------------------------------------------------------
 */
static int
JobPrintCommand (cmd, job)
    char     	  *cmd;	    	    /* command string to print */
    Job           *job;	    	    /* job for which to print it */
{
    Boolean	  noSpecials;	    /* true if we shouldn't worry about
				     * inserting special commands into
				     * the input stream. */
    Boolean       shutUp = FALSE;   /* true if we put a no echo command
				     * into the command file */
    Boolean	  errOff = FALSE;   /* true if we turned error checking
				     * off before printing the command
				     * and need to turn it back on */
    char       	  *cmdTemplate;	    /* Template to use when printing the
				     * command */
    char    	  *cmdStart;	    /* Start of expanded command */
    LstNode 	  cmdNode;  	    /* Node for replacing the command */

    noSpecials = (noExecute && ! (job->node->type & OP_MAKE));

    if (strcmp (cmd, "...") == 0) {
	if ((job->flags & JOB_IGNDOTS) == 0) {
	    job->tailCmds = Lst_Succ (Lst_Member (job->node->commands,
						  (ClientData)cmd));
	    return (1);
	}
	return (0);
    }

#define DBPRINTF(fmt, arg) \
	if (DEBUG(JOB)) { \
	    Debug ("\tEmitting: "); \
	    Debug (fmt, arg); \
	} \
	fprintf (job->cmdFILE, fmt, arg)

    numCommands += 1;

    /*
     * For debugging, we replace each command with the result of expanding
     * the variables in the command.
     */
    cmdNode = Lst_Member (job->node->commands, (ClientData)cmd);
    cmdStart = Var_Subst (cmd, job->node, FALSE);
    Lst_Replace (cmdNode, (ClientData)cmdStart);
    free(cmd);
    cmd = cmdStart;

    cmdTemplate = "%s\n";

    /*
     * Check for leading @' and -'s to control echoing and error checking.
     * The '@' and '-' directives may be interspersed with whitespace.
     * Also eat up any whitespace between them and the command itself.
     */
    while ((*cmd == ' ') || (*cmd == '\t') ||
	   (*cmd == '@') || (*cmd == '-'))
    {
	if (*cmd == '@') {
	    shutUp = TRUE;
	} else if (*cmd == '-') {
	    errOff = TRUE;
	}
	cmd++;
    }

    if (shutUp) {
	if (backwards) {
	    /*
	     * In backwards mode we can simply set JOB_SILENT for this
	     * job, since it will affect only one command and will be
	     * reset when JobStart is invoked for the next command.
	     */
	    job->flags |= JOB_SILENT;
	    shutUp = FALSE;
	} else if (! (job->flags & JOB_SILENT) && !noSpecials &&
	    commandShell->hasEchoCtl) {
		DBPRINTF ("%s\n", commandShell->echoOff);
	} else {
	    shutUp = FALSE;
	}
    }

    if (errOff) {
	if (backwards) {
	    /*
	     * In backwards mode we can simply set JOB_IGNERR for this
	     * job, since it will affect only one command and will be
	     * reset when JobStart is invoked for the next command.
	     * This also provides full backwards compatibility, as it
	     * works even even if the command contains 'exit 1',
	     * 'exec false', or some such.
	     */
	    job->flags |= JOB_IGNERR;
	    errOff = FALSE;
	} else if ( ! (job->flags & JOB_IGNERR) && !noSpecials) {
	    if (commandShell->hasErrCtl) {
		/*
		 * we don't want the error-control commands showing
		 * up either, so we turn off echoing while executing
		 * them. We could put another field in the shell
		 * structure to tell JobDoOutput to look for this
		 * string too, but why make it any more complex than
		 * it already is?
		 */
		if (! (job->flags & JOB_SILENT) && !shutUp &&
		    commandShell->hasEchoCtl) {
			DBPRINTF ("%s\n", commandShell->echoOff);
			DBPRINTF ("%s\n", commandShell->ignErr);
			DBPRINTF ("%s\n", commandShell->echoOn);
		} else {
		    DBPRINTF ("%s\n", commandShell->ignErr);
		}
	    } else if (commandShell->ignErr &&
		       (*commandShell->ignErr != '\0'))
	    {
		/*
		 * The shell has no error control, so we need to be
		 * weird to get it to ignore any errors from the command.
		 * If echoing is turned on, we turn it off and use the
		 * errCheck template to echo the command. Leave echoing
		 * off so the user doesn't see the weirdness we go through
		 * to ignore errors. Set cmdTemplate to use the weirdness
		 * instead of the simple "%s\n" template.
		 */
		if (! (job->flags & JOB_SILENT) && !shutUp &&
		    commandShell->hasEchoCtl) {
			DBPRINTF ("%s\n", commandShell->echoOff);
			DBPRINTF (commandShell->errCheck, cmd);
			shutUp = TRUE;
		}
		cmdTemplate = commandShell->ignErr;
		/*
		 * The error ignoration (hee hee) is already taken care
		 * of by the ignErr template, so pretend error checking
		 * is still on.
		 */
		errOff = FALSE;
	    } else {
		errOff = FALSE;
	    }
	} else {
	    errOff = FALSE;
	}
    }
    
    DBPRINTF (cmdTemplate, cmd);
    
    if (errOff) {
	/*
	 * If echoing is already off, there's no point in issuing the
	 * echoOff command. Otherwise we issue it and pretend it was on
	 * for the whole command...
	 */
	if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl){
	    DBPRINTF ("%s\n", commandShell->echoOff);
	    shutUp = TRUE;
	}
	DBPRINTF ("%s\n", commandShell->errCheck);
    }
    if (shutUp) {
	DBPRINTF ("%s\n", commandShell->echoOn);
    }
    return (0);
}

/*-
 *-----------------------------------------------------------------------
 * JobSaveCommand --
 *	Save a command to be executed when everything else is done.
 *	Callback function for JobFinish...
 *
 * Results:
 *	Always returns 0
 *
 * Side Effects:
 *	The command is tacked onto the end of postCommands's commands list.
 *
 *-----------------------------------------------------------------------
 */
static int
JobSaveCommand (cmd, gn)
    char    *cmd;
    GNode   *gn;
{
    cmd = Var_Subst (cmd, gn, FALSE);
    (void)Lst_AtEnd (postCommands->commands, (ClientData)cmd);
    return (0);
}

/*-
 *-----------------------------------------------------------------------
 * JobCanRetry --
 *	Determine whether a job can be restarted after error return.
 *
 * Results:
 *	TRUE iff so.
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
static Boolean
JobCanRetry (job, status)
    Job           *job;	      	  /* job to finish */
    WAIT_STATUS status;     	  /* sub-why job went away */
{
    if ((aborting != ABORT_INTERRUPT) &&
	(job->flags & JOB_RETRYERR) &&
	(WIFEXITED(status) && WEXITSTATUS(status) != EXIT_OK)) {
	/*
	 * Job return non-zero status and the user has requested
	 * restarting.
	 */
	return (TRUE);
    } else {
	return (FALSE);
    }
}

/*-
 *-----------------------------------------------------------------------
 * JobRestartAll  --
 *	Try to restart as many stopped jobs as possible.
 *	If resume == TRUE, only currently suspended jobs are restarted,
 *	regardless of errors.
 *
 * Results:
 *	None
 *
 * Side Effects:
 *	Members of stoppedJobs are dequeued and JobRestart is called.
 *	If we loop without emptying the queue JobFull is set to TRUE.
 *-----------------------------------------------------------------------
 */
void
JobRestartAll (tag, resume)
    char	*tag;		/* caller's tag for debugging */
    Boolean	resume;		/* continue suspended jobs */
{
    LstNode ln;
    Job *jobPtr;

    if (DEBUG(JOB)||DEBUG(QUEUE)) {
	Debug("%s: trying to restart %d jobs\n", tag, Lst_Length(stoppedJobs));
    }

    /*
     * Clear JOB_RESTARTING flags
     */
    (void)Lst_Open(stoppedJobs);
    while ((ln = Lst_Next(stoppedJobs)) != NILLNODE) {
	jobPtr = (Job *)Lst_Datum(ln);
	jobPtr->flags &= ~JOB_RESTARTING;
    }
    Lst_Close(stoppedJobs);

    /*
     * Empty the queue as long as no errors or loops are encountered.
     */
    while ((resume || !errors || keepgoing) &&
	   (resume || !aborting) &&
           !jobFull && !Lst_IsEmpty(stoppedJobs))
    {
        jobPtr = (Job *)Lst_Datum(Lst_First(stoppedJobs));

	if (jobPtr->flags & JOB_RESTARTING) {
	    if (DEBUG(JOB)||DEBUG(QUEUE)) {
		Debug("%s: looping over stoppedJobs\n", tag);
	    }
	    jobFull = TRUE;
	} else {
	    /*
	     * Mark the job to detect cycles
	     */
	    jobPtr->flags |= JOB_RESTARTING;

	    if (!resume || (jobPtr->flags & JOB_RESUME)) {
		QUEUE_REMOVED(tag, jobPtr, "stoppedJobs");
		JobRestart((Job *)Lst_DeQueue(stoppedJobs));
	    }
	}
    }
}

/*-
 *-----------------------------------------------------------------------
 * JobFinish  --
 *	Do final processing for the given job including updating
 *	parents and starting new jobs as available/necessary. Note
 *	that we pay no attention to the JOB_IGNERR flag here.
 *	This is because when we're called because of a noexecute flag
 *	or something, WEXITSTATUS(jstat) is 0 and when called from
 *	Job_CatchChildren, the status is zeroed if it s/b ignored.
 *
 * Results:
 *	None
 *
 * Side Effects:
 *	Some nodes may be put on the toBeMade queue.
 *	Final commands for the job are placed on postCommands.
 *
 *	If we got an error and are aborting (aborting == ABORT_ERROR) and
 *	the job list is now empty, we are done for the day.
 *	If we recognized an error (errors !=0), we set the aborting flag
 *	to ABORT_ERROR so no more jobs will be started.
 *-----------------------------------------------------------------------
 */
/*ARGSUSED*/
void
JobFinish (job, status)
    Job           *job;	      	  /* job to finish */
    WAIT_STATUS status;     	  /* sub-why job went away */
{
    Boolean 	  done;

    if (JobCanRetry (job, status)) {
	/*
	 * Leave job structure and streams unchanged so we can try
	 * restarting the job.
	 */
	done = FALSE;
    } else if ((WIFEXITED(status) &&
	  (((WEXITSTATUS(status) != EXIT_OK) && !(job->flags & JOB_IGNERR)) ||
	   !backwards)) ||
	(WIFSIGNALED(status) && (WTERMSIG(status) != SIGCONT) &&
	  (!(job->flags & JOB_IGNERR) || !backwards)))
    {
	/*
	 * If it exited non-zero and either we're doing things our
	 * way or we're not ignoring errors, the job is finished.
	 * Similarly, if the shell died because of a signal (the
	 * conditional on SIGCONT is to handle the mapping of Sprite
	 * signal semantics whereby wait will return a signal
	 * termination with SIGCONT being the signal to indicate that the
	 * child has resumed), the job is also finished. In these
	 * cases, finish out the job's output before printing the exit
	 * status...
	 */
	if (usePipes) {
	    if (job->outPipe != job->inPipe) {
		(void)close (job->outPipe);
	    }
	    JobDoOutput (job, TRUE);
	    (void)close (job->inPipe);
	} else {
	    JobDoOutput (job, TRUE);
	    (void)close (job->outFd);
	}

	done = TRUE;
    } else if (backwards &&
	       (WIFSIGNALED(status) && (WTERMSIG(status) != SIGCONT) ||
		WIFEXITED(status) && (WEXITSTATUS(status) != EXIT_OK)))
    {
	/*
	 * Deal with ignored errors in -B mode. We need to print a message
	 * telling of the ignored error as well as setting status.w_status
	 * to 0 so the next command gets run. To do this, we set done to be
	 * TRUE if in -B mode and the job exited non-zero. Note we don't
	 * want to close down any of the streams until we know we're at the
	 * end.
	 */
	done = TRUE;
    } else {
	/*
	 * No need to close things down or anything.
	 */
	done = FALSE;
    }
    
    if (done ||
	WIFSTOPPED(status) ||
	(WIFSIGNALED(status) && (WTERMSIG(status) == SIGCONT)) ||
	JobCanRetry(job, status) ||
	DEBUG(JOB))
    {
	FILE	  *out;
	
	if (backwards && !usePipes && (job->flags & JOB_IGNERR)) {
	    /*
	     * If output is going to a file and this job is ignoring
	     * errors, arrange to have the exit status sent to the
	     * output file as well.
	     */
	    out = fdopen (job->outFd, "w");
	    if (out == (FILE *)0) {
		Error ("Could not open output file (%s)", job->outFile);
		out = stderr;
	    }
	} else {
	    out = stdout;
	}

	if (WIFEXITED(status)) {
	    job->pid = 0;
	    job->rmtID = (char *)0;
	    if (WEXITSTATUS(status) != EXIT_OK) {
		if (queryFlag && (WEXITSTATUS(status) == EXIT_YES)) {
		    /*
		     * This must have been a recursive make target.
		     * Non-zero exit status means it was out-of-date.
		     */
		    if (DEBUG(MAKE) || DEBUG(JOB)) {
			Debug ("Recursive query of `%s' returned yes\n",
			       job->node->name);
		    }
		    outOfDate = TRUE;
		    WSTATUS(status) = 0;
		} else {
		    if (usePipes) {
			Job_PrintTarget(job, out);
		    }
		    fprintf (out == stdout ? stderr : out,
			     "*** Error code %d%s\n", WEXITSTATUS(status),
			     JobCanRetry (job,status) ? " (restarting)" :
			      (job->flags & JOB_IGNERR) ? " (ignored)" :
			       (keepgoing ? " (continuing)" : ""));
		}
		if (JobCanRetry (job, status)) {
		    job->flags &= ~JOB_REMOTE;
		    job->flags |= JOB_RESTART;
		    if (job->rmtHost) free (job->rmtHost);
		    job->rmtHost = (char *)0;

		    JobRestart(job);

		    fflush(out == stdout ? stderr : out);
		    return;
		} else if (job->flags & JOB_IGNERR) {
		    WSTATUS(status) = 0;
		}
	    } else if (DEBUG(JOB)) {
		if (usePipes) {
		    Job_PrintTarget (job, out);
		}
		fprintf (out == stdout ? stderr : out,
			 "*** Completed successfully\n");
	    }
	} else if (WIFSTOPPED(status)) {
	    if (usePipes) {
		Job_PrintTarget (job, out);
	    }
	    if (! (job->flags & JOB_REMIGRATE)) {
		fprintf (out == stdout ? stderr : out,
			 "*** Stopped -- signal %d\n", WSTOPSIG(status));
	    }
	    job->flags |= JOB_RESUME;
	    fflush(out == stdout ? stderr : out);
	    return;
	} else if (WTERMSIG(status) == SIGCONT) {
	    /*
	     * If the beastie has continued, shift the Job from the stopped
	     * list to the running one (or re-stop it if concurrency is
	     * exceeded) and go and get another child.
	     */
	    if (job->flags & (JOB_RESUME|JOB_REMIGRATE|JOB_RESTART)) {
		if (usePipes) {
		    Job_PrintTarget (job, out);
		}
		fprintf (out == stdout ? stderr : out, "*** Continued\n");
	    }
	    if (! (job->flags & JOB_CONTINUING)) {
		JobRestart(job);
	    }

	    fflush(out == stdout ? stderr : out);
	    return;
	} else {
	    job->pid = 0;
	    job->rmtID = (char *)0;
	    if (usePipes) {
		Job_PrintTarget (job, out);
	    }

	    fprintf (out == stdout ? stderr : out,
		     "*** Signal %d%s\n", WTERMSIG(status),
		     JobCanRetry (job, status) ? " (restarting)" :
		      (job->flags & JOB_IGNERR) ? " (ignored)" :
		       (keepgoing ? " (continuing)" : ""));

	    if (JobCanRetry (job, status)) {
		job->flags &= ~JOB_REMOTE;
		job->flags |= JOB_RESTART;
		if (job->rmtHost) free (job->rmtHost);
		job->rmtHost = (char *)0;

	        JobRestart(job);

		fflush(out == stdout ? stderr : out);
		return;
	    } else if (job->flags & JOB_IGNERR) {
		WSTATUS(status) = 0;
	    }
	}

	fflush (out == stdout ? stderr : out);
    }

    /*
     * Close the cmd file now in case it has been done before the job
     * was started.  This is the case for remote jobs, since they may
     * require restarting (see the code with JobCanRetry() above).
     */
    if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
	fclose(job->cmdFILE);
    }

    /*
     * Now handle the -B-mode stuff. If the beast still isn't finished,
     * try and restart the job on the next command. If JobStart says it's
     * ok, it's ok. If there's an error, this puppy is done.
     */
    if (backwards && (WSTATUS(status) == 0) &&
	!Lst_IsAtEnd (job->node->commands))
    {
	/* 
	 * For rechecking purposes the make module needs to know
	 * whether the target creation involved remote execution.
	 */
	if (job->flags & JOB_REMOTE) {
	    job->node->type |= OP_REMOTE;
	}
	
	switch (JobStart (job->node,
			  job->flags & JOB_IGNDOTS,
			  job))
	{
	    case JOB_RUNNING:
	    case JOB_NOTNOW:
		done = FALSE;
		break;
	    case JOB_ERROR:
		done = TRUE;
		WSTATUS(status) = 1<<8; /* status.w_retcode = 1 */
		break;
	    case JOB_FINISHED:
		/*
		 * If we got back a JOB_FINISHED code, JobStart has already
		 * called Make_Update and freed the job descriptor. We set
		 * done to false here to avoid fake cycles and double frees.
		 * JobStart needs to do the update so we can proceed up the
		 * graph when given the -n flag..
		 */
		done = FALSE;
		break;
	}
    } else {
	done = TRUE;
    }
		

    if (done &&
	(aborting != ABORT_ERROR) &&
	(aborting != ABORT_INTERRUPT) &&
	(aborting != ABORT_QUERY) &&
	(WSTATUS(status) == 0))
    {
	/* 
	 * For rechecking purposes the make module needs to know
	 * whether the target creation involved remote execution.
	 */
	if (job->flags & JOB_REMOTE) {
	    job->node->type |= OP_REMOTE;
	}
	
	/*
	 * As long as we aren't aborting and the job didn't return a non-zero
	 * status that we shouldn't ignore, we call Make_Update to update
	 * the parents. In addition, any saved commands for the node are placed
	 * on the .END target.
	 */
	if (job->tailCmds != NILLNODE) {
	    Lst_ForEachFrom (job->node->commands, job->tailCmds,
			     JobSaveCommand,
			     (ClientData)job->node);
	}
	job->node->made = MADE;
	Make_Update (job->node);
	Make_FreeCommands(job->node);

	if (job->rmtHost) free(job->rmtHost);
	free((Address)job);
    } else if (WSTATUS(status)) {
	errors += 1;
	Make_FreeCommands(job->node);

	if (job->rmtHost) free(job->rmtHost);
	free((Address)job);
    }

    JobRestartAll ("JobFinish", FALSE);

    /*
     * Set aborting if any error.
     */
    if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
	/*
	 * If we found any errors in this batch of children and the -k flag
	 * wasn't given, we set the aborting flag so no more jobs get
	 * started.
	 */
	aborting = ABORT_ERROR;
    } else if (queryFlag && outOfDate && (aborting != ABORT_INTERRUPT)) {
	/*
	 * If we already know that something is out of date there is no
	 * point in starting further recursive queries.
	 */
	aborting = ABORT_QUERY;
    }
    
    if ((aborting == ABORT_ERROR) && Job_Empty()) {
	/*
	 * If we are aborting and the job table is now empty, we finish.
	 */
	(void) unlink (tfile);
	Finish (errors);
    }

    if ((aborting == ABORT_QUERY) && Job_Empty()) {
	/*
	 * If the query is answered in the affirmative, and no more jobs
	 * are pending, we may also finish.
	 */
	(void) unlink (tfile);
	Job_Wait();
	exit (EXIT_YES);
    }
}

/*-
 *-----------------------------------------------------------------------
 * Job_Touch --
 *	Touch the given target, or record that it needs remaking for
 *	query answering. Called by JobStart when the -t or -q flag was
 *	given
 *
 * Results:
 *	None
 *
 * Side Effects:
 *	The data modification of the file is changed. In addition, if the
 *	file did not exist, it is created.
 *-----------------------------------------------------------------------
 */
void
Job_Touch (gn, silent)
    GNode         *gn;	      	/* the node of the file to touch */
    Boolean 	  silent;   	/* TRUE if should not print messages */
{
    int		  streamID;   	/* ID of stream opened to do the touch */
    struct timeval times[2];	/* Times for utimes() call */

    if ((gn->type & (OP_JOIN|OP_USE|OP_EXEC|OP_DONTCARE)) ||
	(strcmp(gn->name, ".BEGIN") == 0) ||
	(strcmp(gn->name, ".END") == 0))
    {
	/*
	 * .JOIN, .USE, .ZEROTIME and .DONTCARE targets are "virtual" targets
	 * and, as such, shouldn't really be created.
	 */
	return;
    }
    
    if (OP_NO_CMDS (gn)) {
	/*
	 * Node has no creation commands, so there is no point in trying to
	 * create a file for it.
	 */
	return;
    }

    if (queryFlag) {
	if (DEBUG(MAKE) || DEBUG(JOB)) {
	    Debug ("Target %s has commands and needs remaking\n", gn->name);
	}
	outOfDate = TRUE;
	return;
    }

    if (!silent || noExecute) {
	printf ("touch %s\n", gn->name);
    }

    if (noExecute) {
	return;
    }

    if (gn->type & OP_ARCHV) {
	Arch_Touch (gn);
    } else if (gn->type & OP_LIB) {
	Arch_TouchLib (gn);
    } else {
	char	*file = gn->path ? gn->path : gn->name;

	times[0].tv_sec = times[1].tv_sec = now;
	times[0].tv_usec = times[1].tv_usec = 0;
	if (utimes(file, times) < 0){
	    streamID = open (file, O_RDWR | O_CREAT, 0666);

	    if (streamID >= 0) {
		char	c;

		/*
		 * Read and write a byte to the file to change the
		 * modification time, then close the file.
		 */
		if (read(streamID, &c, 1) == 1) {
		    lseek(streamID, 0L, L_SET);
		    write(streamID, &c, 1);
		}
		
		(void)close (streamID);
	    } else {
		Error("Couldn't touch %s: %s", file, strerror(errno));
	    }
	}
    }
}

/*-
 *-----------------------------------------------------------------------
 * Job_CheckCommands --
 *	Make sure the given node has all the commands it needs. 
 *
 * Results:
 *	TRUE if the commands list is/was ok.
 *
 * Side Effects:
 *	The node will have commands from the .DEFAULT rule added to it
 *	if it needs them.
 *-----------------------------------------------------------------------
 */
Boolean
Job_CheckCommands (gn, abortProc)
    GNode          *gn;	    	    /* The target whose commands need
				     * verifying */
    void    	  (*abortProc)();   /* Function to abort with message */
{
    if (OP_NOP(gn->type) && OP_NO_CMDS(gn)) {
	/*
	 * No commands. Look for .DEFAULT rule from which we might infer
	 * commands 
	 */
	if ((DEFAULT != NILGNODE) && !OP_NO_CMDS(DEFAULT)) {
	    /*
	     * Make only looks for a .DEFAULT if the node was never the
	     * target of an operator, so that's what we do too. If
	     * a .DEFAULT was given, we substitute its commands for gn's
	     * commands and set the IMPSRC variable to be the target's name
	     * The DEFAULT node acts like a transformation rule, in that
	     * gn also inherits any attributes or sources attached to
	     * .DEFAULT itself.
	     */
	    Make_HandleUse(DEFAULT, gn);
	    Var_Set (IMPSRC, Targ_Name (gn), gn);
	} else if (Dir_MTime (gn) == 0) {
	    /*
	     * The node wasn't the target of an operator we have no .DEFAULT
	     * rule to go on and the target doesn't already exist. There's
	     * nothing more we can do for this branch. If the -k flag wasn't
	     * given, we stop in our tracks, otherwise we just don't update
	     * this node's parents so they never get examined. 
	     */
	    if (gn->type & OP_DONTCARE) {
		Error ("Don't know how to make target `%s' (ignored)",
		       gn->name);
	    } else if (keepgoing) {
		Error ("Don't know how to make target `%s' (continuing)",
		       gn->name);
		return (FALSE);
	    } else {
		(*abortProc) ("Don't know how to make target `%s'",
			     gn->name);
		return(FALSE);
	    }
	}
    }
    return (TRUE);
}
#ifdef RMT_WILL_WATCH
/*-
 *-----------------------------------------------------------------------
 * JobLocalInput --
 *	Handle a pipe becoming readable. Callback function for Rmt_Watch
 *
 * Results:
 *	None
 *
 * Side Effects:
 *	JobDoOutput is called.
 *	
 *-----------------------------------------------------------------------
 */
/*ARGSUSED*/
static void
JobLocalInput(stream, job)
    int	    stream; 	/* Stream that's ready (ignored) */
    Job	    *job;   	/* Job to which the stream belongs */
{
    JobDoOutput(job, FALSE);
}
#endif /* RMT_WILL_WATCH */

/*-
 *-----------------------------------------------------------------------
 * JobExec --
 *	Execute the shell for the given job. Called from JobStart and
 *	JobRestart.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	A shell is executed, outputs is altered and the Job structure added
 *	to the job table.
 *
 *-----------------------------------------------------------------------
 */
static void
JobExec(job, argv)
    Job	    	  *job; 	/* Job to execute */
    char    	  **argv;
{
    int	    	  cpid;	    	/* ID of new child */
    
    if (DEBUG(JOB)) {
	int 	  i;
	
	Debug ("Running %s %sly\n", job->node->name,
	       job->flags&JOB_REMOTE?"remote":"local");
	Debug ("\tCommand: ");
	for (i = 0; argv[i] != (char *)NULL; i++) {
	    Debug ("%s ", argv[i]);
	}
	Debug ("\n");
    }
    
    /*
     * Some jobs produce no output and it's disconcerting to have
     * no feedback of their running (since they produce no output, the
     * banner with their name in it never appears). This is an attempt to
     * provide that feedback, even if nothing follows it.
     */
    if (usePipes &&
	(job->flags & JOB_FIRST) &&
	!(job->flags & JOB_SILENT))
    {
	Job_PrintTarget (job, stdout);
    }
    
#ifdef RMT_NO_EXEC
    if (job->flags & JOB_REMOTE) {
	goto jobExecFinish;
    }
#endif /* RMT_NO_EXEC */

    if ((cpid =  vfork()) == -1) {
	Punt ("Could not fork: %s", strerror(errno));
    } else if (cpid == 0) {

	/*
	 * Must duplicate the input stream down to the child's input and
	 * reset it to the beginning (again). Since the stream was marked
	 * close-on-exec, we must clear that bit in the new input.
	 */
	(void) dup2(fileno(job->cmdFILE), 0);
	fcntl(0, F_SETFD, 0);
	lseek(0, 0L, L_SET);
	
	if (usePipes) {
	    /*
	     * Set up the child's output to be routed through the pipe
	     * we've created for it.
	     */
	    (void) dup2 (job->outPipe, 1);
	} else {
	    /*
	     * We're capturing output in a file, so we duplicate the
	     * descriptor to the temporary file into the standard
	     * output.
	     */
	    (void) dup2 (job->outFd, 1);
	}
	/*
	 * The output channels are marked close on exec. This bit was
	 * duplicated by the dup2 (on some systems), so we have to clear
	 * it before routing the shell's error output to the same place as
	 * its standard output.
	 */
	fcntl(1, F_SETFD, 0);
	(void) dup2 (1, 2);

	/*
	 * Relinquish all suid/sgid priviledges.
	 */
	Main_Access(ACCESS_CHILD);

#ifdef USE_PGRP
	/*
	 * We want to switch the child into a different process family so
	 * we can kill it and all its descendants in one fell swoop,
	 * by killing its process family, but not commit suicide.
	 */
	(void) SETPGRP();
#endif /* USE_PGRP */

#ifdef RMT_NO_EXEC
	(void) execv (shellPath, argv);
	Error ("Could not execute shell: %s: %s",
	       shellPath, strerror(errno));
#else
	if (job->flags & JOB_REMOTE) {
	    Rmt_Exec (shellPath, argv, FALSE);
	} else {
	    (void) execv (shellPath, argv);
	    Error ("Could not execute shell: %s: %s",
		   shellPath, strerror(errno));
	}
#endif /* RMT_NO_EXEC */

	_exit (1);
    } else {
	job->pid = cpid;

	if (usePipes) {
	    /*
	     * The first time a job is run for a node, we set the current
	     * position in the buffer to the beginning and mark another
	     * stream to watch in the outputs mask
	     */
#ifdef RMT_WILL_WATCH
	    Rmt_Watch(job->inPipe, JobLocalInput, job);
#else
	    FD_SET(job->inPipe, &outputs);
#endif /* RMT_WILL_WATCH */
	}

	if (job->flags & JOB_REMOTE) {
	    job->rmtID = (char *)Rmt_LastID(job->pid);
	} else {
	    nLocal += 1;
	    /*
	     * We don't the need command file any longer, unless the job
	     * may be restarted.
	     * XXX: Used to not happen if CUSTOMS. Why?
	     */
	    if (!(job->flags & JOB_RETRYERR) &&
		job->cmdFILE != stdout)
	    {
		fclose(job->cmdFILE);
		job->cmdFILE = NULL;
	    }
	}
    }

#ifdef RMT_NO_EXEC
jobExecFinish:    
#endif
    /*
     * Now the job is actually running, add it to the table.
     */
    nJobs += 1;
    (void)Lst_AtEnd (jobs, (ClientData)job);
    QUEUE_ADDED("JobExec", job, "jobs");

    if (nJobs == maxJobs) {
	jobFull = TRUE;
    }
}

/*-
 *-----------------------------------------------------------------------
 * JobMakeArgv --
 *	Create the argv needed to execute the shell for a given job.
 *	
 *
 * Results:
 *
 * Side Effects:
 *
 *-----------------------------------------------------------------------
 */
static void
JobMakeArgv(job, argv)
    Job	    	  *job;
    char	  **argv;
{
    int	    	  argc;
    static char	  args[10]; 	/* For merged arguments */
    
#ifdef MARK_SHELL_ARG0
    static char   arg0[MAXPATHLEN];

    sprintf(arg0, "%.*s (%.*s)",
		  sizeof(arg0) - 4, shellName,
		  sizeof(arg0) - 4 - strlen(shellName), progName);
    argv[0] = arg0;
#else /* !MARK_SHELL_ARG0 */
    argv[0] = shellName;
#endif /* MARK_SHELL_ARG0 */

    argc = 1;

    if ((commandShell->exit && (*commandShell->exit != '-')) ||
	(commandShell->echo && (*commandShell->echo != '-')))
    {
	/*
	 * At least one of the flags doesn't have a minus before it, so
	 * merge them together. Have to do this because the *(&(@*#*&#$#
	 * Bourne shell thinks its second argument is a file to source.
	 * Grrrr. Note the ten-character limitation on the combined arguments.
	 */
	(void)sprintf(args, "-%s%s",
		      ((job->flags & JOB_IGNERR) ? "" :
		       (commandShell->exit ? commandShell->exit : "")),
		      ((job->flags & JOB_SILENT) ? "" :
		       (commandShell->echo ? commandShell->echo : "")));

	if (args[1]) {
	    argv[argc] = args;
	    argc++;
	}
    } else {
	if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
	    argv[argc] = commandShell->exit;
	    argc++;
	}
	if (!(job->flags & JOB_SILENT) && commandShell->echo) {
	    argv[argc] = commandShell->echo;
	    argc++;
	}
    }
    argv[argc] = (char *)NULL;
}

/*-
 *-----------------------------------------------------------------------
 * JobSetupIO --
 *	Set up the I/O streams in the job structure.
 *
 * Results:
 *	TRUE is successful, FALSE and errno set if not.
 *
 * Side Effects:
 *	The streams associated with the job are opened.
 *
 *-----------------------------------------------------------------------
 */
static Boolean
JobSetupIO(job)
    Job	    	  *job;
{
    if (usePipes) {
	int fd[2];

	if (pipe(fd) < 0) {
	    if (errno == EMFILE) {
		if (job->cmdFILE != stdout) {
		    fclose(job->cmdFILE);
		}
		errno = EMFILE;
		return (FALSE);
	    } else {
		Punt ("Couldn't create pipe: %s", strerror(errno));
	    }
	}
	job->inPipe = fd[0];
	job->outPipe = fd[1];
	job->curPos = 0;
	(void)fcntl (job->inPipe, F_SETFD, 1);
	(void)fcntl (job->outPipe, F_SETFD, 1);
	/*
	 * We call read() only after select() or after the
	 * job at the other end has exited, so theoretically we
	 * shouldn't need this.  But very rarely read actually hangs
	 * on the last call to JobDoOutput, so we put the inPipe in
	 * non-blocking mode just in case.
	 */
	(void)fcntl(job->inPipe, F_SETFL, FNDELAY);
    } else {
	static int jobno = 0;  /* job number of catching output in a file */

	sprintf (job->outFile, "%s%02d", tfile, jobno);
	jobno = (jobno + 1) % 100;
	job->outFd = open (job->outFile, O_RDWR|O_CREAT, 0600);
	if (job->outFd < 0) {
	    if (errno == EMFILE) {
		if (job->cmdFILE != stdout) {
		    fclose(job->cmdFILE);
		}
		errno = EMFILE;
		return (FALSE);
	    } else {
		Punt ("Couldn't create output file: %s: %s", 
		      job->outFile, strerror(errno));
	    }
	}
	(void)fcntl (job->outFd, F_SETFD, 1);
	(void)unlink (job->outFile);
    }
    return (TRUE);
}

/*-
 *-----------------------------------------------------------------------
 * JobRestart --
 *	Restart a job that stopped for some reason. If the job stopped
 *	because it migrated home again, we tell the Rmt module to
 *	find a new home for it and make it runnable if Rmt_ReExport
 *	succeeded (if it didn't and the job may be run locally, we
 *	simply resume it). If the job didn't run and can now, we run it.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	jobFull will be set if the job couldn't be run.
 *
 *-----------------------------------------------------------------------
 */
void
JobRestart(job)
    Job 	  *job;    	/* Job to restart */
{
    if (job->flags & JOB_REMIGRATE) {
	if (DEBUG(JOB)) {
	    Debug ("Remigrating %x\n", job->pid);
	}
	if (!Rmt_ReExport(job->pid)) {
	    if (DEBUG(JOB)) {
		Debug ("Couldn't migrate...");
	    }
	    if ((nLocal < maxLocal) ||
		(nLocal == 0) && (maxLocal == 0))
	    {
		/*
		 * Job cannot be remigrated, but there's room on the local
		 * machine, so resume the job and note that another
		 * local job has started.
		 */
		if (DEBUG(JOB)) {
		    Debug ("resuming on local machine\n");
	        }
		KILL(job->pid, SIGCONT);
		nLocal +=1;
		job->flags &= ~(JOB_REMIGRATE|JOB_RESUME);
	    } else {
		/*
		 * Job cannot be restarted. Mark the table as full and
		 * place the job back on the list of stopped jobs.
		 */
		if (DEBUG(JOB)) {
		    Debug ("holding\n");
		}
		(void)Lst_AtFront(stoppedJobs, (ClientData)job);
		QUEUE_ADDED("JobRestart", job, "stoppedJobs");
		jobFull = TRUE;
		if (DEBUG(JOB)) {
		    Debug ("Job queue is full.\n");
		}
		return;
	    }
	} else {
	    /*
	     * Clear out the remigrate and resume flags. If MIGRATE was set,
	     * leave that around for JobFinish to see so it doesn't print out
	     * that the job was continued.
	     */
	    job->flags &= ~(JOB_REMIGRATE|JOB_RESUME);
	}
	
	(void)Lst_AtEnd(jobs, (ClientData)job);
	QUEUE_ADDED("JobRestart", job, "jobs");
	nJobs += 1;
	if (nJobs == maxJobs) {
	    jobFull = TRUE;
	    if (DEBUG(JOB)) {
		Debug ("Job queue is full.\n");
	    }
	}
    } else if (job->flags & JOB_RESTART) {
	/*
	 * Set up the control arguments to the shell. This is based on the
	 * flags set earlier for this job. If the JOB_IGNERR flag is clear,
	 * the 'exit' flag of the commandShell is used to cause it to exit
	 * upon receiving an error. If the JOB_SILENT flag is clear, the
	 * 'echo' flag of the commandShell is used to get it to start echoing
	 * as soon as it starts processing commands. 
	 */
	char	  *argv[4];
	Boolean   noIO;

	JobMakeArgv(job, argv);
	
	/*
	 * Reopen the job pipe if necessary
	 */
	if (usePipes && (job->inPipe == job->outPipe)) {
	    (void)close(job->inPipe);
	    job->inPipe = job->outPipe = -1;
	    noIO = !JobSetupIO(job);
	} else {
	    noIO = FALSE;
	}

	if (DEBUG(JOB)) {
	    Debug ("Restarting %s...", job->node->name);
	}

	if (noIO ||
	    (job->node->type & OP_NOEXPORT) ||
#ifdef RMT_NO_EXEC
	    !Rmt_Export(shellPath, argv, job)
#else
	    !Rmt_Begin(shellPath, argv, job->node)
#endif
	    )
	{
	    if (noIO ||
#ifdef sparc	    	    /* KLUDGE */
		(job->node->type & OP_M68020) ||
#endif
		(job->node->type & OP_EXPORT))
	    {
		/*
		 * Can't be exported and not allowed to run locally -- let it
		 * wait for awhile and then try again.
		 */
		if (Rmt_Defer(job)) {
		    if (DEBUG(JOB)) {
			Debug ("deferred\n");
		    }
		    (void)Lst_AtEnd(stoppedJobs, (ClientData)job);
		    QUEUE_ADDED("JobRestart", job, "stoppedJobs");
		} else {
		    WAIT_STATUS status;

		    if (DEBUG(JOB)) {
			Debug ("finishing\n");
		    }
		    Error ("Couldn't export `%s' -- giving up",
			   job->node->name);
		    job->flags &= ~JOB_RESTART;
		    job->flags &= ~JOB_RETRYERR;
		    WSTATUS(status) = 1<<8; /* status.w_retcode = 1 */
		    JobFinish(job, status);
		}
		return;
	    } else if ((nLocal >= maxLocal) &&
		 (nLocal > 0 || maxLocal > 0) &&
		 ! (job->flags & JOB_SPECIAL))
	    {
		/*
		 * Can't be exported and not allowed to run locally -- leave it
		 * on the hold queue and mark the table full
		 */
		if (Rmt_Defer(job)) {
		    if (DEBUG(JOB)) {
			Debug ("deferred\n");
		    }
		} else {
		    if (DEBUG(JOB)) {
			Debug ("holding\n");
		    }
		    jobFull = TRUE;
		}
		(void)Lst_AtFront(stoppedJobs, (ClientData)job);
		QUEUE_ADDED("JobRestart", job, "stoppedJobs");
		if (DEBUG(JOB)) {
		    Debug ("Job queue is full.\n");
		}
		return;
	    } else {
		/*
		 * Job may be run locally.  Clear the restart flag and remove
		 * it from the hold queue.
		 */
		if (DEBUG(JOB)) {
		    Debug ("running locally\n");
		}
		job->flags &= ~JOB_RESTART;
		job->flags &= ~JOB_REMOTE;
	    }
	} else {
	    /*
	     * Can be exported. Hooray!
	     */
	    if (DEBUG(JOB)) {
		Debug ("exporting\n");
	    }
	    job->flags &= ~JOB_RESTART;
	    job->flags |= JOB_REMOTE;
	}
	JobExec(job, argv);
    } else {
	/*
	 * The job has stopped and needs to be restarted. Why it stopped,
	 * we don't know...
	 */
	if (DEBUG(JOB)) {
	    Debug ("Resuming %s...", job->node->name);
	}
	if (((job->flags & JOB_REMOTE) ||
	     (nLocal < maxLocal) ||
	     (nLocal == 0) && (maxLocal == 0) || 
	     (((job->flags & JOB_SPECIAL) ||
	       (job->node->type & OP_NOEXPORT)))) &&
	    (nJobs != maxJobs))
	{
	    /*
	     * If the job is remote, it's ok to resume it as long as the
	     * maximum concurrency won't be exceeded. If it's local and
	     * we haven't reached the local concurrency limit already (or the
	     * job must be run locally and maxLocal is 0), it's also ok to
	     * resume it.
	     */
	    Boolean error;
	    WAIT_STATUS status;
	    LstNode jnode;

	    /*
	     * Because Rmt_Signal may trigger the signal handler we make
	     * sure the job is recorded in the jobs list first.
	     */
	    (void)Lst_AtEnd(jobs, (ClientData)job);
	    QUEUE_ADDED("JobRestart", job, "jobs");
	    jnode = Lst_Last(jobs);

	    /*
	     * Increment here so count is accurate if job gets killed
	     * while waiting for Rmt_Signal().
	     */
	    nJobs += 1;

#ifdef RMT_WANTS_SIGNALS
	    if (job->flags & JOB_REMOTE) {
		error = !Rmt_Signal(job, SIGCONT);
		/*
		 * There is a chance the job has terminated while we
		 * were sending the signal (if it was remote).
		 * Therefore, check that the job is still on the queue.
		 */
		if (Lst_Member(jobs, job) == NILLNODE) {
		    if (DEBUG(QUEUE)) {
			Debug("JobRestart: %s already gone\n", job->node->name);
		    }
		    return;
		}
	    } else
#endif	/* RMT_WANTS_SIGNALS */
		error = (KILL(job->pid, SIGCONT) != 0);

	    if (!error) {
		/*
		 * Make sure the user knows we've continued the beast and
		 * actually put the thing in the job table.
		 */
		if (! (job->flags & JOB_REMOTE)) {
		    nLocal += 1;
		}
		if (nJobs == maxJobs) {
		    jobFull = TRUE;
		    if (DEBUG(JOB)) {
			Debug ("Job queue is full.\n");
		    }
		}
		job->flags |= JOB_CONTINUING;
		WSTATUS(status) = SIGCONT; /* status.w_termsig = SIGCONT; */
		JobFinish(job, status);
		
		job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
		if (DEBUG(JOB)) {
		    Debug ("done\n");
		}
	    } else {
		Error("Couldn't resume `%s': %s", job->node->name,
		      strerror(errno));

		(void)Lst_Remove(jobs, jnode);
		QUEUE_REMOVED("JobRestart", job, "jobs");
		nJobs -= 1;

		WSTATUS(status) = 1<<8; /* status.w_retcode = 1; */
		JobFinish(job, status);
	    }
	} else {
	    /*
	     * Job cannot be restarted. Mark the table as full and
	     * place the job back on the list of stopped jobs.
	     */
	    if (DEBUG(JOB)) {
		Debug ("table full\n");
	    }
	    (void)Lst_AtFront(stoppedJobs, (ClientData)job);
	    QUEUE_ADDED("JobRestart", job, "stoppedJobs");
	    jobFull = TRUE;
	    if (DEBUG(JOB)) {
		Debug ("Job queue is full.\n");
	    }
	}
    }
}

/*-
 *-----------------------------------------------------------------------
 * JobStart  --
 *	Start a target-creation process going for the target described
 *	by the graph node gn. 
 *
 * Results:
 *	JOB_ERROR if there was an error in the commands, JOB_FINISHED
 *	if there isn't actually anything left to do for the job and
 *	JOB_RUNNING if the job has been started. JOB_NOTNOW indicates
 *	that the job cannot be start at this time because of some
 *	resource limitation (typically file descriptor shortage).
 *	Also, errno is set in that case to indicate the source of the
 *	problem, for use in error messages, etc.
 *
 * Side Effects:
 *	A new Job node is created and added to the list of running
 *	jobs. PMake is forked and a child shell created.
 *-----------------------------------------------------------------------
 */
static int
JobStart (gn, flags, previous)
    GNode         *gn;	      /* target to create */
    short	  flags;      /* flags for the job to override normal ones.
			       * e.g. JOB_SPECIAL or JOB_IGNDOTS */
    Job 	  *previous;  /* The previous Job structure for this node,
			       * if any. */
{
    register Job  *job;       /* new job descriptor */
    char	  *argv[4];   /* Argument vector to shell */
    Boolean	  cmdsOK;     /* true if the nodes commands were all right */
    Boolean 	  local;      /* Set true if the job was run locally */
    Boolean 	  noExec;     /* Set true if we decide not to run the job */

    if (previous != (Job *)NULL) {
	previous->flags &= ~ (JOB_FIRST|JOB_IGNERR|JOB_SILENT|JOB_REMOTE);
	if (previous->rmtHost) {
	    free(previous->rmtHost);
	}
	job = previous;
    } else {
	job = (Job *) emalloc (sizeof (Job));
	flags |= JOB_FIRST;
    }

    /*
     * Mark the new job as having no process yet.  This allows us to tell
     * suspended from unstarted jobs on the stoppedJobs queue.
     */
    job->pid = 0;
    job->rmtID = (char *)0;
    job->rmtHost = (char *)0;
    job->node = gn;
    job->tailCmds = NILLNODE;

    /*
     * Set the initial value of the flags for this job based on the global
     * ones and the node's attributes... Any flags supplied by the caller
     * are also added to the field.
     */
    job->flags = 0;
    if (Targ_Ignore (gn)) {
	job->flags |= JOB_IGNERR;
    }
    if (Targ_Silent (gn)) {
	job->flags |= JOB_SILENT;
    }
    if (gn->type & OP_RESTART) {
	job->flags |= JOB_RETRYERR;
    }
    job->flags |= flags;

    /*
     * Check the commands now so any attributes from .DEFAULT have a chance
     * to migrate to the node
     */
    if (!backwards || (job->flags & JOB_FIRST)) {
	cmdsOK = Job_CheckCommands(gn, Error);
    } else {
	cmdsOK = TRUE;
    }
    
    /*
     * We're serious here, but if the commands were bogus, we're
     * also dead...
     */
    if (!cmdsOK) {
	if (keepgoing) {
	    if (job->rmtHost) free(job->rmtHost);
	    free((Address)job);
	    return(JOB_ERROR);
	} else{
	    DieHorribly();
	}
    }
    
    /*
     * If the -n flag wasn't given, we open up OUR (not the child's)
     * temporary file to stuff commands in it. The thing is rd/wr so we don't
     * need to reopen it to feed it to the shell. If the -n flag *was* given,
     * we just set the file to be stdout. Cute, huh?
     */
    if (((gn->type & OP_MAKE) ||
	(!noExecute && !touchFlag && !queryFlag)))
    {
	job->cmdFILE = fopen (tfile, "w+");
	if (job->cmdFILE == (FILE *) NULL) {
	    if (errno == EMFILE) {
		/*
		 * Too many open files -- try again later
		 */
		return (JOB_NOTNOW);
	    } else {
		Punt ("Could not open %s: %s", tfile, strerror(errno));
	    }
	}
	fcntl(fileno(job->cmdFILE), F_SETFD, 1);
	/*
	 * Send the commands to the command file, flush all its buffers then
	 * rewind and remove the thing.
	 */
	noExec = FALSE;

	if (backwards) {
	    /*
	     * Be compatible: If this is the first time for this node,
	     * verify its commands are ok and open the commands list for
	     * sequential access by later invocations of JobStart.
	     * Once that is done, we take the next command off the list
	     * and print it to the command file. If the command was an
	     * ellipsis, note that there's nothing more to execute.
	     */
	    if ((job->flags&JOB_FIRST) && (Lst_Open(gn->commands) != SUCCESS)){
		cmdsOK = FALSE;
	    } else {
		LstNode	ln = Lst_Next (gn->commands);
		    
		if ((ln == NILLNODE) ||
		    JobPrintCommand ((char *)Lst_Datum (ln), job))
		{
		    noExec = TRUE;
		    Lst_Close (gn->commands);
		}
		if (noExec && !(job->flags & JOB_FIRST)) {
		    /*
		     * If we're not going to execute anything, the job
		     * is done and we need to close down the various
		     * file descriptors we've opened for output, then
		     * call JobDoOutput to catch the final characters or
		     * send the file to the screen... Note that the i/o streams
		     * are only open if this isn't the first job.
		     * Note also that this could not be done in
		     * Job_CatchChildren b/c it wasn't clear if there were
		     * more commands to execute or not...
		     */
		    if (usePipes) {
			if (job->outPipe != job->inPipe) {
			    (void)close (job->outPipe);
			}
			JobDoOutput (job, TRUE);
			(void)close (job->inPipe);
		    } else {
			JobDoOutput (job, TRUE);
			(void)close (job->outFd);
		    }
		}
	    }
	} else {
	    /*
	     * We can do all the commands at once. hooray for sanity
	     */
	    numCommands = 0;
	    Lst_ForEach (gn->commands, JobPrintCommand, (ClientData)job);
	    
	    /*
	     * If we didn't print out any commands to the shell script,
	     * there's not much point in executing the shell, is there?
	     */
	    if (numCommands == 0) {
		noExec = TRUE;
	    }
	}
    } else if (noExecute && !touchFlag && !queryFlag) {
	/*
	 * Not executing anything -- just print all the commands to stdout
	 * in one fell swoop. This will still set up job->tailCmds correctly.
	 */
	printf (targFmt, gn->name);
	job->cmdFILE = stdout;
	/*
	 * Only print the commands if they're ok, but don't die if they're
	 * not -- just let the user know they're bad and keep going. It
	 * doesn't do any harm in this case and may do some good.
	 */
	if (cmdsOK) {
	    Lst_ForEach(gn->commands, JobPrintCommand, (ClientData)job);
	}
	/*
	 * Don't execute the shell, thank you.
	 */
	noExec = TRUE;
    } else {
	/*
	 * Just touch the target and note that no shell should be executed.
	 * Set cmdFILE to stdout to make life easier. Check the commands, too,
	 * but don't die if they're no good -- it does no harm to keep working
	 * up the graph.
	 */
	job->cmdFILE = stdout;
    	Job_Touch (gn, job->flags&JOB_SILENT);
	noExec = TRUE;
    }

    /*
     * If we're not supposed to execute a shell, don't. 
     */
    if (noExec) {
	/*
	 * Unlink and close the command file if we opened one
	 */
	if (job->cmdFILE != stdout) {
	    (void) unlink (tfile);
	    fclose(job->cmdFILE);
	} else {
	    fflush (stdout);
	}

	/*
	 * We only want to work our way up the graph if we aren't here because
	 * the commands for the job were no good.
	 */
	if (cmdsOK) {
	    if (aborting == 0) {
		if (job->tailCmds != NILLNODE) {
		    Lst_ForEachFrom(job->node->commands, job->tailCmds,
				    JobSaveCommand,
				    (ClientData)job->node);
		}
		job->node->made = MADE;
		Make_Update(job->node);
		Make_FreeCommands(job->node);
	    }
	    if (job->rmtHost) free(job->rmtHost);
	    free((Address)job);
	    return(JOB_FINISHED);
	} else {
	    if (job->rmtHost) free(job->rmtHost);
	    free((Address)job);
	    return(JOB_ERROR);
	}
    } else {
	fflush (job->cmdFILE);
	(void) unlink (tfile);
    }

    /*
     * Set up the control arguments to the shell. This is based on the flags
     * set earlier for this job.
     */
    JobMakeArgv(job, argv);

    /*
     * If we're using pipes to catch output, create the pipe by which we'll
     * get the shell's output. If we're using files, print out that we're
     * starting a job and then set up its temporary-file name. This is just
     * tfile with two extra digits tacked on -- jobno.
     */
    if (!backwards || (job->flags & JOB_FIRST)) {
	if (!usePipes) {
	    printf (TARG_FMT, gn->name);
	    fflush (stdout);
	}
	if (!JobSetupIO(job)) {
	    return (JOB_NOTNOW);
	}
    } else {
	/*
	 * Continuing a list of commands in -B mode: check that the
	 * previous command hasn't closed our pipe as a result of
	 * remote execution, and reopen it if necessary.
	 */
	if (usePipes && (job->inPipe == job->outPipe)) {
	    if (!JobSetupIO(job)) {
		(void)close(job->inPipe);
		job->inPipe = job->outPipe = -1;
		return (JOB_NOTNOW);
	    }
	}
    }

    /*
     * If the user prefers local execution, let the rmt module know that.
     */
    if (useLocal) {
	gn->type |= OP_USELOCAL;
    }

    if (!(gn->type & OP_NOEXPORT)) {
#ifdef RMT_NO_EXEC
	local = !Rmt_Export(shellPath, argv, job);
#else
	local = !Rmt_Begin (shellPath, argv, gn);
#endif /* RMT_NO_EXEC */
	if (!local) {
	    job->flags |= JOB_REMOTE;
	}
    } else {
	local = TRUE;
    }

    if (local && (
#ifdef sparc	/* KLUDGE */
	(gn->type & OP_M68020) ||
#endif
	(gn->type & OP_EXPORT)))
    {
	/*
	 * Can't be exported and not allowed to run locally -- defer
	 * it and try again later.
	 */
	if (DEBUG(JOB)) {
	    Debug ("Deferring job to be exported.\n");
	}
	if (Rmt_Defer (job)) {
	    if (DEBUG(JOB)) {
		Debug ("Deferring job to be exported.\n");
	    }

	    if (usePipes) {
		Job_PrintTarget (job, stdout);
	    }
	    fprintf (stderr, "*** export failed (deferring)\n");
	    fflush (stderr);
	} else {
	    /*
	     * We want to let the job terminate with an error.
	     * Pretend it can be started and put it on the hold queue,
	     * from where it will be given one more try by JobRestart.
	     */
	    if (DEBUG(JOB)) {
		Debug ("Job cannot be deferred.\n");
	    }
	}
	job->flags |= JOB_RESTART;
	(void)Lst_AtEnd(stoppedJobs, (ClientData)job);
	QUEUE_ADDED("JobStart", job, "stoppedJobs");
    } else if (local && (
	((nLocal >= maxLocal) &&
	 (nLocal > 0 || maxLocal > 0) &&
	 !(job->flags & JOB_SPECIAL) &&
	 !(gn->type & OP_NOEXPORT))))
    {
	/*
	 * The job can only be run locally, but we've hit the limit of
	 * local concurrency, so put the job on hold until some other job
	 * finishes. Note that the special jobs (.BEGIN, .INTERRUPT and .END)
	 * may be run locally even when the local limit has been reached
	 * (e.g. when maxLocal == 0), though they will be exported if at
	 * all possible. In addition, any target marked with .NOEXPORT will
	 * be run locally if maxLocal is 0.
	 */
	if (Rmt_Defer(job)) {
	    if (DEBUG(JOB)) {
		Debug ("Deferring job to be exported.\n");
	    }
	    /*
	     * Don't print deferral notice here since the job can always
	     * be run locally later.
	     */
	} else {
	    if (DEBUG(JOB)) {
		Debug ("Can only run job locally.\n");
	    }
	    jobFull = TRUE;
	}
	job->flags |= JOB_RESTART;
	(void)Lst_AtEnd(stoppedJobs, (ClientData)job);
	QUEUE_ADDED("JobStart", job, "stoppedJobs");
    } else {
	if ((nLocal >= maxLocal) && local) {
	    /*
	     * If we're running this job locally as a special case (see above),
	     * at least say the table is full.
	     */
	    jobFull = TRUE;
	    if (DEBUG(JOB)) {
		Debug ("Local job queue is full.\n");
	    }
	}
	JobExec(job, argv);
    }
    return(JOB_RUNNING);
}

/*-
 *-----------------------------------------------------------------------
 * JobDoOutput  --
 *	This function is called at different times depending on
 *	whether the user has specified that output is to be collected
 *	via pipes or temporary files. In the former case, we are called
 *	whenever there is something to read on the pipe. We collect more
 *	output from the given job and store it in the job's outBuf. If
 *	this makes up a line, we print it tagged by the job's identifier,
 *	as necessary.
 *	If output has been collected in a temporary file, we open the
 *	file and read it line by line, transfering it to our own
 *	output channel until the file is empty. At which point we
 *	remove the temporary file.
 *	In both cases, however, we keep our figurative eye out for the
 *	'noPrint' line for the shell from which the output came. If
 *	we recognize a line, we don't print it. If the command is not
 *	alone on the line (the character after it is not \0 or \n), we
 *	do print whatever follows it.
 *
 * Results:
 *	None
 *
 * Side Effects:
 *	curPos may be shifted as may the contents of outBuf.
 *-----------------------------------------------------------------------
 */
void
JobDoOutput (job, finish)
    register Job   *job;	  /* the job whose output needs printing */
    Boolean	   finish;	  /* TRUE if this is the last time we'll be
				   * called for this job */
{
    Boolean       gotNL = FALSE;  /* true if got a newline */
    register int  nr;	      	  /* number of bytes read */
    register int  i;	      	  /* auxiliary index into outBuf */
    register int  max;	      	  /* limit for i (end of current data) */
    int		  nRead;      	  /* (Temporary) number of bytes read */

    FILE      	  *oFILE;	  /* Stream pointer to shell's output file */
    char          inLine[132];

    
    if (usePipes) {
	/*
	 * Read as many bytes as will fit in the buffer.
	 */
end_loop:
	
	do {
	    nRead = read (job->inPipe, &job->outBuf[job->curPos],
			     JOB_BUFSIZE - job->curPos);
	} while ((nRead < 0) && (errno == EINTR));
	if (nRead < 0) {
	    if (DEBUG(JOB)) {
		perror("JobDoOutput(piperead)");
	    }
	    nr = 0;
	} else {
	    nr = nRead;
	}

	/*
	 * If we hit the end-of-file (the job is dead), we must flush its
	 * remaining output, so pretend we read a newline if there's any
	 * output remaining in the buffer.
	 * Also clear the 'finish' flag so we stop looping.
	 */
	if ((nr == 0) && (job->curPos != 0)) {
	    job->outBuf[job->curPos] = '\n';
	    nr = 1;
	    finish = FALSE;
	} else if (nr == 0) {
	    finish = FALSE;
	}
	
	/*
	 * Look for the last newline in the bytes we just got. If there is
	 * one, break out of the loop with 'i' as its index and gotNL set
	 * TRUE. 
	 */
	max = job->curPos + nr;
	for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
	    if (job->outBuf[i] == '\n') {
		gotNL = TRUE;
		break;
	    } else if (job->outBuf[i] == '\0') {
		/*
		 * Why?
		 */
		job->outBuf[i] = ' ';
	    }
	}
	
	if (!gotNL) {
	    job->curPos += nr;
	    if (job->curPos == JOB_BUFSIZE) {
		/*
		 * If we've run out of buffer space, we have no choice
		 * but to print the stuff. sigh. 
		 */
		gotNL = TRUE;
		i = job->curPos;
	    }
	}
	if (gotNL) {
	    /*
	     * Need to send the output to the screen. Null terminate it
	     * first, overwriting the newline character if there was one.
	     * So long as the line isn't one we should filter (according
	     * to the shell description), we print the line, preceeded
	     * by a target banner if this target isn't the same as the
	     * one for which we last printed something.
	     * The rest of the data in the buffer are then shifted down
	     * to the start of the buffer and curPos is set accordingly. 
	     */
	    job->outBuf[i] = '\0';
	    if (i >= job->curPos) {
		register char	*cp, *ecp;

		cp = job->outBuf;
		if (!backwards && commandShell->noPrint) {
		    ecp = Str_FindSubstring(job->outBuf,
					    commandShell->noPrint);
		    while ((ecp != (char *)NULL) && 
			   (ecp[commandShell->noPLen] == '\0' ||
			    isspace(ecp[commandShell->noPLen])))
		    {
			if (cp != ecp) {
			    *ecp = '\0';
			    Job_PrintTarget (job, stdout);

			    /*
			     * The only way there wouldn't be a newline after
			     * this line is if it were the last in the buffer.
			     * however, since the non-printable comes after it,
			     * there must be a newline, so we don't print one.
			     */
			    printf ("%s", cp);
			}
			cp = ecp + commandShell->noPLen;
			if (cp != &job->outBuf[i]) {
			    /*
			     * Still more to print, look again after skipping
			     * the whitespace following the non-printable
			     * command....
			     */
			    while (isspace(*cp)) { cp++; }
			    ecp = Str_FindSubstring (cp, commandShell->noPrint);
			} else {
			    break;
			}
		    }
		}

		/*
		 * There's still more in that thar buffer. This time, though,
		 * we know there's no newline at the end, so we add one of
		 * our own free will.
		 */
		if (*cp != '\0') {
		    Job_PrintTarget (job, stdout);
		    printf ("%s\n", cp);
		}

		fflush (stdout);
	    }
	    if (i < max - 1) {
		memmove(job->outBuf,        /* shift the remaining */
		        &job->outBuf[i + 1],/* characters down */
		        max - (i + 1));
		job->curPos = max - (i + 1);
		
	    } else {
		/*
		 * We have written everything out, so we just start over
		 * from the start of the buffer. No copying. No nothing.
		 */
		job->curPos = 0;
	    }
	}
	if (finish) {
	    /*
	     * If the finish flag is true, we must loop until we hit
	     * end-of-file on the pipe. This is guaranteed to happen eventually
	     * since the other end of the pipe is now closed (we closed it
	     * explicitly and the child has exited). When we do get an EOF,
	     * finish will be set FALSE and we'll fall through and out.
	     */
	    goto end_loop;
	}
    } else {
	/*
	 * We've been called to retrieve the output of the job from the
	 * temporary file where it's been squirreled away. This consists of
	 * opening the file, reading the output line by line, being sure not
	 * to print the noPrint line for the shell we used, then close and
	 * remove the temporary file. Very simple.
	 *
	 * Change to read in blocks and do FindSubString type things as for
	 * pipes? That would allow for "@echo -n..."
	 */
	/* printf ("Results of making %s:\n", job->node->name); */
	printf (TARG_FMT, job->node->name);
	oFILE = fdopen (job->outFd, "r");
	if (oFILE != (FILE *) NULL) {
	    rewind (oFILE);
	    while (fgets (inLine, sizeof(inLine), oFILE) != NULL) {
		register char	*cp, *ecp, *endp;

		cp = inLine;
		endp = inLine + strlen(inLine);
		if (endp[-1] == '\n') {
		    *--endp = '\0';
		}
		if (!backwards && commandShell->noPrint) {
		    ecp = Str_FindSubstring(cp, commandShell->noPrint);
		    while ((ecp != (char *)NULL) &&
			   (ecp[commandShell->noPLen] == '\0' ||
			    isspace(ecp[commandShell->noPLen])))
		    {
			if (cp != ecp) {
			    *ecp = '\0';
			    /*
			     * The only way there wouldn't be a newline after
			     * this line is if it were the last in the buffer.
			     * however, since the non-printable comes after it,
			     * there must be a newline, so we don't print one.
			     */
			    printf ("%s", cp);
			}
			cp = ecp + commandShell->noPLen;
			if (cp != endp) {
			    /*
			     * Still more to print, look again after skipping
			     * the whitespace following the non-printable
			     * command....
			     */
			    while (isspace(*cp)) { cp++; }
			    ecp = Str_FindSubstring(cp, commandShell->noPrint);
			} else {
			    break;
			}
		    }
		}

		/*
		 * There's still more in that thar buffer. This time, though,
		 * we know there's no newline at the end, so we add one of
		 * our own free will.
		 */
		if (*cp != '\0') {
		    printf ("%s\n", cp);
		}
	    }
	    fclose (oFILE);
	} else {
	    Error ("Could not open output file (%s)", job->outFile);
	}
    }
    fflush(stdout);
}

/*-
 *-----------------------------------------------------------------------
 * Job_CatchChildren --
 *	Handle the exit of a child. Called from Make_Make.
 *
 * Results:
 *	none.
 *
 * Side Effects:
 *	The job descriptor is removed from the list of children.
 *
 * Notes:
 *	We do waits, blocking or not, according to the wisdom of our
 *	caller, until there are no more children to report. For each
 *	job, call JobFinish to finish things off. This will take care of
 *	putting jobs on the stoppedJobs queue.
 *
 *-----------------------------------------------------------------------
 */
void
Job_CatchChildren (block)
    Boolean	  block;    	/* TRUE if should block on the wait. */
{
    int    	  pid;	    	/* pid of dead child */
    register Job  *job;	    	/* job descriptor for dead child */
    LstNode       jnode;    	/* list element for finding job */
    WAIT_STATUS	  status;   	/* Exit/termination status */

#ifdef RMT_WILL_WATCH
    /*
     * We cannot block even when the caller tells us to since that would
     * disable interrupt handling.
     */
    block = FALSE;
#endif /* RMT_WILL_WATCH */

    while (1) {
	/*
	 * Reap a child, either exited or stopped.
	 */
	pid = WAIT3(&status, (block?0:WNOHANG)|WUNTRACED, NULL);

	if ((pid == 0) ||
	    (pid < 0) && (errno == ECHILD))
	{
	    /*
	     * No children ready yet.
	     */
	    break;
	} else if ((pid < 0) && (errno == EINTR)) {
	   /*
	    * Try again.
	    */
	   continue;
	} else if (pid < 0) {
	   if (DEBUG(JOB)) {
		perror("wait");
	   }
	   break;
	}

	if (DEBUG(JOB)) {
	    Debug ("Process %d %sed.\n",
	           pid, (WIFSTOPPED(status) ? "stopp" :
	                 (WIFSIGNALED(status) &&	/* Sprite only */
			  (WTERMSIG(status) == SIGCONT) ? "continu" :
	                  (WIFSIGNALED(status) ? "kill" : "exit"))));
	}
	    

	jnode = Lst_Find (jobs, (ClientData)pid, JobCmpPid);
	if (jnode == NILLNODE) {
	    jnode = Lst_Find(stoppedJobs, (ClientData)pid, JobCmpPid);
	    if (jnode == NILLNODE) {
		Error ("Child (%d) not in table?", pid);
		continue;
	    }
	    job = (Job *)Lst_Datum(jnode);
	    if (!WIFSTOPPED(status)) {
		QUEUE_REMOVED("Job_CatchChildren", job, "stoppedJobs");
		(void)Lst_Remove(stoppedJobs, jnode);
	    }
	} else {
	    job = (Job *) Lst_Datum (jnode);
	    QUEUE_REMOVED("Job_CatchChildren", job, "jobs");
	    (void)Lst_Remove (jobs, jnode);

	    if (WIFSTOPPED(status)) {
		(void)Lst_AtFront(stoppedJobs, (ClientData)job);
		QUEUE_ADDED("Job_CatchChildren", job, "stoppedJobs");
	    } else if (usePipes) {
		/*
		 * Stop transfering output for this job
		 */
#ifdef RMT_WILL_WATCH
		Rmt_Ignore(job->inPipe);
#else
		FD_CLR(job->inPipe, &outputs);
#endif /* RMT_WILL_WATCH */
	    }

	    nJobs -= 1;

	    if (jobFull && DEBUG(JOB)) {
		Debug ("Job queue is no longer full.\n");
	    }
	    jobFull = FALSE;
	
	    if (job->flags & JOB_REMOTE) {
		Rmt_Done (job->rmtID);
	    } else {
		nLocal -= 1;
	    }
	}

	JobFinish (job, status);
    }
}

/*-
 *-----------------------------------------------------------------------
 * Job_CatchOutput --
 *	Catch the output from our children, if we're using
 *	pipes do so. Otherwise just block time until we get a
 *	signal (most likely a SIGCHLD) since there's no point in
 *	just spinning when there's nothing to do and the reaping
 *	of a child can wait for a while. 
 *
 * Results:
 *	None 
 *
 * Side Effects:
 *	Output is read from pipes if we're piping.
 * -----------------------------------------------------------------------
 */
void
Job_CatchOutput ()
{
#ifdef RMT_WILL_WATCH
    int	    	  	  pnJobs;   	/* Previous nJobs */

    pnJobs = nJobs;

    fflush(stdout);
    /*
     * It is possible for us to be called with nJobs equal to 0. This happens
     * if all the jobs finish and a job that is stopped cannot be run
     * locally (eg if maxLocal is 0) and cannot be exported. The job will
     * be placed back on the stoppedJobs queue, Job_Empty() will return false,
     * Make_Run will call us again when there's nothing for which to wait.
     * nJobs never changes, so we loop forever. Hence the check. It could
     * be argued that we should sleep for a bit so as not to swamp the
     * exportation system with requests. Perhaps we should.
     *
     * NOTE: IT IS THE RESPONSIBILITY OF Rmt_Wait TO CALL Job_CatchChildren
     * IN A TIMELY FASHION TO CATCH ANY LOCALLY RUNNING JOBS THAT EXIT.
     */
    while ((nJobs > 0 || jobFull || (signals > 0)) && pnJobs == nJobs) {
	Rmt_Wait();
    }
#else
    fflush(stdout);
    if (usePipes) {
	int           	  nfds;
	struct timeval	  timeout;
	fd_set            readfds;
	register LstNode  ln;
	register Job   	  *job;

	readfds = outputs;
	timeout.tv_sec = SEL_SEC;
	timeout.tv_usec = SEL_USEC;

	if ((nfds = select (FD_SETSIZE, &readfds, (fd_set *) 0, (fd_set *) 0, &timeout)) < 0)
	{
	    return;
	} else {
	    if (Lst_Open (jobs) == FAILURE) {
		Punt ("Cannot open job table");
	    }
	    while (nfds && (ln = Lst_Next (jobs)) != NILLNODE) {
		job = (Job *) Lst_Datum (ln);
		if (FD_ISSET(job->inPipe, &readfds)) {
		    JobDoOutput (job, FALSE);
		    nfds -= 1;
		}
	    }
	    Lst_Close (jobs);
	}
    }
#endif /* RMT_WILL_WATCH */
}

/*-
 *-----------------------------------------------------------------------
 * Job_Make --
 *	Start the creation of a target. Basically a front-end for
 *	JobStart used by the Make module.
 *
 * Results:
 *	True if the job was started, False it wasn't and should be
 *	delayed.
 *
 * Side Effects:
 *	Another job is started, or else jobFull is set.
 *
 *-----------------------------------------------------------------------
 */
Boolean
Job_Make (gn)
    GNode   *gn;
{
    making = TRUE;

    if (JobStart (gn, 0, (Job *)NULL) == JOB_NOTNOW) {
	jobFull = TRUE;
	maxJobs = nJobs + Lst_Length(stoppedJobs);

	if (maxJobs > 1) {
	    Error("%s: limiting parallel jobs to %d", strerror(errno), maxJobs);
	} else {
	    Punt("%s: cannot continue", strerror(errno));
	}

	return (FALSE);
    } else {
	return (TRUE);
    }
}

/*-
 *-----------------------------------------------------------------------
 * Job_ShellPath --
 *	Build and return the path to the current shell.
 *
 * Results:
 *	Newly allocated string containing full shell path, or NULL
 *	if the current shell is unknown.
 *
 * Side Effects:
 *	Job_ParseShell may be called to interpreted a new SHELL value.
 *	The shellName and shellPath are set if known.
 *-----------------------------------------------------------------------
 */
char *
Job_ShellPath (checkSHELL)
    Boolean	checkSHELL;	/* Whether to recompute value from SHELL */
{
    /*
     * shellChanged indicates that the SHELL variable value might have
     * changed since last time, so we have to recompute it and sync
     * the command shell spec with it, using a call to Job_ParseShell.
     * Note that this will likely cause a recursive call to Job_ShellPath,
     * but that's how it works ...
     */
    if (checkSHELL && shellChanged) {
	char *val;

	val = Var_Value ("SHELL", VAR_CMD);
	if (val == (char *)NULL) {
	    /*
	     * SHELL was #undef'ed -- reset shell to default.
	     */
	    if (DEBUG(JOB) || DEBUG(PARSE)) {
		Debug ("SHELL undef'ed -- reverting to default\n");
	    }
	    Job_ParseShell ("");
	} else if (strchr(val, '$') == (char *)NULL) {
	    char *shellSpec = emalloc (strlen(val) + 8);
	    /*
	     * No recursive expansion required -- this also means
	     * the value can only change again if SHELL itself is
	     * reassigned to.
	     */
	    if (DEBUG(JOB) || DEBUG(PARSE)) {
		Debug ("SHELL constant -- setting shellPath\n");
	    }
	    sprintf(shellSpec, "path=\"%s\"", val);
	    (void)Job_ParseShell (shellSpec);
	    free (shellSpec);
	} else {
	    static char shellSpec[] = "path=\"${SHELL}\"";
	    /*
	     * The variable contains other substitutions.  Expand them
	     * and record that it will have to be reexpanded next time we
	     * are called.
	     */
	    if (DEBUG(JOB) || DEBUG(PARSE)) {
		Debug ("SHELL variable -- expanding and setting shellPath\n");
	    }
	    val = Var_Subst (shellSpec, VAR_CMD, TRUE);
	    (void)Job_ParseShell (val);
	    free (val);
	    shellChanged = TRUE;
	}
    }

    /*
     * commandShell is guaranteed to point to the current shell spec at
     * this point.  Fill in shellPath and shellName if possible and not
     * already set.
     */
    if (shellPath == (char *)NULL) {
	if (commandShell->name != (char *) NULL) {
	    /*
	     * The user didn't specify a shell to use, so we are using the
	     * default one... Both the absolute path and the last component
	     * must be set. The last component is taken from the 'name' field
	     * of the default shell description pointed-to by commandShell.
	     * All default shells are located in DEFSHELLDIR.
	     */
	    shellName = commandShell->name;
	    shellPath = Str_Concat (DEFSHELLDIR, shellName, STR_ADDSLASH);
	}
    }
    return (shellPath);
}

/*-
 *-----------------------------------------------------------------------
 * Job_Init --
 *	Initialize the process module
 *
 * Results:
 *	none
 *
 * Side Effects:
 *	lists and counters are initialized
 *-----------------------------------------------------------------------
 */
void
Job_Init (maxproc, maxlocal)
    int           maxproc;  /* the greatest number of jobs which may be
			     * running at one time */
    int	    	  maxlocal; /* the greatest number of local jobs which may
			     * be running at once. */
{
    GNode         *begin;     /* node for commands to do at the very start */

    sprintf (tfile, "/tmp/make%05d", getpid());

    jobs =  	  Lst_Init (FALSE);
    stoppedJobs = Lst_Init(FALSE);
    maxJobs = 	  (maxproc < 1) ? 1 : maxproc;
    maxLocal = 	  (maxlocal < 0) ? 0 : maxlocal;
    nJobs = 	  0;
    nLocal = 	  0;
    jobFull = 	  FALSE;
    making =	  FALSE;

    aborting = 	  0;
    errors = 	  0;

    if (maxJobs == 1 ||
	noExport && maxLocal <= 1)
    {
	/*
	 * If only one job can run at a time, there's no need for a banner,
	 * no is there?
	 */
	targFmt = "";
    } else {
	targFmt = TARG_FMT;
    }
    
    /*
     * Initialize the shell path if not already done elsewhere.
     */
    (void)Job_ShellPath (TRUE);

    if (commandShell->exit == (char *)NULL) {
	commandShell->exit = "";
    }
    if (commandShell->echo == (char *)NULL) {
	commandShell->echo = "";
    }

    /*
     * Catch the four signals that POSIX specifies if they aren't ignored.
     * JobPassSig will take care of calling JobInterrupt if appropriate.
     */
    if (SIGNAL(SIGINT, SIG_IGN) != SIG_IGN) {
	SIGNAL(SIGINT, JobPassSig);
    }
    if (SIGNAL(SIGHUP, SIG_IGN) != SIG_IGN) {
	SIGNAL(SIGHUP, JobPassSig);
    }
    if (!DEBUG(JOB) &&
	SIGNAL(SIGQUIT, SIG_IGN) != SIG_IGN)
    {
	SIGNAL(SIGQUIT, JobPassSig);
    }
    if (SIGNAL(SIGTERM, SIG_IGN) != SIG_IGN) {
	SIGNAL(SIGTERM, JobPassSig);
    }
#ifdef SIGXCPU
    if (SIGNAL(SIGXCPU, SIG_IGN) != SIG_IGN) {
	SIGNAL(SIGXCPU, JobPassSig);
    }
#endif
    /*
     * There are additional signals that need to be caught and passed if
     * either the export system wants to be told directly of signals or if
     * we're giving each job its own process group (since then it won't get
     * signals from the terminal driver as we own the terminal)
     */
#if defined(RMT_WANTS_SIGNALS) || defined(USE_PGRP)
    if (SIGNAL(SIGTSTP, SIG_IGN) != SIG_IGN) {
	SIGNAL(SIGTSTP, JobPassSig);
    }
    if (SIGNAL(SIGTTOU, SIG_IGN) != SIG_IGN) {
	SIGNAL(SIGTTOU, JobPassSig);
    }
    if (SIGNAL(SIGTTIN, SIG_IGN) != SIG_IGN) {
	SIGNAL(SIGTTIN, JobPassSig);
    }
#ifdef SIGWINCH
    if (SIGNAL(SIGWINCH, SIG_IGN) != SIG_IGN) {
	SIGNAL(SIGWINCH, JobPassSig);
    }
#endif
#ifdef SIGWINDOW
    if (SIGNAL(SIGWINDOW, SIG_IGN) != SIG_IGN) {
	SIGNAL(SIGWINDOW, JobPassSig);
    }
#endif
#endif
    
    begin = Targ_FindNode (".BEGIN", TARG_NOCREATE);

    if (!queryFlag && (begin != NILGNODE)) {
	JobStart (begin, JOB_SPECIAL, (Job *)0);
	while (nJobs) {
	    Job_CatchOutput();
#ifndef RMT_WILL_WATCH
	    Job_CatchChildren (!usePipes);
#endif /* RMT_WILL_WATCH */
	}
    }
    postCommands = Targ_FindNode (".END", TARG_CREATE);
}

/*-
 *-----------------------------------------------------------------------
 * Job_Full --
 *	See if the job table is full. It is considered full if it is OR
 *	if we are in the process of aborting OR if we have
 *	reached/exceeded our local quota. This prevents any more jobs
 *	from starting up.
 *
 * Results:
 *	TRUE if the job table is full, FALSE otherwise
 * Side Effects:
 *	None.
 *-----------------------------------------------------------------------
 */
Boolean
Job_Full ()
{
    /*
     * We make sure that the total number of jobs is bounded.  Otherwise
     * the make module might flood us with jobs that end up being deferred,
     * eventually causing us to run out of file descriptors.
     */
    return ((signals > 0) ||
	    aborting ||
	    (nJobs >= maxJobs) ||
	    (nJobs + Lst_Length(stoppedJobs) >= maxJobs));
}

/*-
 *-----------------------------------------------------------------------
 * Job_Empty --
 *	See if the job table is empty.  Because the local concurrency may
 *	be set to 0, it is possible for the job table to become empty,
 *	while the list of stoppedJobs remains non-empty. In such a case,
 *	we want to restart as many jobs as we can.
 *
 * Results:
 *	TRUE if it is. FALSE if it ain't.
 *
 * Side Effects:
 *	None.
 *
 * -----------------------------------------------------------------------
 */
Boolean
Job_Empty ()
{
    if (signals == 0 && nJobs == 0) {
	if (!Lst_IsEmpty(stoppedJobs)) {
	    /*
	     * The job table is obviously not full if it has no jobs in
	     * it...Try and restart the stopped jobs.
	     */
	    jobFull = FALSE;

	    if (!aborting) {
		JobRestartAll("Job_Empty", FALSE);
		return(FALSE);
	    }
	    else {
		/*
		 * We are aborting, so don't start any new jobs,
		 * only resume suspended ones.
		 */
		JobRestartAll("Job_Empty", TRUE);
		return(nJobs == 0);
	    }
	} else {
	    return(TRUE);
	}
    } else {
	return(FALSE);
    }
}

/*-
 *-----------------------------------------------------------------------
 * JobMatchShell --
 *	Find a matching shell in 'shells' given its final component.
 *
 * Results:
 *	A pointer to the Shell structure.
 *
 * Side Effects:
 *	None.
 *
 *-----------------------------------------------------------------------
 */
static Shell *
JobMatchShell (name)
    char	  *name;      /* Final component of shell path */
{
    register Shell *sh;	      /* Pointer into shells table */
    Shell	   *match;    /* Longest-matching shell */
    register char *cp1,
		  *cp2;
    char	  *eoname;

    eoname = name + strlen (name);

    match = (Shell *) NULL;

    for (sh = shells; sh->name != NULL; sh++) {
	for (cp1 = eoname - strlen (sh->name), cp2 = sh->name;
	     *cp1 != '\0' && *cp1 == *cp2;
	     cp1++, cp2++) {
		 continue;
	}
	if (*cp1 != *cp2) {
	    continue;
	} else if (match == (Shell *) NULL ||
		   strlen (match->name) < strlen (sh->name)) {
		       match = sh;
	}
    }
    return (match == (Shell *) NULL ? sh : match);
}

/*-
 *-----------------------------------------------------------------------
 * Job_ParseShell --
 *	Parse a shell specification and set up commandShell, shellPath
 *	and shellName appropriately.
 *
 * Results:
 *	FAILURE if the specification was incorrect.
 *
 * Side Effects:
 *	commandShell points to a Shell structure (either predefined or
 *	created from the shell spec), shellPath is the full path of the
 *	shell described by commandShell, while shellName is just the
 *	final component of shellPath.
 *	shellChanged is reset to FALSE.
 *
 * Notes:
 *	A shell specification consists of a .SHELL target, with dependency
 *	operator, followed by a series of blank-separated words. Double
 *	quotes can be used to use blanks in words. A backslash escapes
 *	anything (most notably a double-quote and a space) and
 *	provides the functionality it does in C. Each word consists of
 *	keyword and value separated by an equal sign. There should be no
 *	unnecessary spaces in the word. The keywords are as follows:
 *	    name  	    Name of shell.
 *	    path  	    Location of shell. Overrides "name" if given
 *	    quiet 	    Command to turn off echoing.
 *	    echo  	    Command to turn echoing on
 *	    filter	    Result of turning off echoing that shouldn't be
 *	    	  	    printed.
 *	    echoFlag	    Flag to turn echoing on at the start
 *	    errFlag	    Flag to turn error checking on at the start
 *	    hasErrCtl	    True if shell has error checking control
 *	    check 	    Command to turn on error checking if hasErrCtl
 *	    	  	    is TRUE or template of command to echo a command
 *	    	  	    for which error checking is off if hasErrCtl is
 *	    	  	    FALSE.
 *	    ignore	    Command to turn off error checking if hasErrCtl
 *	    	  	    is TRUE or template of command to execute a
 *	    	  	    command so as to ignore any errors it returns if
 *	    	  	    hasErrCtl is FALSE.
 *
 *-----------------------------------------------------------------------
 */
ReturnStatus
Job_ParseShell (line)
    char	  *line;  /* The shell spec */
{
    char    	  **words;
    int	    	  wordCount;
    register char **argv;
    register int  argc;
    char    	  *path;
    Shell   	  newShell;
    Boolean 	  fullSpec = FALSE;

    while (isspace (*line)) {
	line++;
    }
    words = Str_BreakString (line, " \t", "\n", &wordCount);

    memset (&newShell, 0, sizeof(newShell));
    
    /*
     * Parse the specification by keyword
     */
    for (path = (char *)NULL, argc = wordCount - 1, argv = words + 1;
	 argc != 0;
	 argc--, argv++) {
	     if (strncmp (*argv, "path=", 5) == 0) {
		 path = &argv[0][5];
	     } else if (strncmp (*argv, "name=", 5) == 0) {
		 newShell.name = &argv[0][5];
	     } else {
		 if (strncmp (*argv, "quiet=", 6) == 0) {
		     newShell.echoOff = &argv[0][6];
		 } else if (strncmp (*argv, "echo=", 5) == 0) {
		     newShell.echoOn = &argv[0][5];
		 } else if (strncmp (*argv, "filter=", 7) == 0) {
		     newShell.noPrint = &argv[0][7];
		     newShell.noPLen = strlen(newShell.noPrint);
		 } else if (strncmp (*argv, "echoFlag=", 9) == 0) {
		     newShell.echo = &argv[0][9];
		 } else if (strncmp (*argv, "errFlag=", 8) == 0) {
		     newShell.exit = &argv[0][8];
		 } else if (strncmp (*argv, "hasErrCtl=", 10) == 0) {
		     char c = argv[0][10];
		     newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
					    (c != 'T') && (c != 't'));
		 } else if (strncmp (*argv, "check=", 6) == 0) {
		     newShell.errCheck = &argv[0][6];
		 } else if (strncmp (*argv, "ignore=", 7) == 0) {
		     newShell.ignErr = &argv[0][7];
		 } else {
		     Parse_Error (PARSE_FATAL, "Unknown keyword \"%s\"",
				  *argv);
		     Str_FreeVec (wordCount, words);
		     return (FAILURE);
		 }
		 fullSpec = TRUE;
	     }
    }

    if (wordCount == 1) {
	/*
	 * .SHELL with empty dependencies tells PMake to revert to the
	 * default shell.
	 */
	commandShell = &shells[DEFSHELL];
	shellPath = (char *)NULL;
	(void)Job_ShellPath (FALSE);
    } else if (path == (char *)NULL) {
	/*
	 * If no path was given, the user wants one of the pre-defined shells,
	 * yes? So we find the one s/he wants with the help of JobMatchShell
	 * and set things up the right way. shellPath will be set up by
	 * Job_ShellPath.
	 */
	if (newShell.name == (char *)NULL) {
	    Parse_Error (PARSE_FATAL, "Neither path nor name specified");
	    Str_FreeVec (wordCount, words);
	    return (FAILURE);
	} else {
	    commandShell = JobMatchShell (newShell.name);
	    shellPath = (char *)NULL;
	    if (Job_ShellPath (FALSE) == (char *)NULL) {
		shellPath = newShell.name;
	    }
	    shellName = newShell.name;
	}
    } else {
	/*
	 * The user provided a path. If s/he gave nothing else (fullSpec is
	 * FALSE), try and find a matching shell in the ones we know of.
	 * Else we just take the specification at its word and copy it
	 * to a new location. In either case, we need to record the
	 * path the user gave for the shell.
	 */
	shellPath = path;
	path = strrchr (path, '/');
	if (path == (char *)NULL) {
	    path = shellPath;
	} else {
	    path += 1;
	}
	if (newShell.name != (char *)NULL) {
	    shellName = newShell.name;
	} else {
	    shellName = path;
	}
	if (!fullSpec) {
	    commandShell = JobMatchShell (shellName);
	} else {
	    commandShell = (Shell *) emalloc(sizeof(Shell));
	    *commandShell = newShell;
	}
    }

    if (commandShell->echoOn && commandShell->echoOff) {
	commandShell->hasEchoCtl = TRUE;
    }
    
    if (!commandShell->hasErrCtl) {
	if (commandShell->errCheck == (char *)NULL) {
	    commandShell->errCheck = "";
	}
	if (commandShell->ignErr == (char *)NULL) {
	    commandShell->ignErr = "%s\n";
	}
    }
    
    /*
     * SHELL and shellPath are in sync again.
     */
    shellChanged = FALSE;

    /*
     * Do not free up the words themselves, since they might be in use by the
     * shell specification...
     */
    free (words);
    return SUCCESS;
}

/*-
 *-----------------------------------------------------------------------
 * JobInterrupt --
 *	Handle the receipt of an interrupt.
 *
 * Results:
 *	None
 *
 * Side Effects:
 *	All children are killed. Another job will be started if the
 *	.INTERRUPT target was given.
 *-----------------------------------------------------------------------
 */
static void
JobInterrupt (runINTERRUPT)
    int	    runINTERRUPT;   	/* Non-zero if commands for the .INTERRUPT
				 * target should be executed */
{
    LstNode 	  ln;		/* element in job table */
    Job           *job;	    	/* job descriptor in that element */
    GNode         *interrupt;	/* the node describing the .INTERRUPT target */
    
    aborting = ABORT_INTERRUPT;

    (void)Lst_Open (jobs);
    while ((ln = Lst_Next (jobs)) != NILLNODE) {
	job = (Job *) Lst_Datum (ln);

	if (!Targ_Precious (job->node)) {
	    char  	*file = (job->node->path == (char *)NULL ?
				 job->node->name :
				 job->node->path);
	    struct	stat buf;

	    /*
	     * Attempt to remove the current target only if
	     * - it exists as a file
	     * - it has been modified during this make run
	     * - it is not a directory
	     * XXX: For remotely created targets it is very like that
	     * we will miss some due to the directory and attribute
	     * caching in NFS.
	     */
	    if (stat (file, &buf) == 0 && buf.st_mtime >= now) {
		fprintf (stderr, "*** %s ", file);
		if (buf.st_mode & S_IFDIR) {
		    fprintf (stderr, "not removed\n");
		} else if (unlink (file) == 0) {
		    fprintf (stderr, "removed\n");
		} else {
		    fprintf (stderr, "not removed (%s)\n", strerror(errno));
		}
		fflush (stderr);
	    }
	}
	/*
	 * No need to actually kill jobs here, since we are always
	 * called right after JobPassSig() has already done it for us.
	 */
    }
    Lst_Close (jobs);

    if (runINTERRUPT && !touchFlag && !queryFlag) {
	interrupt = Targ_FindNode (".INTERRUPT", TARG_NOCREATE);
	if (interrupt != NILGNODE) {
	    ignoreErrors = FALSE;

	    /*
	     * Make sure we can actually run the .INTERRUPT target.
	     */
	    maxJobs = 2 * maxJobs;
	    maxLocal = 2 * maxLocal;

	    JobStart (interrupt, JOB_IGNDOTS, (Job *)0);
	    while (nJobs) {
		Job_CatchOutput();
#ifndef RMT_WILL_WATCH
		Job_CatchChildren (!usePipes);
#endif /* RMT_WILL_WATCH */
	    }
	}
    }
    (void) unlink (tfile);
    Main_Unlock();
    /*
     * Don't exit here yet.  Fall through to JobPassSig() to commit
     * suicide with the proper signal.
     */
}

/*
 *-----------------------------------------------------------------------
 * Job_End --
 *	Do final processing such as the running of the commands
 *	attached to the .END target. 
 *
 * Results:
 *	Number of errors reported.
 *
 * Side Effects:
 *	The process' temporary file (tfile) is removed if it still
 *	existed.
 *-----------------------------------------------------------------------
 */
int
Job_End ()
{
    if (postCommands != NILGNODE && !Lst_IsEmpty (postCommands->commands)) {
	if (errors) {
	    Error ("Errors reported so .END ignored");
	} else if (!queryFlag) {
	    JobStart (postCommands, JOB_SPECIAL | JOB_IGNDOTS,
		       (Job *)0);

	    while (nJobs) {
		Job_CatchOutput();
#ifndef RMT_WILL_WATCH
		Job_CatchChildren (!usePipes);
#endif /* RMT_WILL_WATCH */
	    }
	}
    }
    (void) unlink (tfile);
    return(errors);
}

/*-
 *-----------------------------------------------------------------------
 * Job_Wait --
 *	Waits for all running jobs to finish and returns. Sets 'aborting'
 *	to ABORT_WAIT to prevent other jobs from starting.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	Currently running jobs finish.
 *
 *-----------------------------------------------------------------------
 */
void
Job_Wait()
{
    aborting = ABORT_WAIT;
    while (nJobs != 0) {
	Job_CatchOutput();
#ifndef RMT_WILL_WATCH
	Job_CatchChildren(!usePipes);
#endif /* RMT_WILL_WATCH */
    }
    aborting = 0;
}

/*-
 *-----------------------------------------------------------------------
 * Job_AbortAll --
 *	Abort all currently running jobs without handling output or anything.
 *	This function is to be called only in the event of a major
 *	error. Most definitely NOT to be called from JobInterrupt.
 *
 * Results:
 *	None
 *
 * Side Effects:
 *	All children are killed, not just the firstborn
 *-----------------------------------------------------------------------
 */
void
Job_AbortAll ()
{
    LstNode           	ln;		/* element in job table */
    Job            	*job;		/* the job descriptor in that element */
    WAIT_STATUS    	foo;
    Lst     		oldJobs;	/* List of all jobs to kill */
    
    aborting = ABORT_ERROR;
    
    /*
     * Make a scratch list of all jobs to signal.
     * We can't just walk down the current list because it is likely to
     * change as a result of this very operation.
     */
    oldJobs = Lst_Init(FALSE);
    Lst_Concat(oldJobs, jobs, LST_CONCNEW);
    Lst_Concat(oldJobs, stoppedJobs, LST_CONCNEW);

    (void)Lst_Open (oldJobs);
    while ((ln = Lst_Next (oldJobs)) != NILLNODE) {
	job = (Job *) Lst_Datum (ln);

	if (!JobIsValid(job)) {
	    continue;
	}

	/*
	 * kill the child process with increasingly drastic signals to make
	 * darn sure it's dead. 
	 */
#ifdef RMT_WANTS_SIGNALS
	if (job->flags & JOB_REMOTE) {
	    (void)Rmt_Signal(job, SIGINT);
	    (void)Rmt_Signal(job, SIGKILL);
	} else if (job->pid) {
	    KILL(job->pid, SIGINT);
	    KILL(job->pid, SIGKILL);
	}
#else
	if (job->pid) {
	    KILL(job->pid, SIGINT);
	    KILL(job->pid, SIGKILL);
	}
#endif /* RMT_WANTS_SIGNALS */
    }
    Lst_Destroy(oldJobs, NOFREE);
    
    /*
     * Catch as many children as want to report in at first, then give up
     */
    while (WAIT3(&foo, WNOHANG, NULL) > 0) {
	;
    }
    (void) unlink (tfile);
}
