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