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