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