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