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