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