xref: /original-bsd/usr.bin/make/job.c (revision c3e32dec)
1 /*
2  * Copyright (c) 1988, 1989, 1990, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1989 by Berkeley Softworks
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * %sccs.include.redist.c%
11  */
12 
13 #ifndef lint
14 static char sccsid[] = "@(#)job.c	8.1 (Berkeley) 06/06/93";
15 #endif /* not lint */
16 
17 /*-
18  * job.c --
19  *	handle the creation etc. of our child processes.
20  *
21  * Interface:
22  *	Job_Make  	    	Start the creation of the given target.
23  *
24  *	Job_CatchChildren   	Check for and handle the termination of any
25  *	    	  	    	children. This must be called reasonably
26  *	    	  	    	frequently to keep the whole make going at
27  *	    	  	    	a decent clip, since job table entries aren't
28  *	    	  	    	removed until their process is caught this way.
29  *	    	  	    	Its single argument is TRUE if the function
30  *	    	  	    	should block waiting for a child to terminate.
31  *
32  *	Job_CatchOutput	    	Print any output our children have produced.
33  *	    	  	    	Should also be called fairly frequently to
34  *	    	  	    	keep the user informed of what's going on.
35  *	    	  	    	If no output is waiting, it will block for
36  *	    	  	    	a time given by the SEL_* constants, below,
37  *	    	  	    	or until output is ready.
38  *
39  *	Job_Init  	    	Called to intialize this module. in addition,
40  *	    	  	    	any commands attached to the .BEGIN target
41  *	    	  	    	are executed before this function returns.
42  *	    	  	    	Hence, the makefile must have been parsed
43  *	    	  	    	before this function is called.
44  *
45  *	Job_Full  	    	Return TRUE if the job table is filled.
46  *
47  *	Job_Empty 	    	Return TRUE if the job table is completely
48  *	    	  	    	empty.
49  *
50  *	Job_ParseShell	    	Given the line following a .SHELL target, parse
51  *	    	  	    	the line as a shell specification. Returns
52  *	    	  	    	FAILURE if the spec was incorrect.
53  *
54  *	Job_End	  	    	Perform any final processing which needs doing.
55  *	    	  	    	This includes the execution of any commands
56  *	    	  	    	which have been/were attached to the .END
57  *	    	  	    	target. It should only be called when the
58  *	    	  	    	job table is empty.
59  *
60  *	Job_AbortAll	    	Abort all currently running jobs. It doesn't
61  *	    	  	    	handle output or do anything for the jobs,
62  *	    	  	    	just kills them. It should only be called in
63  *	    	  	    	an emergency, as it were.
64  *
65  *	Job_CheckCommands   	Verify that the commands for a target are
66  *	    	  	    	ok. Provide them if necessary and possible.
67  *
68  *	Job_Touch 	    	Update a target without really updating it.
69  *
70  *	Job_Wait  	    	Wait for all currently-running jobs to finish.
71  */
72 
73 #include <sys/types.h>
74 #include <sys/stat.h>
75 #include <sys/file.h>
76 #include <sys/time.h>
77 #include <sys/wait.h>
78 
79 #include <errno.h>
80 #include <fcntl.h>
81 #include <signal.h>
82 #include <stdio.h>
83 #include <string.h>
84 
85 #include "make.h"
86 #include "hash.h"
87 #include "dir.h"
88 #include "job.h"
89 #include "pathnames.h"
90 
91 extern int  errno;
92 
93 /*
94  * error handling variables
95  */
96 static int     	errors = 0;	    /* number of errors reported */
97 static int    	aborting = 0;	    /* why is the make aborting? */
98 #define ABORT_ERROR	1   	    /* Because of an error */
99 #define ABORT_INTERRUPT	2   	    /* Because it was interrupted */
100 #define ABORT_WAIT	3   	    /* Waiting for jobs to finish */
101 
102 
103 /*
104  * post-make command processing. The node postCommands is really just the
105  * .END target but we keep it around to avoid having to search for it
106  * all the time.
107  */
108 static GNode   	  *postCommands;    /* node containing commands to execute when
109 				     * everything else is done */
110 static int     	  numCommands; 	    /* The number of commands actually printed
111 				     * for a target. Should this number be
112 				     * 0, no shell will be executed. */
113 
114 
115 /*
116  * Return values from JobStart.
117  */
118 #define JOB_RUNNING	0   	/* Job is running */
119 #define JOB_ERROR 	1   	/* Error in starting the job */
120 #define JOB_FINISHED	2   	/* The job is already finished */
121 #define JOB_STOPPED	3   	/* The job is stopped */
122 
123 /*
124  * tfile is the name of a file into which all shell commands are put. It is
125  * used over by removing it before the child shell is executed. The XXXXX in
126  * the string are replaced by the pid of the make process in a 5-character
127  * field with leading zeroes.
128  */
129 static char     tfile[] = TMPPAT;
130 
131 
132 /*
133  * Descriptions for various shells.
134  */
135 static Shell    shells[] = {
136     /*
137      * CSH description. The csh can do echo control by playing
138      * with the setting of the 'echo' shell variable. Sadly,
139      * however, it is unable to do error control nicely.
140      */
141 {
142     "csh",
143     TRUE, "unset verbose", "set verbose", "unset verbose", 10,
144     FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"",
145     "v", "e",
146 },
147     /*
148      * SH description. Echo control is also possible and, under
149      * sun UNIX anyway, one can even control error checking.
150      */
151 {
152     "sh",
153     TRUE, "set -", "set -v", "set -", 5,
154     FALSE, "echo \"%s\"\n", "sh -c '%s || exit 0'\n",
155     "v", "e",
156 },
157     /*
158      * UNKNOWN.
159      */
160 {
161     (char *)0,
162     FALSE, (char *)0, (char *)0, (char *)0, 0,
163     FALSE, (char *)0, (char *)0,
164     (char *)0, (char *)0,
165 }
166 };
167 static Shell 	*commandShell = &shells[DEFSHELL];/* this is the shell to
168 						   * which we pass all
169 						   * commands in the Makefile.
170 						   * It is set by the
171 						   * Job_ParseShell function */
172 static char   	*shellPath = (char *) NULL,	  /* full pathname of
173 						   * executable image */
174                	*shellName;	      	      	  /* last component of shell */
175 
176 
177 static int  	maxJobs;    	/* The most children we can run at once */
178 static int  	maxLocal;    	/* The most local ones we can have */
179 static int     	nJobs;	    	/* The number of children currently running */
180 static int  	nLocal;    	/* The number of local children */
181 static Lst     	jobs;		/* The structures that describe them */
182 static Boolean	jobFull;    	/* Flag to tell when the job table is full. It
183 				 * is set TRUE when (1) the total number of
184 				 * running jobs equals the maximum allowed or
185 				 * (2) a job can only be run locally, but
186 				 * nLocal equals maxLocal */
187 #ifndef RMT_WILL_WATCH
188 static fd_set  	outputs;    	/* Set of descriptors of pipes connected to
189 				 * the output channels of children */
190 #endif
191 
192 static GNode   	*lastNode;	/* The node for which output was most recently
193 				 * produced. */
194 static char    	*targFmt;   	/* Format string to use to head output from a
195 				 * job when it's not the most-recent job heard
196 				 * from */
197 #define TARG_FMT  "--- %s ---\n" /* Default format */
198 
199 /*
200  * When JobStart attempts to run a job remotely but can't, and isn't allowed
201  * to run the job locally, or when Job_CatchChildren detects a job that has
202  * been migrated home, the job is placed on the stoppedJobs queue to be run
203  * when the next job finishes.
204  */
205 static Lst    stoppedJobs;	/* Lst of Job structures describing
206 				 * jobs that were stopped due to concurrency
207 				 * limits or migration home */
208 
209 
210 #if defined(USE_PGRP) && defined(SYSV)
211 #define KILL(pid,sig)	killpg (-(pid),(sig))
212 #else
213 # if defined(USE_PGRP)
214 #define KILL(pid,sig)	killpg ((pid),(sig))
215 # else
216 #define KILL(pid,sig)	kill ((pid),(sig))
217 # endif
218 #endif
219 
220 static int JobCondPassSig __P((Job *, int));
221 static void JobPassSig __P((int));
222 static int JobCmpPid __P((Job *, int));
223 static int JobPrintCommand __P((char *, Job *));
224 static int JobSaveCommand __P((char *, GNode *));
225 static void JobFinish __P((Job *, union wait));
226 static void JobExec __P((Job *, char **));
227 static void JobMakeArgv __P((Job *, char **));
228 static void JobRestart __P((Job *));
229 static int JobStart __P((GNode *, int, Job *));
230 static void JobDoOutput __P((Job *, Boolean));
231 static Shell *JobMatchShell __P((char *));
232 static void JobInterrupt __P((int));
233 
234 /*-
235  *-----------------------------------------------------------------------
236  * JobCondPassSig --
237  *	Pass a signal to a job if the job is remote or if USE_PGRP
238  *	is defined.
239  *
240  * Results:
241  *	=== 0
242  *
243  * Side Effects:
244  *	None, except the job may bite it.
245  *
246  *-----------------------------------------------------------------------
247  */
248 static int
249 JobCondPassSig(job, signo)
250     Job	    	*job;	    /* Job to biff */
251     int	    	signo;	    /* Signal to send it */
252 {
253 #ifdef RMT_WANTS_SIGNALS
254     if (job->flags & JOB_REMOTE) {
255 	(void)Rmt_Signal(job, signo);
256     } else {
257 	KILL(job->pid, signo);
258     }
259 #else
260     /*
261      * Assume that sending the signal to job->pid will signal any remote
262      * job as well.
263      */
264     KILL(job->pid, signo);
265 #endif
266     return(0);
267 }
268 
269 /*-
270  *-----------------------------------------------------------------------
271  * JobPassSig --
272  *	Pass a signal on to all remote jobs and to all local jobs if
273  *	USE_PGRP is defined, then die ourselves.
274  *
275  * Results:
276  *	None.
277  *
278  * Side Effects:
279  *	We die by the same signal.
280  *
281  *-----------------------------------------------------------------------
282  */
283 static void
284 JobPassSig(signo)
285     int	    signo;	/* The signal number we've received */
286 {
287     int	    mask;
288 
289     Lst_ForEach(jobs, JobCondPassSig, (ClientData)signo);
290 
291     /*
292      * Deal with proper cleanup based on the signal received. We only run
293      * the .INTERRUPT target if the signal was in fact an interrupt. The other
294      * three termination signals are more of a "get out *now*" command.
295      */
296     if (signo == SIGINT) {
297 	JobInterrupt(TRUE);
298     } else if ((signo == SIGHUP) || (signo == SIGTERM) || (signo == SIGQUIT)) {
299 	JobInterrupt(FALSE);
300     }
301 
302     /*
303      * Leave gracefully if SIGQUIT, rather than core dumping.
304      */
305     if (signo == SIGQUIT) {
306 	Finish(0);
307     }
308 
309     /*
310      * Send ourselves the signal now we've given the message to everyone else.
311      * Note we block everything else possible while we're getting the signal.
312      * This ensures that all our jobs get continued when we wake up before
313      * we take any other signal.
314      */
315     mask = sigblock(0);
316     (void) sigsetmask(~0 & ~(1 << (signo-1)));
317     signal(signo, SIG_DFL);
318 
319     kill(getpid(), signo);
320 
321     Lst_ForEach(jobs, JobCondPassSig, (ClientData)SIGCONT);
322 
323     sigsetmask(mask);
324     signal(signo, JobPassSig);
325 
326 }
327 
328 /*-
329  *-----------------------------------------------------------------------
330  * JobCmpPid  --
331  *	Compare the pid of the job with the given pid and return 0 if they
332  *	are equal. This function is called from Job_CatchChildren via
333  *	Lst_Find to find the job descriptor of the finished job.
334  *
335  * Results:
336  *	0 if the pid's match
337  *
338  * Side Effects:
339  *	None
340  *-----------------------------------------------------------------------
341  */
342 static int
343 JobCmpPid (job, pid)
344     int             pid;	/* process id desired */
345     Job            *job;	/* job to examine */
346 {
347     return (pid - job->pid);
348 }
349 
350 /*-
351  *-----------------------------------------------------------------------
352  * JobPrintCommand  --
353  *	Put out another command for the given job. If the command starts
354  *	with an @ or a - we process it specially. In the former case,
355  *	so long as the -s and -n flags weren't given to make, we stick
356  *	a shell-specific echoOff command in the script. In the latter,
357  *	we ignore errors for the entire job, unless the shell has error
358  *	control.
359  *	If the command is just "..." we take all future commands for this
360  *	job to be commands to be executed once the entire graph has been
361  *	made and return non-zero to signal that the end of the commands
362  *	was reached. These commands are later attached to the postCommands
363  *	node and executed by Job_End when all things are done.
364  *	This function is called from JobStart via Lst_ForEach.
365  *
366  * Results:
367  *	Always 0, unless the command was "..."
368  *
369  * Side Effects:
370  *	If the command begins with a '-' and the shell has no error control,
371  *	the JOB_IGNERR flag is set in the job descriptor.
372  *	If the command is "..." and we're not ignoring such things,
373  *	tailCmds is set to the successor node of the cmd.
374  *	numCommands is incremented if the command is actually printed.
375  *-----------------------------------------------------------------------
376  */
377 static int
378 JobPrintCommand (cmd, job)
379     char     	  *cmd;	    	    /* command string to print */
380     Job           *job;	    	    /* job for which to print it */
381 {
382     Boolean	  noSpecials;	    /* true if we shouldn't worry about
383 				     * inserting special commands into
384 				     * the input stream. */
385     Boolean       shutUp = FALSE;   /* true if we put a no echo command
386 				     * into the command file */
387     Boolean	  errOff = FALSE;   /* true if we turned error checking
388 				     * off before printing the command
389 				     * and need to turn it back on */
390     char       	  *cmdTemplate;	    /* Template to use when printing the
391 				     * command */
392     char    	  *cmdStart;	    /* Start of expanded command */
393     LstNode 	  cmdNode;  	    /* Node for replacing the command */
394 
395     noSpecials = (noExecute && ! (job->node->type & OP_MAKE));
396 
397     if (strcmp (cmd, "...") == 0) {
398 	job->node->type |= OP_SAVE_CMDS;
399 	if ((job->flags & JOB_IGNDOTS) == 0) {
400 	    job->tailCmds = Lst_Succ (Lst_Member (job->node->commands,
401 						  (ClientData)cmd));
402 	    return (1);
403 	}
404 	return (0);
405     }
406 
407 #define DBPRINTF(fmt, arg) if (DEBUG(JOB)) printf (fmt, arg); fprintf (job->cmdFILE, fmt, arg)
408 
409     numCommands += 1;
410 
411     /*
412      * For debugging, we replace each command with the result of expanding
413      * the variables in the command.
414      */
415     cmdNode = Lst_Member (job->node->commands, (ClientData)cmd);
416     cmdStart = cmd = Var_Subst (NULL, cmd, job->node, FALSE);
417     Lst_Replace (cmdNode, (ClientData)cmdStart);
418 
419     cmdTemplate = "%s\n";
420 
421     /*
422      * Check for leading @' and -'s to control echoing and error checking.
423      */
424     while (*cmd == '@' || *cmd == '-') {
425 	if (*cmd == '@') {
426 	    shutUp = TRUE;
427 	} else {
428 	    errOff = TRUE;
429 	}
430 	cmd++;
431     }
432 
433     if (shutUp) {
434 	if (! (job->flags & JOB_SILENT) && !noSpecials &&
435 	    commandShell->hasEchoCtl) {
436 		DBPRINTF ("%s\n", commandShell->echoOff);
437 	} else {
438 	    shutUp = FALSE;
439 	}
440     }
441 
442     if (errOff) {
443 	if ( ! (job->flags & JOB_IGNERR) && !noSpecials) {
444 	    if (commandShell->hasErrCtl) {
445 		/*
446 		 * we don't want the error-control commands showing
447 		 * up either, so we turn off echoing while executing
448 		 * them. We could put another field in the shell
449 		 * structure to tell JobDoOutput to look for this
450 		 * string too, but why make it any more complex than
451 		 * it already is?
452 		 */
453 		if (! (job->flags & JOB_SILENT) && !shutUp &&
454 		    commandShell->hasEchoCtl) {
455 			DBPRINTF ("%s\n", commandShell->echoOff);
456 			DBPRINTF ("%s\n", commandShell->ignErr);
457 			DBPRINTF ("%s\n", commandShell->echoOn);
458 		} else {
459 		    DBPRINTF ("%s\n", commandShell->ignErr);
460 		}
461 	    } else if (commandShell->ignErr &&
462 		       (*commandShell->ignErr != '\0'))
463 	    {
464 		/*
465 		 * The shell has no error control, so we need to be
466 		 * weird to get it to ignore any errors from the command.
467 		 * If echoing is turned on, we turn it off and use the
468 		 * errCheck template to echo the command. Leave echoing
469 		 * off so the user doesn't see the weirdness we go through
470 		 * to ignore errors. Set cmdTemplate to use the weirdness
471 		 * instead of the simple "%s\n" template.
472 		 */
473 		if (! (job->flags & JOB_SILENT) && !shutUp &&
474 		    commandShell->hasEchoCtl) {
475 			DBPRINTF ("%s\n", commandShell->echoOff);
476 			DBPRINTF (commandShell->errCheck, cmd);
477 			shutUp = TRUE;
478 		}
479 		cmdTemplate = commandShell->ignErr;
480 		/*
481 		 * The error ignoration (hee hee) is already taken care
482 		 * of by the ignErr template, so pretend error checking
483 		 * is still on.
484 		 */
485 		errOff = FALSE;
486 	    } else {
487 		errOff = FALSE;
488 	    }
489 	} else {
490 	    errOff = FALSE;
491 	}
492     }
493 
494     DBPRINTF (cmdTemplate, cmd);
495 
496     if (errOff) {
497 	/*
498 	 * If echoing is already off, there's no point in issuing the
499 	 * echoOff command. Otherwise we issue it and pretend it was on
500 	 * for the whole command...
501 	 */
502 	if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl){
503 	    DBPRINTF ("%s\n", commandShell->echoOff);
504 	    shutUp = TRUE;
505 	}
506 	DBPRINTF ("%s\n", commandShell->errCheck);
507     }
508     if (shutUp) {
509 	DBPRINTF ("%s\n", commandShell->echoOn);
510     }
511     return (0);
512 }
513 
514 /*-
515  *-----------------------------------------------------------------------
516  * JobSaveCommand --
517  *	Save a command to be executed when everything else is done.
518  *	Callback function for JobFinish...
519  *
520  * Results:
521  *	Always returns 0
522  *
523  * Side Effects:
524  *	The command is tacked onto the end of postCommands's commands list.
525  *
526  *-----------------------------------------------------------------------
527  */
528 static int
529 JobSaveCommand (cmd, gn)
530     char    *cmd;
531     GNode   *gn;
532 {
533     cmd = Var_Subst (NULL, cmd, gn, FALSE);
534     (void)Lst_AtEnd (postCommands->commands, (ClientData)cmd);
535     return (0);
536 }
537 
538 /*-
539  *-----------------------------------------------------------------------
540  * JobFinish  --
541  *	Do final processing for the given job including updating
542  *	parents and starting new jobs as available/necessary. Note
543  *	that we pay no attention to the JOB_IGNERR flag here.
544  *	This is because when we're called because of a noexecute flag
545  *	or something, jstat.w_status is 0 and when called from
546  *	Job_CatchChildren, the status is zeroed if it s/b ignored.
547  *
548  * Results:
549  *	None
550  *
551  * Side Effects:
552  *	Some nodes may be put on the toBeMade queue.
553  *	Final commands for the job are placed on postCommands.
554  *
555  *	If we got an error and are aborting (aborting == ABORT_ERROR) and
556  *	the job list is now empty, we are done for the day.
557  *	If we recognized an error (errors !=0), we set the aborting flag
558  *	to ABORT_ERROR so no more jobs will be started.
559  *-----------------------------------------------------------------------
560  */
561 /*ARGSUSED*/
562 static void
563 JobFinish (job, status)
564     Job           *job;	      	  /* job to finish */
565     union wait	  status;     	  /* sub-why job went away */
566 {
567     Boolean 	  done;
568 
569     if ((WIFEXITED(status) &&
570 	  (((status.w_retcode != 0) && !(job->flags & JOB_IGNERR)))) ||
571 	(WIFSIGNALED(status) && (status.w_termsig != SIGCONT)))
572     {
573 	/*
574 	 * If it exited non-zero and either we're doing things our
575 	 * way or we're not ignoring errors, the job is finished.
576 	 * Similarly, if the shell died because of a signal
577 	 * the job is also finished. In these
578 	 * cases, finish out the job's output before printing the exit
579 	 * status...
580 	 */
581 	if (usePipes) {
582 #ifdef RMT_WILL_WATCH
583 	    Rmt_Ignore(job->inPipe);
584 #else
585 	    FD_CLR(job->inPipe, &outputs);
586 #endif /* RMT_WILL_WATCH */
587 	    if (job->outPipe != job->inPipe) {
588 		(void)close (job->outPipe);
589 	    }
590 	    JobDoOutput (job, TRUE);
591 	    (void)close (job->inPipe);
592 	} else {
593 	    (void)close (job->outFd);
594 	    JobDoOutput (job, TRUE);
595 	}
596 
597 	if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
598 	    fclose(job->cmdFILE);
599 	}
600 	done = TRUE;
601     } else if (WIFEXITED(status) && status.w_retcode != 0) {
602 	/*
603 	 * Deal with ignored errors in -B mode. We need to print a message
604 	 * telling of the ignored error as well as setting status.w_status
605 	 * to 0 so the next command gets run. To do this, we set done to be
606 	 * TRUE if in -B mode and the job exited non-zero. Note we don't
607 	 * want to close down any of the streams until we know we're at the
608 	 * end.
609 	 */
610 	done = TRUE;
611     } else {
612 	/*
613 	 * No need to close things down or anything.
614 	 */
615 	done = FALSE;
616     }
617 
618     if (done ||
619 	WIFSTOPPED(status) ||
620 	(WIFSIGNALED(status) && (status.w_termsig == SIGCONT)) ||
621 	DEBUG(JOB))
622     {
623 	FILE	  *out;
624 
625 	if (!usePipes && (job->flags & JOB_IGNERR)) {
626 	    /*
627 	     * If output is going to a file and this job is ignoring
628 	     * errors, arrange to have the exit status sent to the
629 	     * output file as well.
630 	     */
631 	    out = fdopen (job->outFd, "w");
632 	} else {
633 	    out = stdout;
634 	}
635 
636 	if (WIFEXITED(status)) {
637 	    if (status.w_retcode != 0) {
638 		if (usePipes && job->node != lastNode) {
639 		    fprintf (out, targFmt, job->node->name);
640 		    lastNode = job->node;
641 		}
642 		fprintf (out, "*** Error code %d%s\n", status.w_retcode,
643 			 (job->flags & JOB_IGNERR) ? " (ignored)" : "");
644 
645 		if (job->flags & JOB_IGNERR) {
646 		    status.w_status = 0;
647 		}
648 	    } else if (DEBUG(JOB)) {
649 		if (usePipes && job->node != lastNode) {
650 		    fprintf (out, targFmt, job->node->name);
651 		    lastNode = job->node;
652 		}
653 		fprintf (out, "*** Completed successfully\n");
654 	    }
655 	} else if (WIFSTOPPED(status)) {
656 	    if (usePipes && job->node != lastNode) {
657 		fprintf (out, targFmt, job->node->name);
658 		lastNode = job->node;
659 	    }
660 	    if (! (job->flags & JOB_REMIGRATE)) {
661 		fprintf (out, "*** Stopped -- signal %d\n", status.w_stopsig);
662 	    }
663 	    job->flags |= JOB_RESUME;
664 	    (void)Lst_AtEnd(stoppedJobs, (ClientData)job);
665 	    fflush(out);
666 	    return;
667 	} else if (status.w_termsig == SIGCONT) {
668 	    /*
669 	     * If the beastie has continued, shift the Job from the stopped
670 	     * list to the running one (or re-stop it if concurrency is
671 	     * exceeded) and go and get another child.
672 	     */
673 	    if (job->flags & (JOB_RESUME|JOB_REMIGRATE|JOB_RESTART)) {
674 		if (usePipes && job->node != lastNode) {
675 		    fprintf (out, targFmt, job->node->name);
676 		    lastNode = job->node;
677 		}
678 		fprintf (out, "*** Continued\n");
679 	    }
680 	    if (! (job->flags & JOB_CONTINUING)) {
681 		JobRestart(job);
682 	    } else {
683 		Lst_AtEnd(jobs, (ClientData)job);
684 		nJobs += 1;
685 		if (! (job->flags & JOB_REMOTE)) {
686 		    nLocal += 1;
687 		}
688 		if (nJobs == maxJobs) {
689 		    jobFull = TRUE;
690 		    if (DEBUG(JOB)) {
691 			printf("Job queue is full.\n");
692 		    }
693 		}
694 	    }
695 	    fflush(out);
696 	    return;
697 	} else {
698 	    if (usePipes && job->node != lastNode) {
699 		fprintf (out, targFmt, job->node->name);
700 		lastNode = job->node;
701 	    }
702 	    fprintf (out, "*** Signal %d\n", status.w_termsig);
703 	}
704 
705 	fflush (out);
706     }
707 
708     /*
709      * Now handle the -B-mode stuff. If the beast still isn't finished,
710      * try and restart the job on the next command. If JobStart says it's
711      * ok, it's ok. If there's an error, this puppy is done.
712      */
713     if ((status.w_status == 0) &&
714 	!Lst_IsAtEnd (job->node->commands))
715     {
716 	switch (JobStart (job->node,
717 			  job->flags & JOB_IGNDOTS,
718 			  job))
719 	{
720 	    case JOB_RUNNING:
721 		done = FALSE;
722 		break;
723 	    case JOB_ERROR:
724 		done = TRUE;
725 		status.w_retcode = 1;
726 		break;
727 	    case JOB_FINISHED:
728 		/*
729 		 * If we got back a JOB_FINISHED code, JobStart has already
730 		 * called Make_Update and freed the job descriptor. We set
731 		 * done to false here to avoid fake cycles and double frees.
732 		 * JobStart needs to do the update so we can proceed up the
733 		 * graph when given the -n flag..
734 		 */
735 		done = FALSE;
736 		break;
737 	}
738     } else {
739 	done = TRUE;
740     }
741 
742 
743     if (done &&
744 	(aborting != ABORT_ERROR) &&
745 	(aborting != ABORT_INTERRUPT) &&
746 	(status.w_status == 0))
747     {
748 	/*
749 	 * As long as we aren't aborting and the job didn't return a non-zero
750 	 * status that we shouldn't ignore, we call Make_Update to update
751 	 * the parents. In addition, any saved commands for the node are placed
752 	 * on the .END target.
753 	 */
754 	if (job->tailCmds != NILLNODE) {
755 	    Lst_ForEachFrom (job->node->commands, job->tailCmds,
756 			     JobSaveCommand,
757 			     (ClientData)job->node);
758 	}
759 	job->node->made = MADE;
760 	Make_Update (job->node);
761 	free((Address)job);
762     } else if (status.w_status) {
763 	errors += 1;
764 	free((Address)job);
765     }
766 
767     while (!errors && !jobFull && !Lst_IsEmpty(stoppedJobs)) {
768 	JobRestart((Job *)Lst_DeQueue(stoppedJobs));
769     }
770 
771     /*
772      * Set aborting if any error.
773      */
774     if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
775 	/*
776 	 * If we found any errors in this batch of children and the -k flag
777 	 * wasn't given, we set the aborting flag so no more jobs get
778 	 * started.
779 	 */
780 	aborting = ABORT_ERROR;
781     }
782 
783     if ((aborting == ABORT_ERROR) && Job_Empty()) {
784 	/*
785 	 * If we are aborting and the job table is now empty, we finish.
786 	 */
787 	(void) unlink (tfile);
788 	Finish (errors);
789     }
790 }
791 
792 /*-
793  *-----------------------------------------------------------------------
794  * Job_Touch --
795  *	Touch the given target. Called by JobStart when the -t flag was
796  *	given
797  *
798  * Results:
799  *	None
800  *
801  * Side Effects:
802  *	The data modification of the file is changed. In addition, if the
803  *	file did not exist, it is created.
804  *-----------------------------------------------------------------------
805  */
806 void
807 Job_Touch (gn, silent)
808     GNode         *gn;	      	/* the node of the file to touch */
809     Boolean 	  silent;   	/* TRUE if should not print messages */
810 {
811     int		  streamID;   	/* ID of stream opened to do the touch */
812     struct timeval times[2];	/* Times for utimes() call */
813 
814     if (gn->type & (OP_JOIN|OP_USE|OP_EXEC|OP_OPTIONAL)) {
815 	/*
816 	 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets
817 	 * and, as such, shouldn't really be created.
818 	 */
819 	return;
820     }
821 
822     if (!silent) {
823 	printf ("touch %s\n", gn->name);
824     }
825 
826     if (noExecute) {
827 	return;
828     }
829 
830     if (gn->type & OP_ARCHV) {
831 	Arch_Touch (gn);
832     } else if (gn->type & OP_LIB) {
833 	Arch_TouchLib (gn);
834     } else {
835 	char	*file = gn->path ? gn->path : gn->name;
836 
837 	times[0].tv_sec = times[1].tv_sec = now;
838 	times[0].tv_usec = times[1].tv_usec = 0;
839 	if (utimes(file, times) < 0){
840 	    streamID = open (file, O_RDWR | O_CREAT, 0666);
841 
842 	    if (streamID >= 0) {
843 		char	c;
844 
845 		/*
846 		 * Read and write a byte to the file to change the
847 		 * modification time, then close the file.
848 		 */
849 		if (read(streamID, &c, 1) == 1) {
850 		    lseek(streamID, 0L, L_SET);
851 		    write(streamID, &c, 1);
852 		}
853 
854 		(void)close (streamID);
855 	    } else
856 		printf("*** couldn't touch %s: %s", file, strerror(errno));
857 	}
858     }
859 }
860 
861 /*-
862  *-----------------------------------------------------------------------
863  * Job_CheckCommands --
864  *	Make sure the given node has all the commands it needs.
865  *
866  * Results:
867  *	TRUE if the commands list is/was ok.
868  *
869  * Side Effects:
870  *	The node will have commands from the .DEFAULT rule added to it
871  *	if it needs them.
872  *-----------------------------------------------------------------------
873  */
874 Boolean
875 Job_CheckCommands (gn, abortProc)
876     GNode          *gn;	    	    /* The target whose commands need
877 				     * verifying */
878     void    	  (*abortProc) __P((const char *, ...));
879 			/* Function to abort with message */
880 {
881     if (OP_NOP(gn->type) && Lst_IsEmpty (gn->commands) &&
882 	(gn->type & OP_LIB) == 0) {
883 	/*
884 	 * No commands. Look for .DEFAULT rule from which we might infer
885 	 * commands
886 	 */
887 	if ((DEFAULT != NILGNODE) && !Lst_IsEmpty(DEFAULT->commands)) {
888 	    /*
889 	     * Make only looks for a .DEFAULT if the node was never the
890 	     * target of an operator, so that's what we do too. If
891 	     * a .DEFAULT was given, we substitute its commands for gn's
892 	     * commands and set the IMPSRC variable to be the target's name
893 	     * The DEFAULT node acts like a transformation rule, in that
894 	     * gn also inherits any attributes or sources attached to
895 	     * .DEFAULT itself.
896 	     */
897 	    Make_HandleUse(DEFAULT, gn);
898 	    Var_Set (IMPSRC, Var_Value (TARGET, gn), gn);
899 	} else if (Dir_MTime (gn) == 0) {
900 	    /*
901 	     * The node wasn't the target of an operator we have no .DEFAULT
902 	     * rule to go on and the target doesn't already exist. There's
903 	     * nothing more we can do for this branch. If the -k flag wasn't
904 	     * given, we stop in our tracks, otherwise we just don't update
905 	     * this node's parents so they never get examined.
906 	     */
907 	    if (gn->type & OP_OPTIONAL) {
908 		printf ("make: don't know how to make %s (ignored)\n",
909 			gn->name);
910 	    } else if (keepgoing) {
911 		printf ("make: don't know how to make %s (continuing)\n",
912 			gn->name);
913 		return (FALSE);
914 	    } else {
915 		(*abortProc) ("make: don't know how to make %s. Stop",
916 			     gn->name);
917 		return(FALSE);
918 	    }
919 	}
920     }
921     return (TRUE);
922 }
923 #ifdef RMT_WILL_WATCH
924 /*-
925  *-----------------------------------------------------------------------
926  * JobLocalInput --
927  *	Handle a pipe becoming readable. Callback function for Rmt_Watch
928  *
929  * Results:
930  *	None
931  *
932  * Side Effects:
933  *	JobDoOutput is called.
934  *
935  *-----------------------------------------------------------------------
936  */
937 /*ARGSUSED*/
938 static void
939 JobLocalInput(stream, job)
940     int	    stream; 	/* Stream that's ready (ignored) */
941     Job	    *job;   	/* Job to which the stream belongs */
942 {
943     JobDoOutput(job, FALSE);
944 }
945 #endif /* RMT_WILL_WATCH */
946 
947 /*-
948  *-----------------------------------------------------------------------
949  * JobExec --
950  *	Execute the shell for the given job. Called from JobStart and
951  *	JobRestart.
952  *
953  * Results:
954  *	None.
955  *
956  * Side Effects:
957  *	A shell is executed, outputs is altered and the Job structure added
958  *	to the job table.
959  *
960  *-----------------------------------------------------------------------
961  */
962 static void
963 JobExec(job, argv)
964     Job	    	  *job; 	/* Job to execute */
965     char    	  **argv;
966 {
967     int	    	  cpid;	    	/* ID of new child */
968 
969     if (DEBUG(JOB)) {
970 	int 	  i;
971 
972 	printf("Running %s %sly\n", job->node->name,
973 	       job->flags&JOB_REMOTE?"remote":"local");
974 	printf("\tCommand: ");
975 	for (i = 0; argv[i] != (char *)NULL; i++) {
976 	    printf("%s ", argv[i]);
977 	}
978 	printf("\n");
979     }
980 
981     /*
982      * Some jobs produce no output and it's disconcerting to have
983      * no feedback of their running (since they produce no output, the
984      * banner with their name in it never appears). This is an attempt to
985      * provide that feedback, even if nothing follows it.
986      */
987     if ((lastNode != job->node) && (job->flags & JOB_FIRST) &&
988 	!(job->flags & JOB_SILENT))
989     {
990 	printf(targFmt, job->node->name);
991 	lastNode = job->node;
992     }
993 
994 #ifdef RMT_NO_EXEC
995     if (job->flags & JOB_REMOTE) {
996 	goto jobExecFinish;
997     }
998 #endif /* RMT_NO_EXEC */
999 
1000     if ((cpid =  vfork()) == -1) {
1001 	Punt ("Cannot fork");
1002     } else if (cpid == 0) {
1003 
1004 	/*
1005 	 * Must duplicate the input stream down to the child's input and
1006 	 * reset it to the beginning (again). Since the stream was marked
1007 	 * close-on-exec, we must clear that bit in the new input.
1008 	 */
1009 	(void) dup2(fileno(job->cmdFILE), 0);
1010 	fcntl(0, F_SETFD, 0);
1011 	lseek(0, 0, L_SET);
1012 
1013 	if (usePipes) {
1014 	    /*
1015 	     * Set up the child's output to be routed through the pipe
1016 	     * we've created for it.
1017 	     */
1018 	    (void) dup2 (job->outPipe, 1);
1019 	} else {
1020 	    /*
1021 	     * We're capturing output in a file, so we duplicate the
1022 	     * descriptor to the temporary file into the standard
1023 	     * output.
1024 	     */
1025 	    (void) dup2 (job->outFd, 1);
1026 	}
1027 	/*
1028 	 * The output channels are marked close on exec. This bit was
1029 	 * duplicated by the dup2 (on some systems), so we have to clear
1030 	 * it before routing the shell's error output to the same place as
1031 	 * its standard output.
1032 	 */
1033 	fcntl(1, F_SETFD, 0);
1034 	(void) dup2 (1, 2);
1035 
1036 #ifdef USE_PGRP
1037 	/*
1038 	 * We want to switch the child into a different process family so
1039 	 * we can kill it and all its descendants in one fell swoop,
1040 	 * by killing its process family, but not commit suicide.
1041 	 */
1042 
1043 	(void) setpgrp(0, getpid());
1044 #endif USE_PGRP
1045 
1046 	(void) execv (shellPath, argv);
1047 	(void) write (2, "Could not execute shell\n",
1048 		 sizeof ("Could not execute shell"));
1049 	_exit (1);
1050     } else {
1051 	job->pid = cpid;
1052 
1053 	if (usePipes && (job->flags & JOB_FIRST) ) {
1054 	    /*
1055 	     * The first time a job is run for a node, we set the current
1056 	     * position in the buffer to the beginning and mark another
1057 	     * stream to watch in the outputs mask
1058 	     */
1059 	    job->curPos = 0;
1060 
1061 #ifdef RMT_WILL_WATCH
1062 	    Rmt_Watch(job->inPipe, JobLocalInput, job);
1063 #else
1064 	    FD_SET(job->inPipe, &outputs);
1065 #endif /* RMT_WILL_WATCH */
1066 	}
1067 
1068 	if (job->flags & JOB_REMOTE) {
1069 	    job->rmtID = 0;
1070 	} else {
1071 	    nLocal += 1;
1072 	    /*
1073 	     * XXX: Used to not happen if CUSTOMS. Why?
1074 	     */
1075 	    if (job->cmdFILE != stdout) {
1076 		fclose(job->cmdFILE);
1077 		job->cmdFILE = NULL;
1078 	    }
1079 	}
1080     }
1081 
1082 #ifdef RMT_NO_EXEC
1083 jobExecFinish:
1084 #endif
1085     /*
1086      * Now the job is actually running, add it to the table.
1087      */
1088     nJobs += 1;
1089     (void)Lst_AtEnd (jobs, (ClientData)job);
1090     if (nJobs == maxJobs) {
1091 	jobFull = TRUE;
1092     }
1093 }
1094 
1095 /*-
1096  *-----------------------------------------------------------------------
1097  * JobMakeArgv --
1098  *	Create the argv needed to execute the shell for a given job.
1099  *
1100  *
1101  * Results:
1102  *
1103  * Side Effects:
1104  *
1105  *-----------------------------------------------------------------------
1106  */
1107 static void
1108 JobMakeArgv(job, argv)
1109     Job	    	  *job;
1110     char	  **argv;
1111 {
1112     int	    	  argc;
1113     static char	  args[10]; 	/* For merged arguments */
1114 
1115     argv[0] = shellName;
1116     argc = 1;
1117 
1118     if ((commandShell->exit && (*commandShell->exit != '-')) ||
1119 	(commandShell->echo && (*commandShell->echo != '-')))
1120     {
1121 	/*
1122 	 * At least one of the flags doesn't have a minus before it, so
1123 	 * merge them together. Have to do this because the *(&(@*#*&#$#
1124 	 * Bourne shell thinks its second argument is a file to source.
1125 	 * Grrrr. Note the ten-character limitation on the combined arguments.
1126 	 */
1127 	(void)sprintf(args, "-%s%s",
1128 		      ((job->flags & JOB_IGNERR) ? "" :
1129 		       (commandShell->exit ? commandShell->exit : "")),
1130 		      ((job->flags & JOB_SILENT) ? "" :
1131 		       (commandShell->echo ? commandShell->echo : "")));
1132 
1133 	if (args[1]) {
1134 	    argv[argc] = args;
1135 	    argc++;
1136 	}
1137     } else {
1138 	if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1139 	    argv[argc] = commandShell->exit;
1140 	    argc++;
1141 	}
1142 	if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1143 	    argv[argc] = commandShell->echo;
1144 	    argc++;
1145 	}
1146     }
1147     argv[argc] = (char *)NULL;
1148 }
1149 
1150 /*-
1151  *-----------------------------------------------------------------------
1152  * JobRestart --
1153  *	Restart a job that stopped for some reason.
1154  *
1155  * Results:
1156  *	None.
1157  *
1158  * Side Effects:
1159  *	jobFull will be set if the job couldn't be run.
1160  *
1161  *-----------------------------------------------------------------------
1162  */
1163 static void
1164 JobRestart(job)
1165     Job 	  *job;    	/* Job to restart */
1166 {
1167     if (job->flags & JOB_REMIGRATE) {
1168 	if (DEBUG(JOB)) {
1169 	    printf("Remigrating %x\n", job->pid);
1170 	}
1171 	if (nLocal != maxLocal) {
1172 		/*
1173 		 * Job cannot be remigrated, but there's room on the local
1174 		 * machine, so resume the job and note that another
1175 		 * local job has started.
1176 		 */
1177 		if (DEBUG(JOB)) {
1178 		    printf("resuming on local machine\n");
1179 	        }
1180 		KILL(job->pid, SIGCONT);
1181 		nLocal +=1;
1182 		job->flags &= ~(JOB_REMIGRATE|JOB_RESUME);
1183 	} else {
1184 		/*
1185 		 * Job cannot be restarted. Mark the table as full and
1186 		 * place the job back on the list of stopped jobs.
1187 		 */
1188 		if (DEBUG(JOB)) {
1189 		    printf("holding\n");
1190 		}
1191 		(void)Lst_AtFront(stoppedJobs, (ClientData)job);
1192 		jobFull = TRUE;
1193 		if (DEBUG(JOB)) {
1194 		    printf("Job queue is full.\n");
1195 		}
1196 		return;
1197 	}
1198 
1199 	(void)Lst_AtEnd(jobs, (ClientData)job);
1200 	nJobs += 1;
1201 	if (nJobs == maxJobs) {
1202 	    jobFull = TRUE;
1203 	    if (DEBUG(JOB)) {
1204 		printf("Job queue is full.\n");
1205 	    }
1206 	}
1207     } else if (job->flags & JOB_RESTART) {
1208 	/*
1209 	 * Set up the control arguments to the shell. This is based on the
1210 	 * flags set earlier for this job. If the JOB_IGNERR flag is clear,
1211 	 * the 'exit' flag of the commandShell is used to cause it to exit
1212 	 * upon receiving an error. If the JOB_SILENT flag is clear, the
1213 	 * 'echo' flag of the commandShell is used to get it to start echoing
1214 	 * as soon as it starts processing commands.
1215 	 */
1216 	char	  *argv[4];
1217 
1218 	JobMakeArgv(job, argv);
1219 
1220 	if (DEBUG(JOB)) {
1221 	    printf("Restarting %s...", job->node->name);
1222 	}
1223 	if (((nLocal >= maxLocal) && ! (job->flags & JOB_SPECIAL))) {
1224 		/*
1225 		 * Can't be exported and not allowed to run locally -- put it
1226 		 * back on the hold queue and mark the table full
1227 		 */
1228 		if (DEBUG(JOB)) {
1229 		    printf("holding\n");
1230 		}
1231 		(void)Lst_AtFront(stoppedJobs, (ClientData)job);
1232 		jobFull = TRUE;
1233 		if (DEBUG(JOB)) {
1234 		    printf("Job queue is full.\n");
1235 		}
1236 		return;
1237 	} else {
1238 		/*
1239 		 * Job may be run locally.
1240 		 */
1241 		if (DEBUG(JOB)) {
1242 		    printf("running locally\n");
1243 		}
1244 		job->flags &= ~JOB_REMOTE;
1245 	}
1246 	JobExec(job, argv);
1247     } else {
1248 	/*
1249 	 * The job has stopped and needs to be restarted. Why it stopped,
1250 	 * we don't know...
1251 	 */
1252 	if (DEBUG(JOB)) {
1253 	    printf("Resuming %s...", job->node->name);
1254 	}
1255 	if (((job->flags & JOB_REMOTE) ||
1256 	     (nLocal < maxLocal) ||
1257 	     (((job->flags & JOB_SPECIAL)) &&
1258 	      (maxLocal == 0))) &&
1259 	    (nJobs != maxJobs))
1260 	{
1261 	    /*
1262 	     * If the job is remote, it's ok to resume it as long as the
1263 	     * maximum concurrency won't be exceeded. If it's local and
1264 	     * we haven't reached the local concurrency limit already (or the
1265 	     * job must be run locally and maxLocal is 0), it's also ok to
1266 	     * resume it.
1267 	     */
1268 	    Boolean error;
1269 	    extern int errno;
1270 	    union wait status;
1271 
1272 #ifdef RMT_WANTS_SIGNALS
1273 	    if (job->flags & JOB_REMOTE) {
1274 		error = !Rmt_Signal(job, SIGCONT);
1275 	    } else
1276 #endif	/* RMT_WANTS_SIGNALS */
1277 		error = (KILL(job->pid, SIGCONT) != 0);
1278 
1279 	    if (!error) {
1280 		/*
1281 		 * Make sure the user knows we've continued the beast and
1282 		 * actually put the thing in the job table.
1283 		 */
1284 		job->flags |= JOB_CONTINUING;
1285 		status.w_termsig = SIGCONT;
1286 		JobFinish(job, status);
1287 
1288 		job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1289 		if (DEBUG(JOB)) {
1290 		    printf("done\n");
1291 		}
1292 	    } else {
1293 		Error("couldn't resume %s: %s",
1294 		    job->node->name, strerror(errno));
1295 		status.w_status = 0;
1296 		status.w_retcode = 1;
1297 		JobFinish(job, status);
1298 	    }
1299 	} else {
1300 	    /*
1301 	     * Job cannot be restarted. Mark the table as full and
1302 	     * place the job back on the list of stopped jobs.
1303 	     */
1304 	    if (DEBUG(JOB)) {
1305 		printf("table full\n");
1306 	    }
1307 	    (void)Lst_AtFront(stoppedJobs, (ClientData)job);
1308 	    jobFull = TRUE;
1309 	    if (DEBUG(JOB)) {
1310 		printf("Job queue is full.\n");
1311 	    }
1312 	}
1313     }
1314 }
1315 
1316 /*-
1317  *-----------------------------------------------------------------------
1318  * JobStart  --
1319  *	Start a target-creation process going for the target described
1320  *	by the graph node gn.
1321  *
1322  * Results:
1323  *	JOB_ERROR if there was an error in the commands, JOB_FINISHED
1324  *	if there isn't actually anything left to do for the job and
1325  *	JOB_RUNNING if the job has been started.
1326  *
1327  * Side Effects:
1328  *	A new Job node is created and added to the list of running
1329  *	jobs. PMake is forked and a child shell created.
1330  *-----------------------------------------------------------------------
1331  */
1332 static int
1333 JobStart (gn, flags, previous)
1334     GNode         *gn;	      /* target to create */
1335     short	  flags;      /* flags for the job to override normal ones.
1336 			       * e.g. JOB_SPECIAL or JOB_IGNDOTS */
1337     Job 	  *previous;  /* The previous Job structure for this node,
1338 			       * if any. */
1339 {
1340     register Job  *job;       /* new job descriptor */
1341     char	  *argv[4];   /* Argument vector to shell */
1342     static int    jobno = 0;  /* job number of catching output in a file */
1343     Boolean	  cmdsOK;     /* true if the nodes commands were all right */
1344     Boolean 	  local;      /* Set true if the job was run locally */
1345     Boolean 	  noExec;     /* Set true if we decide not to run the job */
1346 
1347     if (previous != (Job *)NULL) {
1348 	previous->flags &= ~ (JOB_FIRST|JOB_IGNERR|JOB_SILENT|JOB_REMOTE);
1349 	job = previous;
1350     } else {
1351 	job = (Job *) emalloc (sizeof (Job));
1352 	if (job == (Job *)NULL) {
1353 	    Punt("JobStart out of memory");
1354 	}
1355 	flags |= JOB_FIRST;
1356     }
1357 
1358     job->node = gn;
1359     job->tailCmds = NILLNODE;
1360 
1361     /*
1362      * Set the initial value of the flags for this job based on the global
1363      * ones and the node's attributes... Any flags supplied by the caller
1364      * are also added to the field.
1365      */
1366     job->flags = 0;
1367     if (Targ_Ignore (gn)) {
1368 	job->flags |= JOB_IGNERR;
1369     }
1370     if (Targ_Silent (gn)) {
1371 	job->flags |= JOB_SILENT;
1372     }
1373     job->flags |= flags;
1374 
1375     /*
1376      * Check the commands now so any attributes from .DEFAULT have a chance
1377      * to migrate to the node
1378      */
1379     if (job->flags & JOB_FIRST) {
1380 	cmdsOK = Job_CheckCommands(gn, Error);
1381     } else {
1382 	cmdsOK = TRUE;
1383     }
1384 
1385     /*
1386      * If the -n flag wasn't given, we open up OUR (not the child's)
1387      * temporary file to stuff commands in it. The thing is rd/wr so we don't
1388      * need to reopen it to feed it to the shell. If the -n flag *was* given,
1389      * we just set the file to be stdout. Cute, huh?
1390      */
1391     if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1392 	/*
1393 	 * We're serious here, but if the commands were bogus, we're
1394 	 * also dead...
1395 	 */
1396 	if (!cmdsOK) {
1397 	    DieHorribly();
1398 	}
1399 
1400 	job->cmdFILE = fopen (tfile, "w+");
1401 	if (job->cmdFILE == (FILE *) NULL) {
1402 	    Punt ("Could not open %s", tfile);
1403 	}
1404 	fcntl(fileno(job->cmdFILE), F_SETFD, 1);
1405 	/*
1406 	 * Send the commands to the command file, flush all its buffers then
1407 	 * rewind and remove the thing.
1408 	 */
1409 	noExec = FALSE;
1410 
1411 	/*
1412 	 * used to be backwards; replace when start doing multiple commands
1413 	 * per shell.
1414 	 */
1415 	if (compatMake) {
1416 	    /*
1417 	     * Be compatible: If this is the first time for this node,
1418 	     * verify its commands are ok and open the commands list for
1419 	     * sequential access by later invocations of JobStart.
1420 	     * Once that is done, we take the next command off the list
1421 	     * and print it to the command file. If the command was an
1422 	     * ellipsis, note that there's nothing more to execute.
1423 	     */
1424 	    if ((job->flags&JOB_FIRST) && (Lst_Open(gn->commands) != SUCCESS)){
1425 		cmdsOK = FALSE;
1426 	    } else {
1427 		LstNode	ln = Lst_Next (gn->commands);
1428 
1429 		if ((ln == NILLNODE) ||
1430 		    JobPrintCommand ((char *)Lst_Datum (ln), job))
1431 		{
1432 		    noExec = TRUE;
1433 		    Lst_Close (gn->commands);
1434 		}
1435 		if (noExec && !(job->flags & JOB_FIRST)) {
1436 		    /*
1437 		     * If we're not going to execute anything, the job
1438 		     * is done and we need to close down the various
1439 		     * file descriptors we've opened for output, then
1440 		     * call JobDoOutput to catch the final characters or
1441 		     * send the file to the screen... Note that the i/o streams
1442 		     * are only open if this isn't the first job.
1443 		     * Note also that this could not be done in
1444 		     * Job_CatchChildren b/c it wasn't clear if there were
1445 		     * more commands to execute or not...
1446 		     */
1447 		    if (usePipes) {
1448 #ifdef RMT_WILL_WATCH
1449 			Rmt_Ignore(job->inPipe);
1450 #else
1451 			FD_CLR(job->inPipe, &outputs);
1452 #endif
1453 			if (job->outPipe != job->inPipe) {
1454 			    (void)close (job->outPipe);
1455 			}
1456 			JobDoOutput (job, TRUE);
1457 			(void)close (job->inPipe);
1458 		    } else {
1459 			(void)close (job->outFd);
1460 			JobDoOutput (job, TRUE);
1461 		    }
1462 		}
1463 	    }
1464 	} else {
1465 	    /*
1466 	     * We can do all the commands at once. hooray for sanity
1467 	     */
1468 	    numCommands = 0;
1469 	    Lst_ForEach (gn->commands, JobPrintCommand, (ClientData)job);
1470 
1471 	    /*
1472 	     * If we didn't print out any commands to the shell script,
1473 	     * there's not much point in executing the shell, is there?
1474 	     */
1475 	    if (numCommands == 0) {
1476 		noExec = TRUE;
1477 	    }
1478 	}
1479     } else if (noExecute) {
1480 	/*
1481 	 * Not executing anything -- just print all the commands to stdout
1482 	 * in one fell swoop. This will still set up job->tailCmds correctly.
1483 	 */
1484 	if (lastNode != gn) {
1485 	    printf (targFmt, gn->name);
1486 	    lastNode = gn;
1487 	}
1488 	job->cmdFILE = stdout;
1489 	/*
1490 	 * Only print the commands if they're ok, but don't die if they're
1491 	 * not -- just let the user know they're bad and keep going. It
1492 	 * doesn't do any harm in this case and may do some good.
1493 	 */
1494 	if (cmdsOK) {
1495 	    Lst_ForEach(gn->commands, JobPrintCommand, (ClientData)job);
1496 	}
1497 	/*
1498 	 * Don't execute the shell, thank you.
1499 	 */
1500 	noExec = TRUE;
1501     } else {
1502 	/*
1503 	 * Just touch the target and note that no shell should be executed.
1504 	 * Set cmdFILE to stdout to make life easier. Check the commands, too,
1505 	 * but don't die if they're no good -- it does no harm to keep working
1506 	 * up the graph.
1507 	 */
1508 	job->cmdFILE = stdout;
1509     	Job_Touch (gn, job->flags&JOB_SILENT);
1510 	noExec = TRUE;
1511     }
1512 
1513     /*
1514      * If we're not supposed to execute a shell, don't.
1515      */
1516     if (noExec) {
1517 	/*
1518 	 * Unlink and close the command file if we opened one
1519 	 */
1520 	if (job->cmdFILE != stdout) {
1521 	    (void) unlink (tfile);
1522 	    fclose(job->cmdFILE);
1523 	} else {
1524 	    fflush (stdout);
1525 	}
1526 
1527 	/*
1528 	 * We only want to work our way up the graph if we aren't here because
1529 	 * the commands for the job were no good.
1530 	 */
1531 	if (cmdsOK) {
1532 	    if (aborting == 0) {
1533 		if (job->tailCmds != NILLNODE) {
1534 		    Lst_ForEachFrom(job->node->commands, job->tailCmds,
1535 				    JobSaveCommand,
1536 				    (ClientData)job->node);
1537 		}
1538 		Make_Update(job->node);
1539 	    }
1540 	    free((Address)job);
1541 	    return(JOB_FINISHED);
1542 	} else {
1543 	    free((Address)job);
1544 	    return(JOB_ERROR);
1545 	}
1546     } else {
1547 	fflush (job->cmdFILE);
1548 	(void) unlink (tfile);
1549     }
1550 
1551     /*
1552      * Set up the control arguments to the shell. This is based on the flags
1553      * set earlier for this job.
1554      */
1555     JobMakeArgv(job, argv);
1556 
1557     /*
1558      * If we're using pipes to catch output, create the pipe by which we'll
1559      * get the shell's output. If we're using files, print out that we're
1560      * starting a job and then set up its temporary-file name. This is just
1561      * tfile with two extra digits tacked on -- jobno.
1562      */
1563     if (job->flags & JOB_FIRST) {
1564 	if (usePipes) {
1565 	    int fd[2];
1566 	    (void) pipe(fd);
1567 	    job->inPipe = fd[0];
1568 	    job->outPipe = fd[1];
1569 	    (void)fcntl (job->inPipe, F_SETFD, 1);
1570 	    (void)fcntl (job->outPipe, F_SETFD, 1);
1571 	} else {
1572 	    printf ("Remaking `%s'\n", gn->name);
1573 	    fflush (stdout);
1574 	    sprintf (job->outFile, "%s%02d", tfile, jobno);
1575 	    jobno = (jobno + 1) % 100;
1576 	    job->outFd = open(job->outFile,O_WRONLY|O_CREAT|O_APPEND,0600);
1577 	    (void)fcntl (job->outFd, F_SETFD, 1);
1578 	}
1579     }
1580 
1581     local = TRUE;
1582 
1583     if (local && (((nLocal >= maxLocal) &&
1584 	 !(job->flags & JOB_SPECIAL) &&
1585 	 (maxLocal != 0))))
1586     {
1587 	/*
1588 	 * The job can only be run locally, but we've hit the limit of
1589 	 * local concurrency, so put the job on hold until some other job
1590 	 * finishes. Note that the special jobs (.BEGIN, .INTERRUPT and .END)
1591 	 * may be run locally even when the local limit has been reached
1592 	 * (e.g. when maxLocal == 0), though they will be exported if at
1593 	 * all possible.
1594 	 */
1595 	jobFull = TRUE;
1596 
1597 	if (DEBUG(JOB)) {
1598 	    printf("Can only run job locally.\n");
1599 	}
1600 	job->flags |= JOB_RESTART;
1601 	(void)Lst_AtEnd(stoppedJobs, (ClientData)job);
1602     } else {
1603 	if ((nLocal >= maxLocal) && local) {
1604 	    /*
1605 	     * If we're running this job locally as a special case (see above),
1606 	     * at least say the table is full.
1607 	     */
1608 	    jobFull = TRUE;
1609 	    if (DEBUG(JOB)) {
1610 		printf("Local job queue is full.\n");
1611 	    }
1612 	}
1613 	JobExec(job, argv);
1614     }
1615     return(JOB_RUNNING);
1616 }
1617 
1618 /*-
1619  *-----------------------------------------------------------------------
1620  * JobDoOutput  --
1621  *	This function is called at different times depending on
1622  *	whether the user has specified that output is to be collected
1623  *	via pipes or temporary files. In the former case, we are called
1624  *	whenever there is something to read on the pipe. We collect more
1625  *	output from the given job and store it in the job's outBuf. If
1626  *	this makes up a line, we print it tagged by the job's identifier,
1627  *	as necessary.
1628  *	If output has been collected in a temporary file, we open the
1629  *	file and read it line by line, transfering it to our own
1630  *	output channel until the file is empty. At which point we
1631  *	remove the temporary file.
1632  *	In both cases, however, we keep our figurative eye out for the
1633  *	'noPrint' line for the shell from which the output came. If
1634  *	we recognize a line, we don't print it. If the command is not
1635  *	alone on the line (the character after it is not \0 or \n), we
1636  *	do print whatever follows it.
1637  *
1638  * Results:
1639  *	None
1640  *
1641  * Side Effects:
1642  *	curPos may be shifted as may the contents of outBuf.
1643  *-----------------------------------------------------------------------
1644  */
1645 static void
1646 JobDoOutput (job, finish)
1647     register Job   *job;	  /* the job whose output needs printing */
1648     Boolean	   finish;	  /* TRUE if this is the last time we'll be
1649 				   * called for this job */
1650 {
1651     Boolean       gotNL = FALSE;  /* true if got a newline */
1652     register int  nr;	      	  /* number of bytes read */
1653     register int  i;	      	  /* auxiliary index into outBuf */
1654     register int  max;	      	  /* limit for i (end of current data) */
1655     int		  nRead;      	  /* (Temporary) number of bytes read */
1656 
1657     FILE      	  *oFILE;	  /* Stream pointer to shell's output file */
1658     char          inLine[132];
1659 
1660 
1661     if (usePipes) {
1662 	/*
1663 	 * Read as many bytes as will fit in the buffer.
1664 	 */
1665 end_loop:
1666 
1667 	nRead = read (job->inPipe, &job->outBuf[job->curPos],
1668 			 JOB_BUFSIZE - job->curPos);
1669 	if (nRead < 0) {
1670 	    if (DEBUG(JOB)) {
1671 		perror("JobDoOutput(piperead)");
1672 	    }
1673 	    nr = 0;
1674 	} else {
1675 	    nr = nRead;
1676 	}
1677 
1678 	/*
1679 	 * If we hit the end-of-file (the job is dead), we must flush its
1680 	 * remaining output, so pretend we read a newline if there's any
1681 	 * output remaining in the buffer.
1682 	 * Also clear the 'finish' flag so we stop looping.
1683 	 */
1684 	if ((nr == 0) && (job->curPos != 0)) {
1685 	    job->outBuf[job->curPos] = '\n';
1686 	    nr = 1;
1687 	    finish = FALSE;
1688 	} else if (nr == 0) {
1689 	    finish = FALSE;
1690 	}
1691 
1692 	/*
1693 	 * Look for the last newline in the bytes we just got. If there is
1694 	 * one, break out of the loop with 'i' as its index and gotNL set
1695 	 * TRUE.
1696 	 */
1697 	max = job->curPos + nr;
1698 	for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1699 	    if (job->outBuf[i] == '\n') {
1700 		gotNL = TRUE;
1701 		break;
1702 	    } else if (job->outBuf[i] == '\0') {
1703 		/*
1704 		 * Why?
1705 		 */
1706 		job->outBuf[i] = ' ';
1707 	    }
1708 	}
1709 
1710 	if (!gotNL) {
1711 	    job->curPos += nr;
1712 	    if (job->curPos == JOB_BUFSIZE) {
1713 		/*
1714 		 * If we've run out of buffer space, we have no choice
1715 		 * but to print the stuff. sigh.
1716 		 */
1717 		gotNL = TRUE;
1718 		i = job->curPos;
1719 	    }
1720 	}
1721 	if (gotNL) {
1722 	    /*
1723 	     * Need to send the output to the screen. Null terminate it
1724 	     * first, overwriting the newline character if there was one.
1725 	     * So long as the line isn't one we should filter (according
1726 	     * to the shell description), we print the line, preceeded
1727 	     * by a target banner if this target isn't the same as the
1728 	     * one for which we last printed something.
1729 	     * The rest of the data in the buffer are then shifted down
1730 	     * to the start of the buffer and curPos is set accordingly.
1731 	     */
1732 	    job->outBuf[i] = '\0';
1733 	    if (i >= job->curPos) {
1734 		register char	*cp, *ecp;
1735 
1736 		cp = job->outBuf;
1737 		if (commandShell->noPrint) {
1738 		    ecp = Str_FindSubstring(job->outBuf,
1739 					    commandShell->noPrint);
1740 		    while (ecp != (char *)NULL) {
1741 			if (cp != ecp) {
1742 			    *ecp = '\0';
1743 			    if (job->node != lastNode) {
1744 				printf (targFmt, job->node->name);
1745 				lastNode = job->node;
1746 			    }
1747 			    /*
1748 			     * The only way there wouldn't be a newline after
1749 			     * this line is if it were the last in the buffer.
1750 			     * however, since the non-printable comes after it,
1751 			     * there must be a newline, so we don't print one.
1752 			     */
1753 			    printf ("%s", cp);
1754 			}
1755 			cp = ecp + commandShell->noPLen;
1756 			if (cp != &job->outBuf[i]) {
1757 			    /*
1758 			     * Still more to print, look again after skipping
1759 			     * the whitespace following the non-printable
1760 			     * command....
1761 			     */
1762 			    cp++;
1763 			    while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
1764 				cp++;
1765 			    }
1766 			    ecp = Str_FindSubstring (cp,
1767 						     commandShell->noPrint);
1768 			} else {
1769 			    break;
1770 			}
1771 		    }
1772 		}
1773 
1774 		/*
1775 		 * There's still more in that thar buffer. This time, though,
1776 		 * we know there's no newline at the end, so we add one of
1777 		 * our own free will.
1778 		 */
1779 		if (*cp != '\0') {
1780 		    if (job->node != lastNode) {
1781 			printf (targFmt, job->node->name);
1782 			lastNode = job->node;
1783 		    }
1784 		    printf ("%s\n", cp);
1785 		}
1786 
1787 		fflush (stdout);
1788 	    }
1789 	    if (i < max - 1) {
1790 		/* shift the remaining characters down */
1791 		memcpy ( job->outBuf, &job->outBuf[i + 1], max - (i + 1));
1792 		job->curPos = max - (i + 1);
1793 
1794 	    } else {
1795 		/*
1796 		 * We have written everything out, so we just start over
1797 		 * from the start of the buffer. No copying. No nothing.
1798 		 */
1799 		job->curPos = 0;
1800 	    }
1801 	}
1802 	if (finish) {
1803 	    /*
1804 	     * If the finish flag is true, we must loop until we hit
1805 	     * end-of-file on the pipe. This is guaranteed to happen eventually
1806 	     * since the other end of the pipe is now closed (we closed it
1807 	     * explicitly and the child has exited). When we do get an EOF,
1808 	     * finish will be set FALSE and we'll fall through and out.
1809 	     */
1810 	    goto end_loop;
1811 	}
1812     } else {
1813 	/*
1814 	 * We've been called to retrieve the output of the job from the
1815 	 * temporary file where it's been squirreled away. This consists of
1816 	 * opening the file, reading the output line by line, being sure not
1817 	 * to print the noPrint line for the shell we used, then close and
1818 	 * remove the temporary file. Very simple.
1819 	 *
1820 	 * Change to read in blocks and do FindSubString type things as for
1821 	 * pipes? That would allow for "@echo -n..."
1822 	 */
1823 	oFILE = fopen (job->outFile, "r");
1824 	if (oFILE != (FILE *) NULL) {
1825 	    printf ("Results of making %s:\n", job->node->name);
1826 	    while (fgets (inLine, sizeof(inLine), oFILE) != NULL) {
1827 		register char	*cp, *ecp, *endp;
1828 
1829 		cp = inLine;
1830 		endp = inLine + strlen(inLine);
1831 		if (endp[-1] == '\n') {
1832 		    *--endp = '\0';
1833 		}
1834 		if (commandShell->noPrint) {
1835 		    ecp = Str_FindSubstring(cp, commandShell->noPrint);
1836 		    while (ecp != (char *)NULL) {
1837 			if (cp != ecp) {
1838 			    *ecp = '\0';
1839 			    /*
1840 			     * The only way there wouldn't be a newline after
1841 			     * this line is if it were the last in the buffer.
1842 			     * however, since the non-printable comes after it,
1843 			     * there must be a newline, so we don't print one.
1844 			     */
1845 			    printf ("%s", cp);
1846 			}
1847 			cp = ecp + commandShell->noPLen;
1848 			if (cp != endp) {
1849 			    /*
1850 			     * Still more to print, look again after skipping
1851 			     * the whitespace following the non-printable
1852 			     * command....
1853 			     */
1854 			    cp++;
1855 			    while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
1856 				cp++;
1857 			    }
1858 			    ecp = Str_FindSubstring(cp, commandShell->noPrint);
1859 			} else {
1860 			    break;
1861 			}
1862 		    }
1863 		}
1864 
1865 		/*
1866 		 * There's still more in that thar buffer. This time, though,
1867 		 * we know there's no newline at the end, so we add one of
1868 		 * our own free will.
1869 		 */
1870 		if (*cp != '\0') {
1871 		    printf ("%s\n", cp);
1872 		}
1873 	    }
1874 	    fclose (oFILE);
1875 	    (void) unlink (job->outFile);
1876 	}
1877     }
1878     fflush(stdout);
1879 }
1880 
1881 /*-
1882  *-----------------------------------------------------------------------
1883  * Job_CatchChildren --
1884  *	Handle the exit of a child. Called from Make_Make.
1885  *
1886  * Results:
1887  *	none.
1888  *
1889  * Side Effects:
1890  *	The job descriptor is removed from the list of children.
1891  *
1892  * Notes:
1893  *	We do waits, blocking or not, according to the wisdom of our
1894  *	caller, until there are no more children to report. For each
1895  *	job, call JobFinish to finish things off. This will take care of
1896  *	putting jobs on the stoppedJobs queue.
1897  *
1898  *-----------------------------------------------------------------------
1899  */
1900 void
1901 Job_CatchChildren (block)
1902     Boolean	  block;    	/* TRUE if should block on the wait. */
1903 {
1904     int    	  pid;	    	/* pid of dead child */
1905     register Job  *job;	    	/* job descriptor for dead child */
1906     LstNode       jnode;    	/* list element for finding job */
1907     union wait	  status;   	/* Exit/termination status */
1908 
1909     /*
1910      * Don't even bother if we know there's no one around.
1911      */
1912     if (nLocal == 0) {
1913 	return;
1914     }
1915 
1916     while ((pid = wait3((int *)&status, (block?0:WNOHANG)|WUNTRACED,
1917 			(struct rusage *)0)) > 0)
1918     {
1919 	if (DEBUG(JOB))
1920 	    printf("Process %d exited or stopped.\n", pid);
1921 
1922 
1923 	jnode = Lst_Find (jobs, (ClientData)pid, JobCmpPid);
1924 
1925 	if (jnode == NILLNODE) {
1926 	    if (WIFSIGNALED(status) && (status.w_termsig == SIGCONT)) {
1927 		jnode = Lst_Find(stoppedJobs, (ClientData)pid, JobCmpPid);
1928 		if (jnode == NILLNODE) {
1929 		    Error("Resumed child (%d) not in table", pid);
1930 		    continue;
1931 		}
1932 		job = (Job *)Lst_Datum(jnode);
1933 		(void)Lst_Remove(stoppedJobs, jnode);
1934 	    } else {
1935 		Error ("Child (%d) not in table?", pid);
1936 		continue;
1937 	    }
1938 	} else {
1939 	    job = (Job *) Lst_Datum (jnode);
1940 	    (void)Lst_Remove (jobs, jnode);
1941 	    nJobs -= 1;
1942 	    if (jobFull && DEBUG(JOB)) {
1943 		printf("Job queue is no longer full.\n");
1944 	    }
1945 	    jobFull = FALSE;
1946 	    nLocal -= 1;
1947 	}
1948 
1949 	JobFinish (job, status);
1950     }
1951 }
1952 
1953 /*-
1954  *-----------------------------------------------------------------------
1955  * Job_CatchOutput --
1956  *	Catch the output from our children, if we're using
1957  *	pipes do so. Otherwise just block time until we get a
1958  *	signal (most likely a SIGCHLD) since there's no point in
1959  *	just spinning when there's nothing to do and the reaping
1960  *	of a child can wait for a while.
1961  *
1962  * Results:
1963  *	None
1964  *
1965  * Side Effects:
1966  *	Output is read from pipes if we're piping.
1967  * -----------------------------------------------------------------------
1968  */
1969 void
1970 Job_CatchOutput ()
1971 {
1972     int           	  nfds;
1973     struct timeval	  timeout;
1974     fd_set           	  readfds;
1975     register LstNode	  ln;
1976     register Job   	  *job;
1977 #ifdef RMT_WILL_WATCH
1978     int	    	  	  pnJobs;   	/* Previous nJobs */
1979 #endif
1980 
1981     fflush(stdout);
1982 #ifdef RMT_WILL_WATCH
1983     pnJobs = nJobs;
1984 
1985     /*
1986      * It is possible for us to be called with nJobs equal to 0. This happens
1987      * if all the jobs finish and a job that is stopped cannot be run
1988      * locally (eg if maxLocal is 0) and cannot be exported. The job will
1989      * be placed back on the stoppedJobs queue, Job_Empty() will return false,
1990      * Make_Run will call us again when there's nothing for which to wait.
1991      * nJobs never changes, so we loop forever. Hence the check. It could
1992      * be argued that we should sleep for a bit so as not to swamp the
1993      * exportation system with requests. Perhaps we should.
1994      *
1995      * NOTE: IT IS THE RESPONSIBILITY OF Rmt_Wait TO CALL Job_CatchChildren
1996      * IN A TIMELY FASHION TO CATCH ANY LOCALLY RUNNING JOBS THAT EXIT.
1997      * It may use the variable nLocal to determine if it needs to call
1998      * Job_CatchChildren (if nLocal is 0, there's nothing for which to
1999      * wait...)
2000      */
2001     while (nJobs != 0 && pnJobs == nJobs) {
2002 	Rmt_Wait();
2003     }
2004 #else
2005     if (usePipes) {
2006 	readfds = outputs;
2007 	timeout.tv_sec = SEL_SEC;
2008 	timeout.tv_usec = SEL_USEC;
2009 
2010 	if ((nfds = select (FD_SETSIZE, &readfds, (fd_set *) 0, (fd_set *) 0, &timeout)) < 0)
2011 	{
2012 	    return;
2013 	} else {
2014 	    if (Lst_Open (jobs) == FAILURE) {
2015 		Punt ("Cannot open job table");
2016 	    }
2017 	    while (nfds && (ln = Lst_Next (jobs)) != NILLNODE) {
2018 		job = (Job *) Lst_Datum (ln);
2019 		if (FD_ISSET(job->inPipe, &readfds)) {
2020 		    JobDoOutput (job, FALSE);
2021 		    nfds -= 1;
2022 		}
2023 	    }
2024 	    Lst_Close (jobs);
2025 	}
2026     }
2027 #endif /* RMT_WILL_WATCH */
2028 }
2029 
2030 /*-
2031  *-----------------------------------------------------------------------
2032  * Job_Make --
2033  *	Start the creation of a target. Basically a front-end for
2034  *	JobStart used by the Make module.
2035  *
2036  * Results:
2037  *	None.
2038  *
2039  * Side Effects:
2040  *	Another job is started.
2041  *
2042  *-----------------------------------------------------------------------
2043  */
2044 void
2045 Job_Make (gn)
2046     GNode   *gn;
2047 {
2048     (void)JobStart (gn, 0, (Job *)NULL);
2049 }
2050 
2051 /*-
2052  *-----------------------------------------------------------------------
2053  * Job_Init --
2054  *	Initialize the process module
2055  *
2056  * Results:
2057  *	none
2058  *
2059  * Side Effects:
2060  *	lists and counters are initialized
2061  *-----------------------------------------------------------------------
2062  */
2063 void
2064 Job_Init (maxproc, maxlocal)
2065     int           maxproc;  /* the greatest number of jobs which may be
2066 			     * running at one time */
2067     int	    	  maxlocal; /* the greatest number of local jobs which may
2068 			     * be running at once. */
2069 {
2070     GNode         *begin;     /* node for commands to do at the very start */
2071 
2072     sprintf (tfile, "/tmp/make%05d", getpid());
2073 
2074     jobs =  	  Lst_Init (FALSE);
2075     stoppedJobs = Lst_Init(FALSE);
2076     maxJobs = 	  maxproc;
2077     maxLocal = 	  maxlocal;
2078     nJobs = 	  0;
2079     nLocal = 	  0;
2080     jobFull = 	  FALSE;
2081 
2082     aborting = 	  0;
2083     errors = 	  0;
2084 
2085     lastNode =	  NILGNODE;
2086 
2087     if (maxJobs == 1) {
2088 	/*
2089 	 * If only one job can run at a time, there's no need for a banner,
2090 	 * no is there?
2091 	 */
2092 	targFmt = "";
2093     } else {
2094 	targFmt = TARG_FMT;
2095     }
2096 
2097     if (shellPath == (char *) NULL) {
2098 	/*
2099 	 * The user didn't specify a shell to use, so we are using the
2100 	 * default one... Both the absolute path and the last component
2101 	 * must be set. The last component is taken from the 'name' field
2102 	 * of the default shell description pointed-to by commandShell.
2103 	 * All default shells are located in _PATH_DEFSHELLDIR.
2104 	 */
2105 	shellName = commandShell->name;
2106 	shellPath = str_concat (_PATH_DEFSHELLDIR, shellName, STR_ADDSLASH);
2107     }
2108 
2109     if (commandShell->exit == (char *)NULL) {
2110 	commandShell->exit = "";
2111     }
2112     if (commandShell->echo == (char *)NULL) {
2113 	commandShell->echo = "";
2114     }
2115 
2116     /*
2117      * Catch the four signals that POSIX specifies if they aren't ignored.
2118      * JobPassSig will take care of calling JobInterrupt if appropriate.
2119      */
2120     if (signal (SIGINT, SIG_IGN) != SIG_IGN) {
2121 	signal (SIGINT, JobPassSig);
2122     }
2123     if (signal (SIGHUP, SIG_IGN) != SIG_IGN) {
2124 	signal (SIGHUP, JobPassSig);
2125     }
2126     if (signal (SIGQUIT, SIG_IGN) != SIG_IGN) {
2127 	signal (SIGQUIT, JobPassSig);
2128     }
2129     if (signal (SIGTERM, SIG_IGN) != SIG_IGN) {
2130 	signal (SIGTERM, JobPassSig);
2131     }
2132     /*
2133      * There are additional signals that need to be caught and passed if
2134      * either the export system wants to be told directly of signals or if
2135      * we're giving each job its own process group (since then it won't get
2136      * signals from the terminal driver as we own the terminal)
2137      */
2138 #if defined(RMT_WANTS_SIGNALS) || defined(USE_PGRP)
2139     if (signal (SIGTSTP, SIG_IGN) != SIG_IGN) {
2140 	signal (SIGTSTP, JobPassSig);
2141     }
2142     if (signal (SIGTTOU, SIG_IGN) != SIG_IGN) {
2143 	signal (SIGTTOU, JobPassSig);
2144     }
2145     if (signal (SIGTTIN, SIG_IGN) != SIG_IGN) {
2146 	signal (SIGTTIN, JobPassSig);
2147     }
2148     if (signal (SIGWINCH, SIG_IGN) != SIG_IGN) {
2149 	signal (SIGWINCH, JobPassSig);
2150     }
2151 #endif
2152 
2153     begin = Targ_FindNode (".BEGIN", TARG_NOCREATE);
2154 
2155     if (begin != NILGNODE) {
2156 	JobStart (begin, JOB_SPECIAL, (Job *)0);
2157 	while (nJobs) {
2158 	    Job_CatchOutput();
2159 #ifndef RMT_WILL_WATCH
2160 	    Job_CatchChildren (!usePipes);
2161 #endif /* RMT_WILL_WATCH */
2162 	}
2163     }
2164     postCommands = Targ_FindNode (".END", TARG_CREATE);
2165 }
2166 
2167 /*-
2168  *-----------------------------------------------------------------------
2169  * Job_Full --
2170  *	See if the job table is full. It is considered full if it is OR
2171  *	if we are in the process of aborting OR if we have
2172  *	reached/exceeded our local quota. This prevents any more jobs
2173  *	from starting up.
2174  *
2175  * Results:
2176  *	TRUE if the job table is full, FALSE otherwise
2177  * Side Effects:
2178  *	None.
2179  *-----------------------------------------------------------------------
2180  */
2181 Boolean
2182 Job_Full ()
2183 {
2184     return (aborting || jobFull);
2185 }
2186 
2187 /*-
2188  *-----------------------------------------------------------------------
2189  * Job_Empty --
2190  *	See if the job table is empty.  Because the local concurrency may
2191  *	be set to 0, it is possible for the job table to become empty,
2192  *	while the list of stoppedJobs remains non-empty. In such a case,
2193  *	we want to restart as many jobs as we can.
2194  *
2195  * Results:
2196  *	TRUE if it is. FALSE if it ain't.
2197  *
2198  * Side Effects:
2199  *	None.
2200  *
2201  * -----------------------------------------------------------------------
2202  */
2203 Boolean
2204 Job_Empty ()
2205 {
2206     if (nJobs == 0) {
2207 	if (!Lst_IsEmpty(stoppedJobs) && !aborting) {
2208 	    /*
2209 	     * The job table is obviously not full if it has no jobs in
2210 	     * it...Try and restart the stopped jobs.
2211 	     */
2212 	    jobFull = FALSE;
2213 	    while (!jobFull && !Lst_IsEmpty(stoppedJobs)) {
2214 		JobRestart((Job *)Lst_DeQueue(stoppedJobs));
2215 	    }
2216 	    return(FALSE);
2217 	} else {
2218 	    return(TRUE);
2219 	}
2220     } else {
2221 	return(FALSE);
2222     }
2223 }
2224 
2225 /*-
2226  *-----------------------------------------------------------------------
2227  * JobMatchShell --
2228  *	Find a matching shell in 'shells' given its final component.
2229  *
2230  * Results:
2231  *	A pointer to the Shell structure.
2232  *
2233  * Side Effects:
2234  *	None.
2235  *
2236  *-----------------------------------------------------------------------
2237  */
2238 static Shell *
2239 JobMatchShell (name)
2240     char	  *name;      /* Final component of shell path */
2241 {
2242     register Shell *sh;	      /* Pointer into shells table */
2243     Shell	   *match;    /* Longest-matching shell */
2244     register char *cp1,
2245 		  *cp2;
2246     char	  *eoname;
2247 
2248     eoname = name + strlen (name);
2249 
2250     match = (Shell *) NULL;
2251 
2252     for (sh = shells; sh->name != NULL; sh++) {
2253 	for (cp1 = eoname - strlen (sh->name), cp2 = sh->name;
2254 	     *cp1 != '\0' && *cp1 == *cp2;
2255 	     cp1++, cp2++) {
2256 		 continue;
2257 	}
2258 	if (*cp1 != *cp2) {
2259 	    continue;
2260 	} else if (match == (Shell *) NULL ||
2261 		   strlen (match->name) < strlen (sh->name)) {
2262 		       match = sh;
2263 	}
2264     }
2265     return (match == (Shell *) NULL ? sh : match);
2266 }
2267 
2268 /*-
2269  *-----------------------------------------------------------------------
2270  * Job_ParseShell --
2271  *	Parse a shell specification and set up commandShell, shellPath
2272  *	and shellName appropriately.
2273  *
2274  * Results:
2275  *	FAILURE if the specification was incorrect.
2276  *
2277  * Side Effects:
2278  *	commandShell points to a Shell structure (either predefined or
2279  *	created from the shell spec), shellPath is the full path of the
2280  *	shell described by commandShell, while shellName is just the
2281  *	final component of shellPath.
2282  *
2283  * Notes:
2284  *	A shell specification consists of a .SHELL target, with dependency
2285  *	operator, followed by a series of blank-separated words. Double
2286  *	quotes can be used to use blanks in words. A backslash escapes
2287  *	anything (most notably a double-quote and a space) and
2288  *	provides the functionality it does in C. Each word consists of
2289  *	keyword and value separated by an equal sign. There should be no
2290  *	unnecessary spaces in the word. The keywords are as follows:
2291  *	    name  	    Name of shell.
2292  *	    path  	    Location of shell. Overrides "name" if given
2293  *	    quiet 	    Command to turn off echoing.
2294  *	    echo  	    Command to turn echoing on
2295  *	    filter	    Result of turning off echoing that shouldn't be
2296  *	    	  	    printed.
2297  *	    echoFlag	    Flag to turn echoing on at the start
2298  *	    errFlag	    Flag to turn error checking on at the start
2299  *	    hasErrCtl	    True if shell has error checking control
2300  *	    check 	    Command to turn on error checking if hasErrCtl
2301  *	    	  	    is TRUE or template of command to echo a command
2302  *	    	  	    for which error checking is off if hasErrCtl is
2303  *	    	  	    FALSE.
2304  *	    ignore	    Command to turn off error checking if hasErrCtl
2305  *	    	  	    is TRUE or template of command to execute a
2306  *	    	  	    command so as to ignore any errors it returns if
2307  *	    	  	    hasErrCtl is FALSE.
2308  *
2309  *-----------------------------------------------------------------------
2310  */
2311 ReturnStatus
2312 Job_ParseShell (line)
2313     char	  *line;  /* The shell spec */
2314 {
2315     char    	  **words;
2316     int	    	  wordCount;
2317     register char **argv;
2318     register int  argc;
2319     char    	  *path;
2320     Shell   	  newShell;
2321     Boolean 	  fullSpec = FALSE;
2322 
2323     while (isspace (*line)) {
2324 	line++;
2325     }
2326     words = brk_string (line, &wordCount);
2327 
2328     memset ((Address)&newShell, 0, sizeof(newShell));
2329 
2330     /*
2331      * Parse the specification by keyword
2332      */
2333     for (path = (char *)NULL, argc = wordCount - 1, argv = words + 1;
2334 	 argc != 0;
2335 	 argc--, argv++) {
2336 	     if (strncmp (*argv, "path=", 5) == 0) {
2337 		 path = &argv[0][5];
2338 	     } else if (strncmp (*argv, "name=", 5) == 0) {
2339 		 newShell.name = &argv[0][5];
2340 	     } else {
2341 		 if (strncmp (*argv, "quiet=", 6) == 0) {
2342 		     newShell.echoOff = &argv[0][6];
2343 		 } else if (strncmp (*argv, "echo=", 5) == 0) {
2344 		     newShell.echoOn = &argv[0][5];
2345 		 } else if (strncmp (*argv, "filter=", 7) == 0) {
2346 		     newShell.noPrint = &argv[0][7];
2347 		     newShell.noPLen = strlen(newShell.noPrint);
2348 		 } else if (strncmp (*argv, "echoFlag=", 9) == 0) {
2349 		     newShell.echo = &argv[0][9];
2350 		 } else if (strncmp (*argv, "errFlag=", 8) == 0) {
2351 		     newShell.exit = &argv[0][8];
2352 		 } else if (strncmp (*argv, "hasErrCtl=", 10) == 0) {
2353 		     char c = argv[0][10];
2354 		     newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
2355 					    (c != 'T') && (c != 't'));
2356 		 } else if (strncmp (*argv, "check=", 6) == 0) {
2357 		     newShell.errCheck = &argv[0][6];
2358 		 } else if (strncmp (*argv, "ignore=", 7) == 0) {
2359 		     newShell.ignErr = &argv[0][7];
2360 		 } else {
2361 		     Parse_Error (PARSE_FATAL, "Unknown keyword \"%s\"",
2362 				  *argv);
2363 		     return (FAILURE);
2364 		 }
2365 		 fullSpec = TRUE;
2366 	     }
2367     }
2368 
2369     if (path == (char *)NULL) {
2370 	/*
2371 	 * If no path was given, the user wants one of the pre-defined shells,
2372 	 * yes? So we find the one s/he wants with the help of JobMatchShell
2373 	 * and set things up the right way. shellPath will be set up by
2374 	 * Job_Init.
2375 	 */
2376 	if (newShell.name == (char *)NULL) {
2377 	    Parse_Error (PARSE_FATAL, "Neither path nor name specified");
2378 	    return (FAILURE);
2379 	} else {
2380 	    commandShell = JobMatchShell (newShell.name);
2381 	    shellName = newShell.name;
2382 	}
2383     } else {
2384 	/*
2385 	 * The user provided a path. If s/he gave nothing else (fullSpec is
2386 	 * FALSE), try and find a matching shell in the ones we know of.
2387 	 * Else we just take the specification at its word and copy it
2388 	 * to a new location. In either case, we need to record the
2389 	 * path the user gave for the shell.
2390 	 */
2391 	shellPath = path;
2392 	path = strrchr (path, '/');
2393 	if (path == (char *)NULL) {
2394 	    path = shellPath;
2395 	} else {
2396 	    path += 1;
2397 	}
2398 	if (newShell.name != (char *)NULL) {
2399 	    shellName = newShell.name;
2400 	} else {
2401 	    shellName = path;
2402 	}
2403 	if (!fullSpec) {
2404 	    commandShell = JobMatchShell (shellName);
2405 	} else {
2406 	    commandShell = (Shell *) emalloc(sizeof(Shell));
2407 	    *commandShell = newShell;
2408 	}
2409     }
2410 
2411     if (commandShell->echoOn && commandShell->echoOff) {
2412 	commandShell->hasEchoCtl = TRUE;
2413     }
2414 
2415     if (!commandShell->hasErrCtl) {
2416 	if (commandShell->errCheck == (char *)NULL) {
2417 	    commandShell->errCheck = "";
2418 	}
2419 	if (commandShell->ignErr == (char *)NULL) {
2420 	    commandShell->ignErr = "%s\n";
2421 	}
2422     }
2423 
2424     /*
2425      * Do not free up the words themselves, since they might be in use by the
2426      * shell specification...
2427      */
2428     free (words);
2429     return SUCCESS;
2430 }
2431 
2432 /*-
2433  *-----------------------------------------------------------------------
2434  * JobInterrupt --
2435  *	Handle the receipt of an interrupt.
2436  *
2437  * Results:
2438  *	None
2439  *
2440  * Side Effects:
2441  *	All children are killed. Another job will be started if the
2442  *	.INTERRUPT target was given.
2443  *-----------------------------------------------------------------------
2444  */
2445 static void
2446 JobInterrupt (runINTERRUPT)
2447     int	    runINTERRUPT;   	/* Non-zero if commands for the .INTERRUPT
2448 				 * target should be executed */
2449 {
2450     LstNode 	  ln;		/* element in job table */
2451     Job           *job;	    	/* job descriptor in that element */
2452     GNode         *interrupt;	/* the node describing the .INTERRUPT target */
2453     struct stat sb;
2454 
2455     aborting = ABORT_INTERRUPT;
2456 
2457     (void)Lst_Open (jobs);
2458     while ((ln = Lst_Next (jobs)) != NILLNODE) {
2459 	job = (Job *) Lst_Datum (ln);
2460 
2461 	if (!Targ_Precious (job->node)) {
2462 	    char  	*file = (job->node->path == (char *)NULL ?
2463 				 job->node->name :
2464 				 job->node->path);
2465 	    if (!stat(file, &sb) && S_ISREG(sb.st_mode) &&
2466 		unlink (file) == 0) {
2467 		Error ("*** %s removed", file);
2468 	    }
2469 	}
2470 #ifdef RMT_WANTS_SIGNALS
2471 	if (job->flags & JOB_REMOTE) {
2472 	    /*
2473 	     * If job is remote, let the Rmt module do the killing.
2474 	     */
2475 	    if (!Rmt_Signal(job, SIGINT)) {
2476 		/*
2477 		 * If couldn't kill the thing, finish it out now with an
2478 		 * error code, since no exit report will come in likely.
2479 		 */
2480 		union wait status;
2481 
2482 		status.w_status = 0;
2483 		status.w_retcode = 1;
2484 		JobFinish(job, status);
2485 	    }
2486 	} else if (job->pid) {
2487 	    KILL(job->pid, SIGINT);
2488 	}
2489 #else
2490 	if (job->pid) {
2491 	    KILL(job->pid, SIGINT);
2492 	}
2493 #endif /* RMT_WANTS_SIGNALS */
2494     }
2495     Lst_Close (jobs);
2496 
2497     if (runINTERRUPT && !touchFlag) {
2498 	interrupt = Targ_FindNode (".INTERRUPT", TARG_NOCREATE);
2499 	if (interrupt != NILGNODE) {
2500 	    ignoreErrors = FALSE;
2501 
2502 	    JobStart (interrupt, JOB_IGNDOTS, (Job *)0);
2503 	    while (nJobs) {
2504 		Job_CatchOutput();
2505 #ifndef RMT_WILL_WATCH
2506 		Job_CatchChildren (!usePipes);
2507 #endif /* RMT_WILL_WATCH */
2508 	    }
2509 	}
2510     }
2511     (void) unlink (tfile);
2512     exit (0);
2513 }
2514 
2515 /*
2516  *-----------------------------------------------------------------------
2517  * Job_End --
2518  *	Do final processing such as the running of the commands
2519  *	attached to the .END target.
2520  *
2521  * Results:
2522  *	Number of errors reported.
2523  *
2524  * Side Effects:
2525  *	The process' temporary file (tfile) is removed if it still
2526  *	existed.
2527  *-----------------------------------------------------------------------
2528  */
2529 int
2530 Job_End ()
2531 {
2532     if (postCommands != NILGNODE && !Lst_IsEmpty (postCommands->commands)) {
2533 	if (errors) {
2534 	    Error ("Errors reported so .END ignored");
2535 	} else {
2536 	    JobStart (postCommands, JOB_SPECIAL | JOB_IGNDOTS,
2537 		       (Job *)0);
2538 
2539 	    while (nJobs) {
2540 		Job_CatchOutput();
2541 #ifndef RMT_WILL_WATCH
2542 		Job_CatchChildren (!usePipes);
2543 #endif /* RMT_WILL_WATCH */
2544 	    }
2545 	}
2546     }
2547     (void) unlink (tfile);
2548     return(errors);
2549 }
2550 
2551 /*-
2552  *-----------------------------------------------------------------------
2553  * Job_Wait --
2554  *	Waits for all running jobs to finish and returns. Sets 'aborting'
2555  *	to ABORT_WAIT to prevent other jobs from starting.
2556  *
2557  * Results:
2558  *	None.
2559  *
2560  * Side Effects:
2561  *	Currently running jobs finish.
2562  *
2563  *-----------------------------------------------------------------------
2564  */
2565 void
2566 Job_Wait()
2567 {
2568     aborting = ABORT_WAIT;
2569     while (nJobs != 0) {
2570 	Job_CatchOutput();
2571 #ifndef RMT_WILL_WATCH
2572 	Job_CatchChildren(!usePipes);
2573 #endif /* RMT_WILL_WATCH */
2574     }
2575     aborting = 0;
2576 }
2577 
2578 /*-
2579  *-----------------------------------------------------------------------
2580  * Job_AbortAll --
2581  *	Abort all currently running jobs without handling output or anything.
2582  *	This function is to be called only in the event of a major
2583  *	error. Most definitely NOT to be called from JobInterrupt.
2584  *
2585  * Results:
2586  *	None
2587  *
2588  * Side Effects:
2589  *	All children are killed, not just the firstborn
2590  *-----------------------------------------------------------------------
2591  */
2592 void
2593 Job_AbortAll ()
2594 {
2595     LstNode           	ln;		/* element in job table */
2596     Job            	*job;	/* the job descriptor in that element */
2597     int     	  	foo;
2598 
2599     aborting = ABORT_ERROR;
2600 
2601     if (nJobs) {
2602 
2603 	(void)Lst_Open (jobs);
2604 	while ((ln = Lst_Next (jobs)) != NILLNODE) {
2605 	    job = (Job *) Lst_Datum (ln);
2606 
2607 	    /*
2608 	     * kill the child process with increasingly drastic signals to make
2609 	     * darn sure it's dead.
2610 	     */
2611 #ifdef RMT_WANTS_SIGNALS
2612 	    if (job->flags & JOB_REMOTE) {
2613 		Rmt_Signal(job, SIGINT);
2614 		Rmt_Signal(job, SIGKILL);
2615 	    } else {
2616 		KILL(job->pid, SIGINT);
2617 		KILL(job->pid, SIGKILL);
2618 	    }
2619 #else
2620 	    KILL(job->pid, SIGINT);
2621 	    KILL(job->pid, SIGKILL);
2622 #endif /* RMT_WANTS_SIGNALS */
2623 	}
2624     }
2625 
2626     /*
2627      * Catch as many children as want to report in at first, then give up
2628      */
2629     while (wait3(&foo, WNOHANG, (struct rusage *)0) > 0)
2630 	continue;
2631     (void) unlink (tfile);
2632 }
2633