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