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