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