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