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