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