xref: /freebsd/contrib/bmake/job.c (revision 045c8f526484cb3b97f5fd693987f4376fa43c5f)
1 /*	$NetBSD: job.c,v 1.451 2022/02/04 23:22:19 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.451 2022/02/04 23:22:19 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 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 	} else {
880 		if (inout_cmdFlags->echo)
881 			ShellWriter_EchoCmd(wr, escCmd);
882 	}
883 	*inout_cmdTemplate = shell->runIgnTmpl;
884 
885 	/*
886 	 * The template runIgnTmpl already takes care of ignoring errors,
887 	 * so pretend error checking is still on.
888 	 * XXX: What effects does this have, and why is it necessary?
889 	 */
890 	inout_cmdFlags->ignerr = false;
891 }
892 
893 static void
894 JobWriteSpecials(Job *job, ShellWriter *wr, const char *escCmd, bool run,
895 		 CommandFlags *inout_cmdFlags, const char **inout_cmdTemplate)
896 {
897 	if (!run) {
898 		/*
899 		 * If there is no command to run, there is no need to switch
900 		 * error checking off and on again for nothing.
901 		 */
902 		inout_cmdFlags->ignerr = false;
903 	} else if (shell->hasErrCtl)
904 		ShellWriter_ErrOff(wr, job->echo && inout_cmdFlags->echo);
905 	else if (shell->runIgnTmpl != NULL && shell->runIgnTmpl[0] != '\0') {
906 		JobWriteSpecialsEchoCtl(job, wr, inout_cmdFlags, escCmd,
907 		    inout_cmdTemplate);
908 	} else
909 		inout_cmdFlags->ignerr = false;
910 }
911 
912 /*
913  * Write a shell command to the job's commands file, to be run later.
914  *
915  * If the command starts with '@' and neither the -s nor the -n flag was
916  * given to make, stick a shell-specific echoOff command in the script.
917  *
918  * If the command starts with '-' and the shell has no error control (none
919  * of the predefined shells has that), ignore errors for the entire job.
920  *
921  * XXX: Why ignore errors for the entire job?  This is even documented in the
922  * manual page, but without any rationale since there is no known rationale.
923  *
924  * XXX: The manual page says the '-' "affects the entire job", but that's not
925  * accurate.  The '-' does not affect the commands before the '-'.
926  *
927  * If the command is just "...", skip all further commands of this job.  These
928  * commands are attached to the .END node instead and will be run by
929  * Job_Finish after all other targets have been made.
930  */
931 static void
932 JobWriteCommand(Job *job, ShellWriter *wr, StringListNode *ln, const char *ucmd)
933 {
934 	bool run;
935 
936 	CommandFlags cmdFlags;
937 	/* Template for writing a command to the shell file */
938 	const char *cmdTemplate;
939 	char *xcmd;		/* The expanded command */
940 	char *xcmdStart;
941 	char *escCmd;		/* xcmd escaped to be used in double quotes */
942 
943 	run = GNode_ShouldExecute(job->node);
944 
945 	(void)Var_Subst(ucmd, job->node, VARE_WANTRES, &xcmd);
946 	/* TODO: handle errors */
947 	xcmdStart = xcmd;
948 
949 	cmdTemplate = "%s\n";
950 
951 	ParseCommandFlags(&xcmd, &cmdFlags);
952 
953 	/* The '+' command flag overrides the -n or -N options. */
954 	if (cmdFlags.always && !run) {
955 		/*
956 		 * We're not actually executing anything...
957 		 * but this one needs to be - use compat mode just for it.
958 		 */
959 		(void)Compat_RunCommand(ucmd, job->node, ln);
960 		free(xcmdStart);
961 		return;
962 	}
963 
964 	/*
965 	 * If the shell doesn't have error control, the alternate echoing
966 	 * will be done (to avoid showing additional error checking code)
967 	 * and this needs some characters escaped.
968 	 */
969 	escCmd = shell->hasErrCtl ? NULL : EscapeShellDblQuot(xcmd);
970 
971 	if (!cmdFlags.echo) {
972 		if (job->echo && run && shell->hasEchoCtl) {
973 			ShellWriter_EchoOff(wr);
974 		} else {
975 			if (shell->hasErrCtl)
976 				cmdFlags.echo = true;
977 		}
978 	}
979 
980 	if (cmdFlags.ignerr) {
981 		JobWriteSpecials(job, wr, escCmd, run, &cmdFlags, &cmdTemplate);
982 	} else {
983 
984 		/*
985 		 * If errors are being checked and the shell doesn't have
986 		 * error control but does supply an runChkTmpl template, then
987 		 * set up commands to run through it.
988 		 */
989 
990 		if (!shell->hasErrCtl && shell->runChkTmpl != NULL &&
991 		    shell->runChkTmpl[0] != '\0') {
992 			if (job->echo && cmdFlags.echo) {
993 				ShellWriter_EchoOff(wr);
994 				ShellWriter_EchoCmd(wr, escCmd);
995 				cmdFlags.echo = false;
996 			}
997 			/*
998 			 * If it's a comment line or blank, avoid the possible
999 			 * syntax error generated by "{\n} || exit $?".
1000 			 */
1001 			cmdTemplate = escCmd[0] == shell->commentChar ||
1002 				      escCmd[0] == '\0'
1003 			    ? shell->runIgnTmpl
1004 			    : shell->runChkTmpl;
1005 			cmdFlags.ignerr = false;
1006 		}
1007 	}
1008 
1009 	if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0)
1010 		ShellWriter_TraceOn(wr);
1011 
1012 	ShellWriter_WriteFmt(wr, cmdTemplate, xcmd);
1013 	free(xcmdStart);
1014 	free(escCmd);
1015 
1016 	if (cmdFlags.ignerr)
1017 		ShellWriter_ErrOn(wr, cmdFlags.echo && job->echo);
1018 
1019 	if (!cmdFlags.echo)
1020 		ShellWriter_EchoOn(wr);
1021 }
1022 
1023 /*
1024  * Write all commands to the shell file that is later executed.
1025  *
1026  * The special command "..." stops writing and saves the remaining commands
1027  * to be executed later, when the target '.END' is made.
1028  *
1029  * Return whether at least one command was written to the shell file.
1030  */
1031 static bool
1032 JobWriteCommands(Job *job)
1033 {
1034 	StringListNode *ln;
1035 	bool seen = false;
1036 	ShellWriter wr;
1037 
1038 	wr.f = job->cmdFILE;
1039 	wr.xtraced = false;
1040 
1041 	for (ln = job->node->commands.first; ln != NULL; ln = ln->next) {
1042 		const char *cmd = ln->datum;
1043 
1044 		if (strcmp(cmd, "...") == 0) {
1045 			job->node->type |= OP_SAVE_CMDS;
1046 			job->tailCmds = ln->next;
1047 			break;
1048 		}
1049 
1050 		JobWriteCommand(job, &wr, ln, ln->datum);
1051 		seen = true;
1052 	}
1053 
1054 	return seen;
1055 }
1056 
1057 /*
1058  * Save the delayed commands (those after '...'), to be executed later in
1059  * the '.END' node, when everything else is done.
1060  */
1061 static void
1062 JobSaveCommands(Job *job)
1063 {
1064 	StringListNode *ln;
1065 
1066 	for (ln = job->tailCmds; ln != NULL; ln = ln->next) {
1067 		const char *cmd = ln->datum;
1068 		char *expanded_cmd;
1069 		/*
1070 		 * XXX: This Var_Subst is only intended to expand the dynamic
1071 		 * variables such as .TARGET, .IMPSRC.  It is not intended to
1072 		 * expand the other variables as well; see deptgt-end.mk.
1073 		 */
1074 		(void)Var_Subst(cmd, job->node, VARE_WANTRES, &expanded_cmd);
1075 		/* TODO: handle errors */
1076 		Lst_Append(&Targ_GetEndNode()->commands, expanded_cmd);
1077 	}
1078 }
1079 
1080 
1081 /* Called to close both input and output pipes when a job is finished. */
1082 static void
1083 JobClosePipes(Job *job)
1084 {
1085 	clearfd(job);
1086 	(void)close(job->outPipe);
1087 	job->outPipe = -1;
1088 
1089 	CollectOutput(job, true);
1090 	(void)close(job->inPipe);
1091 	job->inPipe = -1;
1092 }
1093 
1094 static void
1095 DebugFailedJob(const Job *job)
1096 {
1097 	const StringListNode *ln;
1098 
1099 	if (!DEBUG(ERROR))
1100 		return;
1101 
1102 	debug_printf("\n");
1103 	debug_printf("*** Failed target: %s\n", job->node->name);
1104 	debug_printf("*** Failed commands:\n");
1105 	for (ln = job->node->commands.first; ln != NULL; ln = ln->next) {
1106 		const char *cmd = ln->datum;
1107 		debug_printf("\t%s\n", cmd);
1108 
1109 		if (strchr(cmd, '$') != NULL) {
1110 			char *xcmd;
1111 			(void)Var_Subst(cmd, job->node, VARE_WANTRES, &xcmd);
1112 			debug_printf("\t=> %s\n", xcmd);
1113 			free(xcmd);
1114 		}
1115 	}
1116 }
1117 
1118 static void
1119 JobFinishDoneExitedError(Job *job, WAIT_T *inout_status)
1120 {
1121 	SwitchOutputTo(job->node);
1122 #ifdef USE_META
1123 	if (useMeta) {
1124 		meta_job_error(job, job->node,
1125 		    job->ignerr, WEXITSTATUS(*inout_status));
1126 	}
1127 #endif
1128 	if (!shouldDieQuietly(job->node, -1)) {
1129 		DebugFailedJob(job);
1130 		(void)printf("*** [%s] Error code %d%s\n",
1131 		    job->node->name, WEXITSTATUS(*inout_status),
1132 		    job->ignerr ? " (ignored)" : "");
1133 	}
1134 
1135 	if (job->ignerr)
1136 		WAIT_STATUS(*inout_status) = 0;
1137 	else {
1138 		if (deleteOnError)
1139 			JobDeleteTarget(job->node);
1140 		PrintOnError(job->node, "\n");
1141 	}
1142 }
1143 
1144 static void
1145 JobFinishDoneExited(Job *job, WAIT_T *inout_status)
1146 {
1147 	DEBUG2(JOB, "Process %d [%s] exited.\n", job->pid, job->node->name);
1148 
1149 	if (WEXITSTATUS(*inout_status) != 0)
1150 		JobFinishDoneExitedError(job, inout_status);
1151 	else if (DEBUG(JOB)) {
1152 		SwitchOutputTo(job->node);
1153 		(void)printf("*** [%s] Completed successfully\n",
1154 		    job->node->name);
1155 	}
1156 }
1157 
1158 static void
1159 JobFinishDoneSignaled(Job *job, WAIT_T status)
1160 {
1161 	SwitchOutputTo(job->node);
1162 	DebugFailedJob(job);
1163 	(void)printf("*** [%s] Signal %d\n", job->node->name, WTERMSIG(status));
1164 	if (deleteOnError)
1165 		JobDeleteTarget(job->node);
1166 }
1167 
1168 static void
1169 JobFinishDone(Job *job, WAIT_T *inout_status)
1170 {
1171 	if (WIFEXITED(*inout_status))
1172 		JobFinishDoneExited(job, inout_status);
1173 	else
1174 		JobFinishDoneSignaled(job, *inout_status);
1175 
1176 	(void)fflush(stdout);
1177 }
1178 
1179 /*
1180  * Do final processing for the given job including updating parent nodes and
1181  * starting new jobs as available/necessary.
1182  *
1183  * Deferred commands for the job are placed on the .END node.
1184  *
1185  * If there was a serious error (job_errors != 0; not an ignored one), no more
1186  * jobs will be started.
1187  *
1188  * Input:
1189  *	job		job to finish
1190  *	status		sub-why job went away
1191  */
1192 static void
1193 JobFinish (Job *job, WAIT_T status)
1194 {
1195 	bool done, return_job_token;
1196 
1197 	DEBUG3(JOB, "JobFinish: %d [%s], status %d\n",
1198 	    job->pid, job->node->name, status);
1199 
1200 	if ((WIFEXITED(status) &&
1201 	     ((WEXITSTATUS(status) != 0 && !job->ignerr))) ||
1202 	    WIFSIGNALED(status)) {
1203 		/* Finished because of an error. */
1204 
1205 		JobClosePipes(job);
1206 		if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1207 			if (fclose(job->cmdFILE) != 0)
1208 				Punt("Cannot write shell script for '%s': %s",
1209 				    job->node->name, strerror(errno));
1210 			job->cmdFILE = NULL;
1211 		}
1212 		done = true;
1213 
1214 	} else if (WIFEXITED(status)) {
1215 		/*
1216 		 * Deal with ignored errors in -B mode. We need to print a
1217 		 * message telling of the ignored error as well as to run
1218 		 * the next command.
1219 		 */
1220 		done = WEXITSTATUS(status) != 0;
1221 
1222 		JobClosePipes(job);
1223 
1224 	} else {
1225 		/* No need to close things down or anything. */
1226 		done = false;
1227 	}
1228 
1229 	if (done)
1230 		JobFinishDone(job, &status);
1231 
1232 #ifdef USE_META
1233 	if (useMeta) {
1234 		int meta_status = meta_job_finish(job);
1235 		if (meta_status != 0 && status == 0)
1236 			status = meta_status;
1237 	}
1238 #endif
1239 
1240 	return_job_token = false;
1241 
1242 	Trace_Log(JOBEND, job);
1243 	if (!job->special) {
1244 		if (WAIT_STATUS(status) != 0 ||
1245 		    (aborting == ABORT_ERROR) || aborting == ABORT_INTERRUPT)
1246 			return_job_token = true;
1247 	}
1248 
1249 	if (aborting != ABORT_ERROR && aborting != ABORT_INTERRUPT &&
1250 	    (WAIT_STATUS(status) == 0)) {
1251 		/*
1252 		 * As long as we aren't aborting and the job didn't return a
1253 		 * non-zero status that we shouldn't ignore, we call
1254 		 * Make_Update to update the parents.
1255 		 */
1256 		JobSaveCommands(job);
1257 		job->node->made = MADE;
1258 		if (!job->special)
1259 			return_job_token = true;
1260 		Make_Update(job->node);
1261 		job->status = JOB_ST_FREE;
1262 	} else if (status != 0) {
1263 		job_errors++;
1264 		job->status = JOB_ST_FREE;
1265 	}
1266 
1267 	if (job_errors > 0 && !opts.keepgoing && aborting != ABORT_INTERRUPT) {
1268 		/* Prevent more jobs from getting started. */
1269 		aborting = ABORT_ERROR;
1270 	}
1271 
1272 	if (return_job_token)
1273 		Job_TokenReturn();
1274 
1275 	if (aborting == ABORT_ERROR && jobTokensRunning == 0)
1276 		Finish(job_errors);
1277 }
1278 
1279 static void
1280 TouchRegular(GNode *gn)
1281 {
1282 	const char *file = GNode_Path(gn);
1283 	struct utimbuf times;
1284 	int fd;
1285 	char c;
1286 
1287 	times.actime = now;
1288 	times.modtime = now;
1289 	if (utime(file, &times) >= 0)
1290 		return;
1291 
1292 	fd = open(file, O_RDWR | O_CREAT, 0666);
1293 	if (fd < 0) {
1294 		(void)fprintf(stderr, "*** couldn't touch %s: %s\n",
1295 		    file, strerror(errno));
1296 		(void)fflush(stderr);
1297 		return;		/* XXX: What about propagating the error? */
1298 	}
1299 
1300 	/*
1301 	 * Last resort: update the file's time stamps in the traditional way.
1302 	 * XXX: This doesn't work for empty files, which are sometimes used
1303 	 * as marker files.
1304 	 */
1305 	if (read(fd, &c, 1) == 1) {
1306 		(void)lseek(fd, 0, SEEK_SET);
1307 		while (write(fd, &c, 1) == -1 && errno == EAGAIN)
1308 			continue;
1309 	}
1310 	(void)close(fd);	/* XXX: What about propagating the error? */
1311 }
1312 
1313 /*
1314  * Touch the given target. Called by JobStart when the -t flag was given.
1315  *
1316  * The modification date of the file is changed.
1317  * If the file did not exist, it is created.
1318  */
1319 void
1320 Job_Touch(GNode *gn, bool echo)
1321 {
1322 	if (gn->type &
1323 	    (OP_JOIN | OP_USE | OP_USEBEFORE | OP_EXEC | OP_OPTIONAL |
1324 	     OP_SPECIAL | OP_PHONY)) {
1325 		/*
1326 		 * These are "virtual" targets and should not really be
1327 		 * created.
1328 		 */
1329 		return;
1330 	}
1331 
1332 	if (echo || !GNode_ShouldExecute(gn)) {
1333 		(void)fprintf(stdout, "touch %s\n", gn->name);
1334 		(void)fflush(stdout);
1335 	}
1336 
1337 	if (!GNode_ShouldExecute(gn))
1338 		return;
1339 
1340 	if (gn->type & OP_ARCHV)
1341 		Arch_Touch(gn);
1342 	else if (gn->type & OP_LIB)
1343 		Arch_TouchLib(gn);
1344 	else
1345 		TouchRegular(gn);
1346 }
1347 
1348 /*
1349  * Make sure the given node has all the commands it needs.
1350  *
1351  * The node will have commands from the .DEFAULT rule added to it if it
1352  * needs them.
1353  *
1354  * Input:
1355  *	gn		The target whose commands need verifying
1356  *	abortProc	Function to abort with message
1357  *
1358  * Results:
1359  *	true if the commands list is/was ok.
1360  */
1361 bool
1362 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1363 {
1364 	if (GNode_IsTarget(gn))
1365 		return true;
1366 	if (!Lst_IsEmpty(&gn->commands))
1367 		return true;
1368 	if ((gn->type & OP_LIB) && !Lst_IsEmpty(&gn->children))
1369 		return true;
1370 
1371 	/*
1372 	 * No commands. Look for .DEFAULT rule from which we might infer
1373 	 * commands.
1374 	 */
1375 	if (defaultNode != NULL && !Lst_IsEmpty(&defaultNode->commands) &&
1376 	    !(gn->type & OP_SPECIAL)) {
1377 		/*
1378 		 * The traditional Make only looks for a .DEFAULT if the node
1379 		 * was never the target of an operator, so that's what we do
1380 		 * too.
1381 		 *
1382 		 * The .DEFAULT node acts like a transformation rule, in that
1383 		 * gn also inherits any attributes or sources attached to
1384 		 * .DEFAULT itself.
1385 		 */
1386 		Make_HandleUse(defaultNode, gn);
1387 		Var_Set(gn, IMPSRC, GNode_VarTarget(gn));
1388 		return true;
1389 	}
1390 
1391 	Dir_UpdateMTime(gn, false);
1392 	if (gn->mtime != 0 || (gn->type & OP_SPECIAL))
1393 		return true;
1394 
1395 	/*
1396 	 * The node wasn't the target of an operator.  We have no .DEFAULT
1397 	 * rule to go on and the target doesn't already exist. There's
1398 	 * nothing more we can do for this branch. If the -k flag wasn't
1399 	 * given, we stop in our tracks, otherwise we just don't update
1400 	 * this node's parents so they never get examined.
1401 	 */
1402 
1403 	if (gn->flags.fromDepend) {
1404 		if (!Job_RunTarget(".STALE", gn->fname))
1405 			fprintf(stdout,
1406 			    "%s: %s, %u: ignoring stale %s for %s\n",
1407 			    progname, gn->fname, gn->lineno, makeDependfile,
1408 			    gn->name);
1409 		return true;
1410 	}
1411 
1412 	if (gn->type & OP_OPTIONAL) {
1413 		(void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
1414 		    progname, gn->name, "ignored");
1415 		(void)fflush(stdout);
1416 		return true;
1417 	}
1418 
1419 	if (opts.keepgoing) {
1420 		(void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
1421 		    progname, gn->name, "continuing");
1422 		(void)fflush(stdout);
1423 		return false;
1424 	}
1425 
1426 	abortProc("%s: don't know how to make %s. Stop", progname, gn->name);
1427 	return false;
1428 }
1429 
1430 /*
1431  * Execute the shell for the given job.
1432  *
1433  * See Job_CatchOutput for handling the output of the shell.
1434  */
1435 static void
1436 JobExec(Job *job, char **argv)
1437 {
1438 	int cpid;		/* ID of new child */
1439 	sigset_t mask;
1440 
1441 	if (DEBUG(JOB)) {
1442 		int i;
1443 
1444 		debug_printf("Running %s\n", job->node->name);
1445 		debug_printf("\tCommand: ");
1446 		for (i = 0; argv[i] != NULL; i++) {
1447 			debug_printf("%s ", argv[i]);
1448 		}
1449 		debug_printf("\n");
1450 	}
1451 
1452 	/*
1453 	 * Some jobs produce no output and it's disconcerting to have
1454 	 * no feedback of their running (since they produce no output, the
1455 	 * banner with their name in it never appears). This is an attempt to
1456 	 * provide that feedback, even if nothing follows it.
1457 	 */
1458 	if (job->echo)
1459 		SwitchOutputTo(job->node);
1460 
1461 	/* No interruptions until this job is on the `jobs' list */
1462 	JobSigLock(&mask);
1463 
1464 	/* Pre-emptively mark job running, pid still zero though */
1465 	job->status = JOB_ST_RUNNING;
1466 
1467 	Var_ReexportVars();
1468 
1469 	cpid = vfork();
1470 	if (cpid == -1)
1471 		Punt("Cannot vfork: %s", strerror(errno));
1472 
1473 	if (cpid == 0) {
1474 		/* Child */
1475 		sigset_t tmask;
1476 
1477 #ifdef USE_META
1478 		if (useMeta)
1479 			meta_job_child(job);
1480 #endif
1481 		/*
1482 		 * Reset all signal handlers; this is necessary because we
1483 		 * also need to unblock signals before we exec(2).
1484 		 */
1485 		JobSigReset();
1486 
1487 		/* Now unblock signals */
1488 		sigemptyset(&tmask);
1489 		JobSigUnlock(&tmask);
1490 
1491 		/*
1492 		 * Must duplicate the input stream down to the child's input
1493 		 * and reset it to the beginning (again). Since the stream
1494 		 * was marked close-on-exec, we must clear that bit in the
1495 		 * new input.
1496 		 */
1497 		if (dup2(fileno(job->cmdFILE), 0) == -1)
1498 			execDie("dup2", "job->cmdFILE");
1499 		if (fcntl(0, F_SETFD, 0) == -1)
1500 			execDie("fcntl clear close-on-exec", "stdin");
1501 		if (lseek(0, 0, SEEK_SET) == -1)
1502 			execDie("lseek to 0", "stdin");
1503 
1504 		if (Always_pass_job_queue ||
1505 		    (job->node->type & (OP_MAKE | OP_SUBMAKE))) {
1506 			/*
1507 			 * Pass job token pipe to submakes.
1508 			 */
1509 			if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1)
1510 				execDie("clear close-on-exec",
1511 				    "tokenWaitJob.inPipe");
1512 			if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1)
1513 				execDie("clear close-on-exec",
1514 				    "tokenWaitJob.outPipe");
1515 		}
1516 
1517 		/*
1518 		 * Set up the child's output to be routed through the pipe
1519 		 * we've created for it.
1520 		 */
1521 		if (dup2(job->outPipe, 1) == -1)
1522 			execDie("dup2", "job->outPipe");
1523 
1524 		/*
1525 		 * The output channels are marked close on exec. This bit
1526 		 * was duplicated by the dup2(on some systems), so we have
1527 		 * to clear it before routing the shell's error output to
1528 		 * the same place as its standard output.
1529 		 */
1530 		if (fcntl(1, F_SETFD, 0) == -1)
1531 			execDie("clear close-on-exec", "stdout");
1532 		if (dup2(1, 2) == -1)
1533 			execDie("dup2", "1, 2");
1534 
1535 		/*
1536 		 * We want to switch the child into a different process
1537 		 * family so we can kill it and all its descendants in
1538 		 * one fell swoop, by killing its process family, but not
1539 		 * commit suicide.
1540 		 */
1541 #if defined(HAVE_SETPGID)
1542 		(void)setpgid(0, getpid());
1543 #else
1544 # if defined(HAVE_SETSID)
1545 		/* XXX: dsl - I'm sure this should be setpgrp()... */
1546 		(void)setsid();
1547 # else
1548 		(void)setpgrp(0, getpid());
1549 # endif
1550 #endif
1551 
1552 		(void)execv(shellPath, argv);
1553 		execDie("exec", shellPath);
1554 	}
1555 
1556 	/* Parent, continuing after the child exec */
1557 	job->pid = cpid;
1558 
1559 	Trace_Log(JOBSTART, job);
1560 
1561 #ifdef USE_META
1562 	if (useMeta)
1563 		meta_job_parent(job, cpid);
1564 #endif
1565 
1566 	/*
1567 	 * Set the current position in the buffer to the beginning
1568 	 * and mark another stream to watch in the outputs mask
1569 	 */
1570 	job->curPos = 0;
1571 
1572 	watchfd(job);
1573 
1574 	if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1575 		if (fclose(job->cmdFILE) != 0)
1576 			Punt("Cannot write shell script for '%s': %s",
1577 			    job->node->name, strerror(errno));
1578 		job->cmdFILE = NULL;
1579 	}
1580 
1581 	/* Now that the job is actually running, add it to the table. */
1582 	if (DEBUG(JOB)) {
1583 		debug_printf("JobExec(%s): pid %d added to jobs table\n",
1584 		    job->node->name, job->pid);
1585 		DumpJobs("job started");
1586 	}
1587 	JobSigUnlock(&mask);
1588 }
1589 
1590 /* Create the argv needed to execute the shell for a given job. */
1591 static void
1592 JobMakeArgv(Job *job, char **argv)
1593 {
1594 	int argc;
1595 	static char args[10];	/* For merged arguments */
1596 
1597 	argv[0] = UNCONST(shellName);
1598 	argc = 1;
1599 
1600 	if ((shell->errFlag != NULL && shell->errFlag[0] != '-') ||
1601 	    (shell->echoFlag != NULL && shell->echoFlag[0] != '-')) {
1602 		/*
1603 		 * At least one of the flags doesn't have a minus before it,
1604 		 * so merge them together. Have to do this because the Bourne
1605 		 * shell thinks its second argument is a file to source.
1606 		 * Grrrr. Note the ten-character limitation on the combined
1607 		 * arguments.
1608 		 *
1609 		 * TODO: Research until when the above comments were
1610 		 * practically relevant.
1611 		 */
1612 		(void)snprintf(args, sizeof args, "-%s%s",
1613 		    (job->ignerr ? "" :
1614 			(shell->errFlag != NULL ? shell->errFlag : "")),
1615 		    (!job->echo ? "" :
1616 			(shell->echoFlag != NULL ? shell->echoFlag : "")));
1617 
1618 		if (args[1] != '\0') {
1619 			argv[argc] = args;
1620 			argc++;
1621 		}
1622 	} else {
1623 		if (!job->ignerr && shell->errFlag != NULL) {
1624 			argv[argc] = UNCONST(shell->errFlag);
1625 			argc++;
1626 		}
1627 		if (job->echo && shell->echoFlag != NULL) {
1628 			argv[argc] = UNCONST(shell->echoFlag);
1629 			argc++;
1630 		}
1631 	}
1632 	argv[argc] = NULL;
1633 }
1634 
1635 static void
1636 JobWriteShellCommands(Job *job, GNode *gn, bool *out_run)
1637 {
1638 	/*
1639 	 * tfile is the name of a file into which all shell commands
1640 	 * are put. It is removed before the child shell is executed,
1641 	 * unless DEBUG(SCRIPT) is set.
1642 	 */
1643 	char tfile[MAXPATHLEN];
1644 	int tfd;		/* File descriptor to the temp file */
1645 
1646 	tfd = Job_TempFile(TMPPAT, tfile, sizeof tfile);
1647 
1648 	job->cmdFILE = fdopen(tfd, "w+");
1649 	if (job->cmdFILE == NULL)
1650 		Punt("Could not fdopen %s", tfile);
1651 
1652 	(void)fcntl(fileno(job->cmdFILE), F_SETFD, FD_CLOEXEC);
1653 
1654 #ifdef USE_META
1655 	if (useMeta) {
1656 		meta_job_start(job, gn);
1657 		if (gn->type & OP_SILENT)	/* might have changed */
1658 			job->echo = false;
1659 	}
1660 #endif
1661 
1662 	*out_run = JobWriteCommands(job);
1663 }
1664 
1665 /*
1666  * Start a target-creation process going for the target described by gn.
1667  *
1668  * Results:
1669  *	JOB_ERROR if there was an error in the commands, JOB_FINISHED
1670  *	if there isn't actually anything left to do for the job and
1671  *	JOB_RUNNING if the job has been started.
1672  *
1673  * Details:
1674  *	A new Job node is created and added to the list of running
1675  *	jobs. PMake is forked and a child shell created.
1676  *
1677  * NB: The return value is ignored by everyone.
1678  */
1679 static JobStartResult
1680 JobStart(GNode *gn, bool special)
1681 {
1682 	Job *job;		/* new job descriptor */
1683 	char *argv[10];		/* Argument vector to shell */
1684 	bool cmdsOK;		/* true if the nodes commands were all right */
1685 	bool run;
1686 
1687 	for (job = job_table; job < job_table_end; job++) {
1688 		if (job->status == JOB_ST_FREE)
1689 			break;
1690 	}
1691 	if (job >= job_table_end)
1692 		Punt("JobStart no job slots vacant");
1693 
1694 	memset(job, 0, sizeof *job);
1695 	job->node = gn;
1696 	job->tailCmds = NULL;
1697 	job->status = JOB_ST_SET_UP;
1698 
1699 	job->special = special || gn->type & OP_SPECIAL;
1700 	job->ignerr = opts.ignoreErrors || gn->type & OP_IGNORE;
1701 	job->echo = !(opts.silent || gn->type & OP_SILENT);
1702 
1703 	/*
1704 	 * Check the commands now so any attributes from .DEFAULT have a
1705 	 * chance to migrate to the node.
1706 	 */
1707 	cmdsOK = Job_CheckCommands(gn, Error);
1708 
1709 	job->inPollfd = NULL;
1710 
1711 	if (Lst_IsEmpty(&gn->commands)) {
1712 		job->cmdFILE = stdout;
1713 		run = false;
1714 
1715 		/*
1716 		 * We're serious here, but if the commands were bogus, we're
1717 		 * also dead...
1718 		 */
1719 		if (!cmdsOK) {
1720 			PrintOnError(gn, "\n");	/* provide some clue */
1721 			DieHorribly();
1722 		}
1723 	} else if (((gn->type & OP_MAKE) && !opts.noRecursiveExecute) ||
1724 	    (!opts.noExecute && !opts.touch)) {
1725 		/*
1726 		 * The above condition looks very similar to
1727 		 * GNode_ShouldExecute but is subtly different.  It prevents
1728 		 * that .MAKE targets are touched since these are usually
1729 		 * virtual targets.
1730 		 */
1731 
1732 		/*
1733 		 * We're serious here, but if the commands were bogus, we're
1734 		 * also dead...
1735 		 */
1736 		if (!cmdsOK) {
1737 			PrintOnError(gn, "\n");	/* provide some clue */
1738 			DieHorribly();
1739 		}
1740 
1741 		JobWriteShellCommands(job, gn, &run);
1742 		(void)fflush(job->cmdFILE);
1743 	} else if (!GNode_ShouldExecute(gn)) {
1744 		/*
1745 		 * Just write all the commands to stdout in one fell swoop.
1746 		 * This still sets up job->tailCmds correctly.
1747 		 */
1748 		SwitchOutputTo(gn);
1749 		job->cmdFILE = stdout;
1750 		if (cmdsOK)
1751 			JobWriteCommands(job);
1752 		run = false;
1753 		(void)fflush(job->cmdFILE);
1754 	} else {
1755 		Job_Touch(gn, job->echo);
1756 		run = false;
1757 	}
1758 
1759 	/* If we're not supposed to execute a shell, don't. */
1760 	if (!run) {
1761 		if (!job->special)
1762 			Job_TokenReturn();
1763 		/* Unlink and close the command file if we opened one */
1764 		if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1765 			(void)fclose(job->cmdFILE);
1766 			job->cmdFILE = NULL;
1767 		}
1768 
1769 		/*
1770 		 * We only want to work our way up the graph if we aren't
1771 		 * here because the commands for the job were no good.
1772 		 */
1773 		if (cmdsOK && aborting == ABORT_NONE) {
1774 			JobSaveCommands(job);
1775 			job->node->made = MADE;
1776 			Make_Update(job->node);
1777 		}
1778 		job->status = JOB_ST_FREE;
1779 		return cmdsOK ? JOB_FINISHED : JOB_ERROR;
1780 	}
1781 
1782 	/*
1783 	 * Set up the control arguments to the shell. This is based on the
1784 	 * flags set earlier for this job.
1785 	 */
1786 	JobMakeArgv(job, argv);
1787 
1788 	/* Create the pipe by which we'll get the shell's output. */
1789 	JobCreatePipe(job, 3);
1790 
1791 	JobExec(job, argv);
1792 	return JOB_RUNNING;
1793 }
1794 
1795 /*
1796  * If the shell has an output filter (which only csh and ksh have by default),
1797  * print the output of the child process, skipping the noPrint text of the
1798  * shell.
1799  *
1800  * Return the part of the output that the calling function needs to output by
1801  * itself.
1802  */
1803 static char *
1804 PrintFilteredOutput(char *cp, char *endp)	/* XXX: should all be const */
1805 {
1806 	char *ecp;		/* XXX: should be const */
1807 
1808 	if (shell->noPrint == NULL || shell->noPrint[0] == '\0')
1809 		return cp;
1810 
1811 	/*
1812 	 * XXX: What happens if shell->noPrint occurs on the boundary of
1813 	 * the buffer?  To work correctly in all cases, this should rather
1814 	 * be a proper stream filter instead of doing string matching on
1815 	 * selected chunks of the output.
1816 	 */
1817 	while ((ecp = strstr(cp, shell->noPrint)) != NULL) {
1818 		if (ecp != cp) {
1819 			*ecp = '\0';	/* XXX: avoid writing to the buffer */
1820 			/*
1821 			 * The only way there wouldn't be a newline after
1822 			 * this line is if it were the last in the buffer.
1823 			 * however, since the noPrint output comes after it,
1824 			 * there must be a newline, so we don't print one.
1825 			 */
1826 			/* XXX: What about null bytes in the output? */
1827 			(void)fprintf(stdout, "%s", cp);
1828 			(void)fflush(stdout);
1829 		}
1830 		cp = ecp + shell->noPrintLen;
1831 		if (cp == endp)
1832 			break;
1833 		cp++;		/* skip over the (XXX: assumed) newline */
1834 		pp_skip_whitespace(&cp);
1835 	}
1836 	return cp;
1837 }
1838 
1839 /*
1840  * This function is called whenever there is something to read on the pipe.
1841  * We collect more output from the given job and store it in the job's
1842  * outBuf. If this makes up a line, we print it tagged by the job's
1843  * identifier, as necessary.
1844  *
1845  * In the output of the shell, the 'noPrint' lines are removed. If the
1846  * command is not alone on the line (the character after it is not \0 or
1847  * \n), we do print whatever follows it.
1848  *
1849  * Input:
1850  *	job		the job whose output needs printing
1851  *	finish		true if this is the last time we'll be called
1852  *			for this job
1853  */
1854 static void
1855 CollectOutput(Job *job, bool finish)
1856 {
1857 	bool gotNL;		/* true if got a newline */
1858 	bool fbuf;		/* true if our buffer filled up */
1859 	size_t nr;		/* number of bytes read */
1860 	size_t i;		/* auxiliary index into outBuf */
1861 	size_t max;		/* limit for i (end of current data) */
1862 	ssize_t nRead;		/* (Temporary) number of bytes read */
1863 
1864 	/* Read as many bytes as will fit in the buffer. */
1865 again:
1866 	gotNL = false;
1867 	fbuf = false;
1868 
1869 	nRead = read(job->inPipe, &job->outBuf[job->curPos],
1870 	    JOB_BUFSIZE - job->curPos);
1871 	if (nRead < 0) {
1872 		if (errno == EAGAIN)
1873 			return;
1874 		if (DEBUG(JOB)) {
1875 			perror("CollectOutput(piperead)");
1876 		}
1877 		nr = 0;
1878 	} else {
1879 		nr = (size_t)nRead;
1880 	}
1881 
1882 	/*
1883 	 * If we hit the end-of-file (the job is dead), we must flush its
1884 	 * remaining output, so pretend we read a newline if there's any
1885 	 * output remaining in the buffer.
1886 	 * Also clear the 'finish' flag so we stop looping.
1887 	 */
1888 	if (nr == 0 && job->curPos != 0) {
1889 		job->outBuf[job->curPos] = '\n';
1890 		nr = 1;
1891 		finish = false;
1892 	} else if (nr == 0) {
1893 		finish = false;
1894 	}
1895 
1896 	/*
1897 	 * Look for the last newline in the bytes we just got. If there is
1898 	 * one, break out of the loop with 'i' as its index and gotNL set
1899 	 * true.
1900 	 */
1901 	max = job->curPos + nr;
1902 	for (i = job->curPos + nr - 1;
1903 	     i >= job->curPos && i != (size_t)-1; i--) {
1904 		if (job->outBuf[i] == '\n') {
1905 			gotNL = true;
1906 			break;
1907 		} else if (job->outBuf[i] == '\0') {
1908 			/*
1909 			 * FIXME: The null characters are only replaced with
1910 			 * space _after_ the last '\n'.  Everywhere else they
1911 			 * hide the rest of the command output.
1912 			 */
1913 			job->outBuf[i] = ' ';
1914 		}
1915 	}
1916 
1917 	if (!gotNL) {
1918 		job->curPos += nr;
1919 		if (job->curPos == JOB_BUFSIZE) {
1920 			/*
1921 			 * If we've run out of buffer space, we have no choice
1922 			 * but to print the stuff. sigh.
1923 			 */
1924 			fbuf = true;
1925 			i = job->curPos;
1926 		}
1927 	}
1928 	if (gotNL || fbuf) {
1929 		/*
1930 		 * Need to send the output to the screen. Null terminate it
1931 		 * first, overwriting the newline character if there was one.
1932 		 * So long as the line isn't one we should filter (according
1933 		 * to the shell description), we print the line, preceded
1934 		 * by a target banner if this target isn't the same as the
1935 		 * one for which we last printed something.
1936 		 * The rest of the data in the buffer are then shifted down
1937 		 * to the start of the buffer and curPos is set accordingly.
1938 		 */
1939 		job->outBuf[i] = '\0';
1940 		if (i >= job->curPos) {
1941 			char *cp;
1942 
1943 			/*
1944 			 * FIXME: SwitchOutputTo should be here, according to
1945 			 * the comment above.  But since PrintOutput does not
1946 			 * do anything in the default shell, this bug has gone
1947 			 * unnoticed until now.
1948 			 */
1949 			cp = PrintFilteredOutput(job->outBuf, &job->outBuf[i]);
1950 
1951 			/*
1952 			 * There's still more in the output buffer. This time,
1953 			 * though, we know there's no newline at the end, so
1954 			 * we add one of our own free will.
1955 			 */
1956 			if (*cp != '\0') {
1957 				if (!opts.silent)
1958 					SwitchOutputTo(job->node);
1959 #ifdef USE_META
1960 				if (useMeta) {
1961 					meta_job_output(job, cp,
1962 					    gotNL ? "\n" : "");
1963 				}
1964 #endif
1965 				(void)fprintf(stdout, "%s%s", cp,
1966 				    gotNL ? "\n" : "");
1967 				(void)fflush(stdout);
1968 			}
1969 		}
1970 		/*
1971 		 * max is the last offset still in the buffer. Move any
1972 		 * remaining characters to the start of the buffer and
1973 		 * update the end marker curPos.
1974 		 */
1975 		if (i < max) {
1976 			(void)memmove(job->outBuf, &job->outBuf[i + 1],
1977 			    max - (i + 1));
1978 			job->curPos = max - (i + 1);
1979 		} else {
1980 			assert(i == max);
1981 			job->curPos = 0;
1982 		}
1983 	}
1984 	if (finish) {
1985 		/*
1986 		 * If the finish flag is true, we must loop until we hit
1987 		 * end-of-file on the pipe. This is guaranteed to happen
1988 		 * eventually since the other end of the pipe is now closed
1989 		 * (we closed it explicitly and the child has exited). When
1990 		 * we do get an EOF, finish will be set false and we'll fall
1991 		 * through and out.
1992 		 */
1993 		goto again;
1994 	}
1995 }
1996 
1997 static void
1998 JobRun(GNode *targ)
1999 {
2000 #if 0
2001 	/*
2002 	 * Unfortunately it is too complicated to run .BEGIN, .END, and
2003 	 * .INTERRUPT job in the parallel job module.  As of 2020-09-25,
2004 	 * unit-tests/deptgt-end-jobs.mk hangs in an endless loop.
2005 	 *
2006 	 * Running these jobs in compat mode also guarantees that these
2007 	 * jobs do not overlap with other unrelated jobs.
2008 	 */
2009 	GNodeList lst = LST_INIT;
2010 	Lst_Append(&lst, targ);
2011 	(void)Make_Run(&lst);
2012 	Lst_Done(&lst);
2013 	JobStart(targ, true);
2014 	while (jobTokensRunning != 0) {
2015 		Job_CatchOutput();
2016 	}
2017 #else
2018 	Compat_Make(targ, targ);
2019 	/* XXX: Replace with GNode_IsError(gn) */
2020 	if (targ->made == ERROR) {
2021 		PrintOnError(targ, "\n\nStop.\n");
2022 		exit(1);
2023 	}
2024 #endif
2025 }
2026 
2027 /*
2028  * Handle the exit of a child. Called from Make_Make.
2029  *
2030  * The job descriptor is removed from the list of children.
2031  *
2032  * Notes:
2033  *	We do waits, blocking or not, according to the wisdom of our
2034  *	caller, until there are no more children to report. For each
2035  *	job, call JobFinish to finish things off.
2036  */
2037 void
2038 Job_CatchChildren(void)
2039 {
2040 	int pid;		/* pid of dead child */
2041 	WAIT_T status;		/* Exit/termination status */
2042 
2043 	/* Don't even bother if we know there's no one around. */
2044 	if (jobTokensRunning == 0)
2045 		return;
2046 
2047 	/* Have we received SIGCHLD since last call? */
2048 	if (caught_sigchld == 0)
2049 		return;
2050 	caught_sigchld = 0;
2051 
2052 	while ((pid = waitpid((pid_t)-1, &status, WNOHANG | WUNTRACED)) > 0) {
2053 		DEBUG2(JOB, "Process %d exited/stopped status %x.\n",
2054 		    pid, WAIT_STATUS(status));
2055 		JobReapChild(pid, status, true);
2056 	}
2057 }
2058 
2059 /*
2060  * It is possible that wait[pid]() was called from elsewhere,
2061  * this lets us reap jobs regardless.
2062  */
2063 void
2064 JobReapChild(pid_t pid, WAIT_T status, bool isJobs)
2065 {
2066 	Job *job;		/* job descriptor for dead child */
2067 
2068 	/* Don't even bother if we know there's no one around. */
2069 	if (jobTokensRunning == 0)
2070 		return;
2071 
2072 	job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
2073 	if (job == NULL) {
2074 		if (isJobs) {
2075 			if (!lurking_children)
2076 				Error("Child (%d) status %x not in table?",
2077 				    pid, status);
2078 		}
2079 		return;		/* not ours */
2080 	}
2081 	if (WIFSTOPPED(status)) {
2082 		DEBUG2(JOB, "Process %d (%s) stopped.\n",
2083 		    job->pid, job->node->name);
2084 		if (!make_suspended) {
2085 			switch (WSTOPSIG(status)) {
2086 			case SIGTSTP:
2087 				(void)printf("*** [%s] Suspended\n",
2088 				    job->node->name);
2089 				break;
2090 			case SIGSTOP:
2091 				(void)printf("*** [%s] Stopped\n",
2092 				    job->node->name);
2093 				break;
2094 			default:
2095 				(void)printf("*** [%s] Stopped -- signal %d\n",
2096 				    job->node->name, WSTOPSIG(status));
2097 			}
2098 			job->suspended = true;
2099 		}
2100 		(void)fflush(stdout);
2101 		return;
2102 	}
2103 
2104 	job->status = JOB_ST_FINISHED;
2105 	job->exit_status = WAIT_STATUS(status);
2106 
2107 	JobFinish(job, status);
2108 }
2109 
2110 /*
2111  * Catch the output from our children, if we're using pipes do so. Otherwise
2112  * just block time until we get a signal(most likely a SIGCHLD) since there's
2113  * no point in just spinning when there's nothing to do and the reaping of a
2114  * child can wait for a while.
2115  */
2116 void
2117 Job_CatchOutput(void)
2118 {
2119 	int nready;
2120 	Job *job;
2121 	unsigned int i;
2122 
2123 	(void)fflush(stdout);
2124 
2125 	/* The first fd in the list is the job token pipe */
2126 	do {
2127 		nready = poll(fds + 1 - wantToken, fdsLen - 1 + wantToken,
2128 		    POLL_MSEC);
2129 	} while (nready < 0 && errno == EINTR);
2130 
2131 	if (nready < 0)
2132 		Punt("poll: %s", strerror(errno));
2133 
2134 	if (nready > 0 && readyfd(&childExitJob)) {
2135 		char token = 0;
2136 		ssize_t count;
2137 		count = read(childExitJob.inPipe, &token, 1);
2138 		if (count == 1) {
2139 			if (token == DO_JOB_RESUME[0])
2140 				/*
2141 				 * Complete relay requested from our SIGCONT
2142 				 * handler
2143 				 */
2144 				JobRestartJobs();
2145 		} else if (count == 0)
2146 			Punt("unexpected eof on token pipe");
2147 		else if (errno != EAGAIN)
2148 			Punt("token pipe read: %s", strerror(errno));
2149 		nready--;
2150 	}
2151 
2152 	Job_CatchChildren();
2153 	if (nready == 0)
2154 		return;
2155 
2156 	for (i = npseudojobs * nfds_per_job(); i < fdsLen; i++) {
2157 		if (fds[i].revents == 0)
2158 			continue;
2159 		job = jobByFdIndex[i];
2160 		if (job->status == JOB_ST_RUNNING)
2161 			CollectOutput(job, false);
2162 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2163 		/*
2164 		 * With meta mode, we may have activity on the job's filemon
2165 		 * descriptor too, which at the moment is any pollfd other
2166 		 * than job->inPollfd.
2167 		 */
2168 		if (useMeta && job->inPollfd != &fds[i]) {
2169 			if (meta_job_event(job) <= 0)
2170 				fds[i].events = 0;	/* never mind */
2171 		}
2172 #endif
2173 		if (--nready == 0)
2174 			return;
2175 	}
2176 }
2177 
2178 /*
2179  * Start the creation of a target. Basically a front-end for JobStart used by
2180  * the Make module.
2181  */
2182 void
2183 Job_Make(GNode *gn)
2184 {
2185 	(void)JobStart(gn, false);
2186 }
2187 
2188 static void
2189 InitShellNameAndPath(void)
2190 {
2191 	shellName = shell->name;
2192 
2193 #ifdef DEFSHELL_CUSTOM
2194 	if (shellName[0] == '/') {
2195 		shellPath = shellName;
2196 		shellName = str_basename(shellPath);
2197 		return;
2198 	}
2199 #endif
2200 #ifdef DEFSHELL_PATH
2201 	shellPath = DEFSHELL_PATH;
2202 #else
2203 	shellPath = str_concat3(_PATH_DEFSHELLDIR, "/", shellName);
2204 #endif
2205 }
2206 
2207 void
2208 Shell_Init(void)
2209 {
2210 	if (shellPath == NULL)
2211 		InitShellNameAndPath();
2212 
2213 	Var_SetWithFlags(SCOPE_CMDLINE, ".SHELL", shellPath, VAR_SET_READONLY);
2214 	if (shell->errFlag == NULL)
2215 		shell->errFlag = "";
2216 	if (shell->echoFlag == NULL)
2217 		shell->echoFlag = "";
2218 	if (shell->hasErrCtl && shell->errFlag[0] != '\0') {
2219 		if (shellErrFlag != NULL &&
2220 		    strcmp(shell->errFlag, &shellErrFlag[1]) != 0) {
2221 			free(shellErrFlag);
2222 			shellErrFlag = NULL;
2223 		}
2224 		if (shellErrFlag == NULL)
2225 			shellErrFlag = str_concat2("-", shell->errFlag);
2226 	} else if (shellErrFlag != NULL) {
2227 		free(shellErrFlag);
2228 		shellErrFlag = NULL;
2229 	}
2230 }
2231 
2232 /*
2233  * Return the string literal that is used in the current command shell
2234  * to produce a newline character.
2235  */
2236 const char *
2237 Shell_GetNewline(void)
2238 {
2239 	return shell->newline;
2240 }
2241 
2242 void
2243 Job_SetPrefix(void)
2244 {
2245 	if (targPrefix != NULL) {
2246 		free(targPrefix);
2247 	} else if (!Var_Exists(SCOPE_GLOBAL, MAKE_JOB_PREFIX)) {
2248 		Global_Set(MAKE_JOB_PREFIX, "---");
2249 	}
2250 
2251 	(void)Var_Subst("${" MAKE_JOB_PREFIX "}",
2252 	    SCOPE_GLOBAL, VARE_WANTRES, &targPrefix);
2253 	/* TODO: handle errors */
2254 }
2255 
2256 static void
2257 AddSig(int sig, SignalProc handler)
2258 {
2259 	if (bmake_signal(sig, SIG_IGN) != SIG_IGN) {
2260 		sigaddset(&caught_signals, sig);
2261 		(void)bmake_signal(sig, handler);
2262 	}
2263 }
2264 
2265 /* Initialize the process module. */
2266 void
2267 Job_Init(void)
2268 {
2269 	Job_SetPrefix();
2270 	/* Allocate space for all the job info */
2271 	job_table = bmake_malloc((size_t)opts.maxJobs * sizeof *job_table);
2272 	memset(job_table, 0, (size_t)opts.maxJobs * sizeof *job_table);
2273 	job_table_end = job_table + opts.maxJobs;
2274 	wantToken = 0;
2275 	caught_sigchld = 0;
2276 
2277 	aborting = ABORT_NONE;
2278 	job_errors = 0;
2279 
2280 	Always_pass_job_queue = GetBooleanExpr(MAKE_ALWAYS_PASS_JOB_QUEUE,
2281 	    Always_pass_job_queue);
2282 
2283 	Job_error_token = GetBooleanExpr(MAKE_JOB_ERROR_TOKEN, Job_error_token);
2284 
2285 
2286 	/*
2287 	 * There is a non-zero chance that we already have children.
2288 	 * eg after 'make -f- <<EOF'
2289 	 * Since their termination causes a 'Child (pid) not in table'
2290 	 * message, Collect the status of any that are already dead, and
2291 	 * suppress the error message if there are any undead ones.
2292 	 */
2293 	for (;;) {
2294 		int rval;
2295 		WAIT_T status;
2296 
2297 		rval = waitpid((pid_t)-1, &status, WNOHANG);
2298 		if (rval > 0)
2299 			continue;
2300 		if (rval == 0)
2301 			lurking_children = true;
2302 		break;
2303 	}
2304 
2305 	Shell_Init();
2306 
2307 	JobCreatePipe(&childExitJob, 3);
2308 
2309 	{
2310 		/* Preallocate enough for the maximum number of jobs. */
2311 		size_t nfds = (npseudojobs + (size_t)opts.maxJobs) *
2312 			      nfds_per_job();
2313 		fds = bmake_malloc(sizeof *fds * nfds);
2314 		jobByFdIndex = bmake_malloc(sizeof *jobByFdIndex * nfds);
2315 	}
2316 
2317 	/* These are permanent entries and take slots 0 and 1 */
2318 	watchfd(&tokenWaitJob);
2319 	watchfd(&childExitJob);
2320 
2321 	sigemptyset(&caught_signals);
2322 	/*
2323 	 * Install a SIGCHLD handler.
2324 	 */
2325 	(void)bmake_signal(SIGCHLD, JobChildSig);
2326 	sigaddset(&caught_signals, SIGCHLD);
2327 
2328 	/*
2329 	 * Catch the four signals that POSIX specifies if they aren't ignored.
2330 	 * JobPassSig will take care of calling JobInterrupt if appropriate.
2331 	 */
2332 	AddSig(SIGINT, JobPassSig_int);
2333 	AddSig(SIGHUP, JobPassSig_term);
2334 	AddSig(SIGTERM, JobPassSig_term);
2335 	AddSig(SIGQUIT, JobPassSig_term);
2336 
2337 	/*
2338 	 * There are additional signals that need to be caught and passed if
2339 	 * either the export system wants to be told directly of signals or if
2340 	 * we're giving each job its own process group (since then it won't get
2341 	 * signals from the terminal driver as we own the terminal)
2342 	 */
2343 	AddSig(SIGTSTP, JobPassSig_suspend);
2344 	AddSig(SIGTTOU, JobPassSig_suspend);
2345 	AddSig(SIGTTIN, JobPassSig_suspend);
2346 	AddSig(SIGWINCH, JobCondPassSig);
2347 	AddSig(SIGCONT, JobContinueSig);
2348 
2349 	(void)Job_RunTarget(".BEGIN", NULL);
2350 	/*
2351 	 * Create the .END node now, even though no code in the unit tests
2352 	 * depends on it.  See also Targ_GetEndNode in Compat_Run.
2353 	 */
2354 	(void)Targ_GetEndNode();
2355 }
2356 
2357 static void
2358 DelSig(int sig)
2359 {
2360 	if (sigismember(&caught_signals, sig) != 0)
2361 		(void)bmake_signal(sig, SIG_DFL);
2362 }
2363 
2364 static void
2365 JobSigReset(void)
2366 {
2367 	DelSig(SIGINT);
2368 	DelSig(SIGHUP);
2369 	DelSig(SIGQUIT);
2370 	DelSig(SIGTERM);
2371 	DelSig(SIGTSTP);
2372 	DelSig(SIGTTOU);
2373 	DelSig(SIGTTIN);
2374 	DelSig(SIGWINCH);
2375 	DelSig(SIGCONT);
2376 	(void)bmake_signal(SIGCHLD, SIG_DFL);
2377 }
2378 
2379 /* Find a shell in 'shells' given its name, or return NULL. */
2380 static Shell *
2381 FindShellByName(const char *name)
2382 {
2383 	Shell *sh = shells;
2384 	const Shell *shellsEnd = sh + sizeof shells / sizeof shells[0];
2385 
2386 	for (sh = shells; sh < shellsEnd; sh++) {
2387 		if (strcmp(name, sh->name) == 0)
2388 			return sh;
2389 	}
2390 	return NULL;
2391 }
2392 
2393 /*
2394  * Parse a shell specification and set up 'shell', shellPath and
2395  * shellName appropriately.
2396  *
2397  * Input:
2398  *	line		The shell spec
2399  *
2400  * Results:
2401  *	false if the specification was incorrect.
2402  *
2403  * Side Effects:
2404  *	'shell' points to a Shell structure (either predefined or
2405  *	created from the shell spec), shellPath is the full path of the
2406  *	shell described by 'shell', while shellName is just the
2407  *	final component of shellPath.
2408  *
2409  * Notes:
2410  *	A shell specification consists of a .SHELL target, with dependency
2411  *	operator, followed by a series of blank-separated words. Double
2412  *	quotes can be used to use blanks in words. A backslash escapes
2413  *	anything (most notably a double-quote and a space) and
2414  *	provides the functionality it does in C. Each word consists of
2415  *	keyword and value separated by an equal sign. There should be no
2416  *	unnecessary spaces in the word. The keywords are as follows:
2417  *	    name	Name of shell.
2418  *	    path	Location of shell.
2419  *	    quiet	Command to turn off echoing.
2420  *	    echo	Command to turn echoing on
2421  *	    filter	Result of turning off echoing that shouldn't be
2422  *			printed.
2423  *	    echoFlag	Flag to turn echoing on at the start
2424  *	    errFlag	Flag to turn error checking on at the start
2425  *	    hasErrCtl	True if shell has error checking control
2426  *	    newline	String literal to represent a newline char
2427  *	    check	Command to turn on error checking if hasErrCtl
2428  *			is true or template of command to echo a command
2429  *			for which error checking is off if hasErrCtl is
2430  *			false.
2431  *	    ignore	Command to turn off error checking if hasErrCtl
2432  *			is true or template of command to execute a
2433  *			command so as to ignore any errors it returns if
2434  *			hasErrCtl is false.
2435  */
2436 bool
2437 Job_ParseShell(char *line)
2438 {
2439 	Words wordsList;
2440 	char **words;
2441 	char **argv;
2442 	size_t argc;
2443 	char *path;
2444 	Shell newShell;
2445 	bool fullSpec = false;
2446 	Shell *sh;
2447 
2448 	/* XXX: don't use line as an iterator variable */
2449 	pp_skip_whitespace(&line);
2450 
2451 	free(shell_freeIt);
2452 
2453 	memset(&newShell, 0, sizeof newShell);
2454 
2455 	/*
2456 	 * Parse the specification by keyword
2457 	 */
2458 	wordsList = Str_Words(line, true);
2459 	words = wordsList.words;
2460 	argc = wordsList.len;
2461 	path = wordsList.freeIt;
2462 	if (words == NULL) {
2463 		Error("Unterminated quoted string [%s]", line);
2464 		return false;
2465 	}
2466 	shell_freeIt = path;
2467 
2468 	for (path = NULL, argv = words; argc != 0; argc--, argv++) {
2469 		char *arg = *argv;
2470 		if (strncmp(arg, "path=", 5) == 0) {
2471 			path = arg + 5;
2472 		} else if (strncmp(arg, "name=", 5) == 0) {
2473 			newShell.name = arg + 5;
2474 		} else {
2475 			if (strncmp(arg, "quiet=", 6) == 0) {
2476 				newShell.echoOff = arg + 6;
2477 			} else if (strncmp(arg, "echo=", 5) == 0) {
2478 				newShell.echoOn = arg + 5;
2479 			} else if (strncmp(arg, "filter=", 7) == 0) {
2480 				newShell.noPrint = arg + 7;
2481 				newShell.noPrintLen = strlen(newShell.noPrint);
2482 			} else if (strncmp(arg, "echoFlag=", 9) == 0) {
2483 				newShell.echoFlag = arg + 9;
2484 			} else if (strncmp(arg, "errFlag=", 8) == 0) {
2485 				newShell.errFlag = arg + 8;
2486 			} else if (strncmp(arg, "hasErrCtl=", 10) == 0) {
2487 				char c = arg[10];
2488 				newShell.hasErrCtl = c == 'Y' || c == 'y' ||
2489 						     c == 'T' || c == 't';
2490 			} else if (strncmp(arg, "newline=", 8) == 0) {
2491 				newShell.newline = arg + 8;
2492 			} else if (strncmp(arg, "check=", 6) == 0) {
2493 				/*
2494 				 * Before 2020-12-10, these two variables had
2495 				 * been a single variable.
2496 				 */
2497 				newShell.errOn = arg + 6;
2498 				newShell.echoTmpl = arg + 6;
2499 			} else if (strncmp(arg, "ignore=", 7) == 0) {
2500 				/*
2501 				 * Before 2020-12-10, these two variables had
2502 				 * been a single variable.
2503 				 */
2504 				newShell.errOff = arg + 7;
2505 				newShell.runIgnTmpl = arg + 7;
2506 			} else if (strncmp(arg, "errout=", 7) == 0) {
2507 				newShell.runChkTmpl = arg + 7;
2508 			} else if (strncmp(arg, "comment=", 8) == 0) {
2509 				newShell.commentChar = arg[8];
2510 			} else {
2511 				Parse_Error(PARSE_FATAL,
2512 				    "Unknown keyword \"%s\"", arg);
2513 				free(words);
2514 				return false;
2515 			}
2516 			fullSpec = true;
2517 		}
2518 	}
2519 
2520 	if (path == NULL) {
2521 		/*
2522 		 * If no path was given, the user wants one of the
2523 		 * pre-defined shells, yes? So we find the one s/he wants
2524 		 * with the help of FindShellByName and set things up the
2525 		 * right way. shellPath will be set up by Shell_Init.
2526 		 */
2527 		if (newShell.name == NULL) {
2528 			Parse_Error(PARSE_FATAL,
2529 			    "Neither path nor name specified");
2530 			free(words);
2531 			return false;
2532 		} else {
2533 			if ((sh = FindShellByName(newShell.name)) == NULL) {
2534 				Parse_Error(PARSE_WARNING,
2535 				    "%s: No matching shell", newShell.name);
2536 				free(words);
2537 				return false;
2538 			}
2539 			shell = sh;
2540 			shellName = newShell.name;
2541 			if (shellPath != NULL) {
2542 				/*
2543 				 * Shell_Init has already been called!
2544 				 * Do it again.
2545 				 */
2546 				free(UNCONST(shellPath));
2547 				shellPath = NULL;
2548 				Shell_Init();
2549 			}
2550 		}
2551 	} else {
2552 		/*
2553 		 * The user provided a path. If s/he gave nothing else
2554 		 * (fullSpec is false), try and find a matching shell in the
2555 		 * ones we know of. Else we just take the specification at
2556 		 * its word and copy it to a new location. In either case,
2557 		 * we need to record the path the user gave for the shell.
2558 		 */
2559 		shellPath = path;
2560 		path = strrchr(path, '/');
2561 		if (path == NULL) {
2562 			path = UNCONST(shellPath);
2563 		} else {
2564 			path++;
2565 		}
2566 		if (newShell.name != NULL) {
2567 			shellName = newShell.name;
2568 		} else {
2569 			shellName = path;
2570 		}
2571 		if (!fullSpec) {
2572 			if ((sh = FindShellByName(shellName)) == NULL) {
2573 				Parse_Error(PARSE_WARNING,
2574 				    "%s: No matching shell", shellName);
2575 				free(words);
2576 				return false;
2577 			}
2578 			shell = sh;
2579 		} else {
2580 			shell = bmake_malloc(sizeof *shell);
2581 			*shell = newShell;
2582 		}
2583 		/* this will take care of shellErrFlag */
2584 		Shell_Init();
2585 	}
2586 
2587 	if (shell->echoOn != NULL && shell->echoOff != NULL)
2588 		shell->hasEchoCtl = true;
2589 
2590 	if (!shell->hasErrCtl) {
2591 		if (shell->echoTmpl == NULL)
2592 			shell->echoTmpl = "";
2593 		if (shell->runIgnTmpl == NULL)
2594 			shell->runIgnTmpl = "%s\n";
2595 	}
2596 
2597 	/*
2598 	 * Do not free up the words themselves, since they might be in use
2599 	 * by the shell specification.
2600 	 */
2601 	free(words);
2602 	return true;
2603 }
2604 
2605 /*
2606  * Handle the receipt of an interrupt.
2607  *
2608  * All children are killed. Another job will be started if the .INTERRUPT
2609  * target is defined.
2610  *
2611  * Input:
2612  *	runINTERRUPT	Non-zero if commands for the .INTERRUPT target
2613  *			should be executed
2614  *	signo		signal received
2615  */
2616 static void
2617 JobInterrupt(bool runINTERRUPT, int signo)
2618 {
2619 	Job *job;		/* job descriptor in that element */
2620 	GNode *interrupt;	/* the node describing the .INTERRUPT target */
2621 	sigset_t mask;
2622 	GNode *gn;
2623 
2624 	aborting = ABORT_INTERRUPT;
2625 
2626 	JobSigLock(&mask);
2627 
2628 	for (job = job_table; job < job_table_end; job++) {
2629 		if (job->status != JOB_ST_RUNNING)
2630 			continue;
2631 
2632 		gn = job->node;
2633 
2634 		JobDeleteTarget(gn);
2635 		if (job->pid != 0) {
2636 			DEBUG2(JOB,
2637 			    "JobInterrupt passing signal %d to child %d.\n",
2638 			    signo, job->pid);
2639 			KILLPG(job->pid, signo);
2640 		}
2641 	}
2642 
2643 	JobSigUnlock(&mask);
2644 
2645 	if (runINTERRUPT && !opts.touch) {
2646 		interrupt = Targ_FindNode(".INTERRUPT");
2647 		if (interrupt != NULL) {
2648 			opts.ignoreErrors = false;
2649 			JobRun(interrupt);
2650 		}
2651 	}
2652 	Trace_Log(MAKEINTR, NULL);
2653 	exit(signo);		/* XXX: why signo? */
2654 }
2655 
2656 /*
2657  * Do the final processing, i.e. run the commands attached to the .END target.
2658  *
2659  * Return the number of errors reported.
2660  */
2661 int
2662 Job_Finish(void)
2663 {
2664 	GNode *endNode = Targ_GetEndNode();
2665 	if (!Lst_IsEmpty(&endNode->commands) ||
2666 	    !Lst_IsEmpty(&endNode->children)) {
2667 		if (job_errors != 0) {
2668 			Error("Errors reported so .END ignored");
2669 		} else {
2670 			JobRun(endNode);
2671 		}
2672 	}
2673 	return job_errors;
2674 }
2675 
2676 /* Clean up any memory used by the jobs module. */
2677 void
2678 Job_End(void)
2679 {
2680 #ifdef CLEANUP
2681 	free(shell_freeIt);
2682 #endif
2683 }
2684 
2685 /*
2686  * Waits for all running jobs to finish and returns.
2687  * Sets 'aborting' to ABORT_WAIT to prevent other jobs from starting.
2688  */
2689 void
2690 Job_Wait(void)
2691 {
2692 	aborting = ABORT_WAIT;
2693 	while (jobTokensRunning != 0) {
2694 		Job_CatchOutput();
2695 	}
2696 	aborting = ABORT_NONE;
2697 }
2698 
2699 /*
2700  * Abort all currently running jobs without handling output or anything.
2701  * This function is to be called only in the event of a major error.
2702  * Most definitely NOT to be called from JobInterrupt.
2703  *
2704  * All children are killed, not just the firstborn.
2705  */
2706 void
2707 Job_AbortAll(void)
2708 {
2709 	Job *job;		/* the job descriptor in that element */
2710 	WAIT_T foo;
2711 
2712 	aborting = ABORT_ERROR;
2713 
2714 	if (jobTokensRunning != 0) {
2715 		for (job = job_table; job < job_table_end; job++) {
2716 			if (job->status != JOB_ST_RUNNING)
2717 				continue;
2718 			/*
2719 			 * kill the child process with increasingly drastic
2720 			 * signals to make darn sure it's dead.
2721 			 */
2722 			KILLPG(job->pid, SIGINT);
2723 			KILLPG(job->pid, SIGKILL);
2724 		}
2725 	}
2726 
2727 	/*
2728 	 * Catch as many children as want to report in at first, then give up
2729 	 */
2730 	while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2731 		continue;
2732 }
2733 
2734 /*
2735  * Tries to restart stopped jobs if there are slots available.
2736  * Called in process context in response to a SIGCONT.
2737  */
2738 static void
2739 JobRestartJobs(void)
2740 {
2741 	Job *job;
2742 
2743 	for (job = job_table; job < job_table_end; job++) {
2744 		if (job->status == JOB_ST_RUNNING &&
2745 		    (make_suspended || job->suspended)) {
2746 			DEBUG1(JOB, "Restarting stopped job pid %d.\n",
2747 			    job->pid);
2748 			if (job->suspended) {
2749 				(void)printf("*** [%s] Continued\n",
2750 				    job->node->name);
2751 				(void)fflush(stdout);
2752 			}
2753 			job->suspended = false;
2754 			if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
2755 				debug_printf("Failed to send SIGCONT to %d\n",
2756 				    job->pid);
2757 			}
2758 		}
2759 		if (job->status == JOB_ST_FINISHED) {
2760 			/*
2761 			 * Job exit deferred after calling waitpid() in a
2762 			 * signal handler
2763 			 */
2764 			JobFinish(job, job->exit_status);
2765 		}
2766 	}
2767 	make_suspended = false;
2768 }
2769 
2770 static void
2771 watchfd(Job *job)
2772 {
2773 	if (job->inPollfd != NULL)
2774 		Punt("Watching watched job");
2775 
2776 	fds[fdsLen].fd = job->inPipe;
2777 	fds[fdsLen].events = POLLIN;
2778 	jobByFdIndex[fdsLen] = job;
2779 	job->inPollfd = &fds[fdsLen];
2780 	fdsLen++;
2781 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2782 	if (useMeta) {
2783 		fds[fdsLen].fd = meta_job_fd(job);
2784 		fds[fdsLen].events = fds[fdsLen].fd == -1 ? 0 : POLLIN;
2785 		jobByFdIndex[fdsLen] = job;
2786 		fdsLen++;
2787 	}
2788 #endif
2789 }
2790 
2791 static void
2792 clearfd(Job *job)
2793 {
2794 	size_t i;
2795 	if (job->inPollfd == NULL)
2796 		Punt("Unwatching unwatched job");
2797 	i = (size_t)(job->inPollfd - fds);
2798 	fdsLen--;
2799 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2800 	if (useMeta) {
2801 		/*
2802 		 * Sanity check: there should be two fds per job, so the job's
2803 		 * pollfd number should be even.
2804 		 */
2805 		assert(nfds_per_job() == 2);
2806 		if (i % 2 != 0)
2807 			Punt("odd-numbered fd with meta");
2808 		fdsLen--;
2809 	}
2810 #endif
2811 	/*
2812 	 * Move last job in table into hole made by dead job.
2813 	 */
2814 	if (fdsLen != i) {
2815 		fds[i] = fds[fdsLen];
2816 		jobByFdIndex[i] = jobByFdIndex[fdsLen];
2817 		jobByFdIndex[i]->inPollfd = &fds[i];
2818 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2819 		if (useMeta) {
2820 			fds[i + 1] = fds[fdsLen + 1];
2821 			jobByFdIndex[i + 1] = jobByFdIndex[fdsLen + 1];
2822 		}
2823 #endif
2824 	}
2825 	job->inPollfd = NULL;
2826 }
2827 
2828 static bool
2829 readyfd(Job *job)
2830 {
2831 	if (job->inPollfd == NULL)
2832 		Punt("Polling unwatched job");
2833 	return (job->inPollfd->revents & POLLIN) != 0;
2834 }
2835 
2836 /*
2837  * Put a token (back) into the job pipe.
2838  * This allows a make process to start a build job.
2839  */
2840 static void
2841 JobTokenAdd(void)
2842 {
2843 	char tok = JOB_TOKENS[aborting], tok1;
2844 
2845 	if (!Job_error_token && aborting == ABORT_ERROR) {
2846 		if (jobTokensRunning == 0)
2847 			return;
2848 		tok = '+';		/* no error token */
2849 	}
2850 
2851 	/* If we are depositing an error token flush everything else */
2852 	while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2853 		continue;
2854 
2855 	DEBUG3(JOB, "(%d) aborting %d, deposit token %c\n",
2856 	    getpid(), aborting, tok);
2857 	while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2858 		continue;
2859 }
2860 
2861 /* Get a temp file */
2862 int
2863 Job_TempFile(const char *pattern, char *tfile, size_t tfile_sz)
2864 {
2865 	int fd;
2866 	sigset_t mask;
2867 
2868 	JobSigLock(&mask);
2869 	fd = mkTempFile(pattern, tfile, tfile_sz);
2870 	if (tfile != NULL && !DEBUG(SCRIPT))
2871 		unlink(tfile);
2872 	JobSigUnlock(&mask);
2873 
2874 	return fd;
2875 }
2876 
2877 /* Prep the job token pipe in the root make process. */
2878 void
2879 Job_ServerStart(int max_tokens, int jp_0, int jp_1)
2880 {
2881 	int i;
2882 	char jobarg[64];
2883 
2884 	if (jp_0 >= 0 && jp_1 >= 0) {
2885 		/* Pipe passed in from parent */
2886 		tokenWaitJob.inPipe = jp_0;
2887 		tokenWaitJob.outPipe = jp_1;
2888 		(void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
2889 		(void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
2890 		return;
2891 	}
2892 
2893 	JobCreatePipe(&tokenWaitJob, 15);
2894 
2895 	snprintf(jobarg, sizeof jobarg, "%d,%d",
2896 	    tokenWaitJob.inPipe, tokenWaitJob.outPipe);
2897 
2898 	Global_Append(MAKEFLAGS, "-J");
2899 	Global_Append(MAKEFLAGS, jobarg);
2900 
2901 	/*
2902 	 * Preload the job pipe with one token per job, save the one
2903 	 * "extra" token for the primary job.
2904 	 *
2905 	 * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
2906 	 * larger than the write buffer size of the pipe, we will
2907 	 * deadlock here.
2908 	 */
2909 	for (i = 1; i < max_tokens; i++)
2910 		JobTokenAdd();
2911 }
2912 
2913 /* Return a withdrawn token to the pool. */
2914 void
2915 Job_TokenReturn(void)
2916 {
2917 	jobTokensRunning--;
2918 	if (jobTokensRunning < 0)
2919 		Punt("token botch");
2920 	if (jobTokensRunning != 0 || JOB_TOKENS[aborting] != '+')
2921 		JobTokenAdd();
2922 }
2923 
2924 /*
2925  * Attempt to withdraw a token from the pool.
2926  *
2927  * If pool is empty, set wantToken so that we wake up when a token is
2928  * released.
2929  *
2930  * Returns true if a token was withdrawn, and false if the pool is currently
2931  * empty.
2932  */
2933 bool
2934 Job_TokenWithdraw(void)
2935 {
2936 	char tok, tok1;
2937 	ssize_t count;
2938 
2939 	wantToken = 0;
2940 	DEBUG3(JOB, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
2941 	    getpid(), aborting, jobTokensRunning);
2942 
2943 	if (aborting != ABORT_NONE || (jobTokensRunning >= opts.maxJobs))
2944 		return false;
2945 
2946 	count = read(tokenWaitJob.inPipe, &tok, 1);
2947 	if (count == 0)
2948 		Fatal("eof on job pipe!");
2949 	if (count < 0 && jobTokensRunning != 0) {
2950 		if (errno != EAGAIN) {
2951 			Fatal("job pipe read: %s", strerror(errno));
2952 		}
2953 		DEBUG1(JOB, "(%d) blocked for token\n", getpid());
2954 		wantToken = 1;
2955 		return false;
2956 	}
2957 
2958 	if (count == 1 && tok != '+') {
2959 		/* make being aborted - remove any other job tokens */
2960 		DEBUG2(JOB, "(%d) aborted by token %c\n", getpid(), tok);
2961 		while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2962 			continue;
2963 		/* And put the stopper back */
2964 		while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
2965 		       errno == EAGAIN)
2966 			continue;
2967 		if (shouldDieQuietly(NULL, 1))
2968 			exit(6);	/* we aborted */
2969 		Fatal("A failure has been detected "
2970 		      "in another branch of the parallel make");
2971 	}
2972 
2973 	if (count == 1 && jobTokensRunning == 0)
2974 		/* We didn't want the token really */
2975 		while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
2976 		       errno == EAGAIN)
2977 			continue;
2978 
2979 	jobTokensRunning++;
2980 	DEBUG1(JOB, "(%d) withdrew token\n", getpid());
2981 	return true;
2982 }
2983 
2984 /*
2985  * Run the named target if found. If a filename is specified, then set that
2986  * to the sources.
2987  *
2988  * Exits if the target fails.
2989  */
2990 bool
2991 Job_RunTarget(const char *target, const char *fname)
2992 {
2993 	GNode *gn = Targ_FindNode(target);
2994 	if (gn == NULL)
2995 		return false;
2996 
2997 	if (fname != NULL)
2998 		Var_Set(gn, ALLSRC, fname);
2999 
3000 	JobRun(gn);
3001 	/* XXX: Replace with GNode_IsError(gn) */
3002 	if (gn->made == ERROR) {
3003 		PrintOnError(gn, "\n\nStop.\n");
3004 		exit(1);
3005 	}
3006 	return true;
3007 }
3008 
3009 #ifdef USE_SELECT
3010 int
3011 emul_poll(struct pollfd *fd, int nfd, int timeout)
3012 {
3013 	fd_set rfds, wfds;
3014 	int i, maxfd, nselect, npoll;
3015 	struct timeval tv, *tvp;
3016 	long usecs;
3017 
3018 	FD_ZERO(&rfds);
3019 	FD_ZERO(&wfds);
3020 
3021 	maxfd = -1;
3022 	for (i = 0; i < nfd; i++) {
3023 		fd[i].revents = 0;
3024 
3025 		if (fd[i].events & POLLIN)
3026 			FD_SET(fd[i].fd, &rfds);
3027 
3028 		if (fd[i].events & POLLOUT)
3029 			FD_SET(fd[i].fd, &wfds);
3030 
3031 		if (fd[i].fd > maxfd)
3032 			maxfd = fd[i].fd;
3033 	}
3034 
3035 	if (maxfd >= FD_SETSIZE) {
3036 		Punt("Ran out of fd_set slots; "
3037 		     "recompile with a larger FD_SETSIZE.");
3038 	}
3039 
3040 	if (timeout < 0) {
3041 		tvp = NULL;
3042 	} else {
3043 		usecs = timeout * 1000;
3044 		tv.tv_sec = usecs / 1000000;
3045 		tv.tv_usec = usecs % 1000000;
3046 		tvp = &tv;
3047 	}
3048 
3049 	nselect = select(maxfd + 1, &rfds, &wfds, NULL, tvp);
3050 
3051 	if (nselect <= 0)
3052 		return nselect;
3053 
3054 	npoll = 0;
3055 	for (i = 0; i < nfd; i++) {
3056 		if (FD_ISSET(fd[i].fd, &rfds))
3057 			fd[i].revents |= POLLIN;
3058 
3059 		if (FD_ISSET(fd[i].fd, &wfds))
3060 			fd[i].revents |= POLLOUT;
3061 
3062 		if (fd[i].revents)
3063 			npoll++;
3064 	}
3065 
3066 	return npoll;
3067 }
3068 #endif				/* USE_SELECT */
3069