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