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