job.c revision 146557
1/*-
2 * Copyright (c) 1988, 1989, 1990, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 * Copyright (c) 1988, 1989 by Adam de Boor
5 * Copyright (c) 1989 by Berkeley Softworks
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to Berkeley by
9 * Adam de Boor.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 *    must display the following acknowledgement:
21 *	This product includes software developed by the University of
22 *	California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 *    may be used to endorse or promote products derived from this software
25 *    without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
38 *
39 * @(#)job.c	8.2 (Berkeley) 3/19/94
40 */
41
42#include <sys/cdefs.h>
43__FBSDID("$FreeBSD: head/usr.bin/make/job.c 146557 2005-05-24 07:45:49Z harti $");
44
45#ifndef OLD_JOKE
46#define	OLD_JOKE 0
47#endif /* OLD_JOKE */
48
49/*-
50 * job.c --
51 *	handle the creation etc. of our child processes.
52 *
53 * Interface:
54 *	Job_Make	Start the creation of the given target.
55 *
56 *	Job_CatchChildren
57 *			Check for and handle the termination of any children.
58 *			This must be called reasonably frequently to keep the
59 *			whole make going at a decent clip, since job table
60 *			entries aren't removed until their process is caught
61 *			this way. Its single argument is TRUE if the function
62 *			should block waiting for a child to terminate.
63 *
64 *	Job_CatchOutput	Print any output our children have produced. Should
65 *			also be called fairly frequently to keep the user
66 *			informed of what's going on. If no output is waiting,
67 *			it will block for a time given by the SEL_* constants,
68 *			below, or until output is ready.
69 *
70 *	Job_Init	Called to intialize this module. in addition, any
71 *			commands attached to the .BEGIN target are executed
72 *			before this function returns. Hence, the makefile must
73 *			have been parsed before this function is called.
74 *
75 *	Job_Full	Return TRUE if the job table is filled.
76 *
77 *	Job_Empty	Return TRUE if the job table is completely empty.
78 *
79 *	Job_ParseShell	Given the line following a .SHELL target, parse the
80 *			line as a shell specification. Returns FALSE if the
81 *			spec was incorrect.
82 *
83 *	Job_Finish	Perform any final processing which needs doing. This
84 *			includes the execution of any commands which have
85 *			been/were attached to the .END target. It should only
86 *			be called when the job table is empty.
87 *
88 *	Job_AbortAll	Abort all currently running jobs. It doesn't handle
89 *			output or do anything for the jobs, just kills them.
90 *			It should only be called in an emergency, as it were.
91 *
92 *	Job_CheckCommands
93 *			Verify that the commands for a target are ok. Provide
94 *			them if necessary and possible.
95 *
96 *	Job_Touch	Update a target without really updating it.
97 *
98 *	Job_Wait	Wait for all currently-running jobs to finish.
99 *
100 * compat.c --
101 *	The routines in this file implement the full-compatibility
102 *	mode of PMake. Most of the special functionality of PMake
103 *	is available in this mode. Things not supported:
104 *	    - different shells.
105 *	    - friendly variable substitution.
106 *
107 * Interface:
108 *	Compat_Run	    Initialize things for this module and recreate
109 *			    thems as need creatin'
110 */
111
112#include <sys/queue.h>
113#include <sys/types.h>
114#include <sys/select.h>
115#include <sys/stat.h>
116#ifdef USE_KQUEUE
117#include <sys/event.h>
118#endif
119#include <sys/wait.h>
120#include <ctype.h>
121#include <err.h>
122#include <errno.h>
123#include <fcntl.h>
124#include <inttypes.h>
125#include <string.h>
126#include <signal.h>
127#include <stdlib.h>
128#include <unistd.h>
129#include <utime.h>
130
131#include "arch.h"
132#include "buf.h"
133#include "config.h"
134#include "dir.h"
135#include "globals.h"
136#include "GNode.h"
137#include "job.h"
138#include "make.h"
139#include "parse.h"
140#include "pathnames.h"
141#include "str.h"
142#include "suff.h"
143#include "targ.h"
144#include "util.h"
145#include "var.h"
146
147#define	TMPPAT	"/tmp/makeXXXXXXXXXX"
148
149#ifndef USE_KQUEUE
150/*
151 * The SEL_ constants determine the maximum amount of time spent in select
152 * before coming out to see if a child has finished. SEL_SEC is the number of
153 * seconds and SEL_USEC is the number of micro-seconds
154 */
155#define	SEL_SEC		2
156#define	SEL_USEC	0
157#endif /* !USE_KQUEUE */
158
159/*
160 * Job Table definitions.
161 *
162 * The job "table" is kept as a linked Lst in 'jobs', with the number of
163 * active jobs maintained in the 'nJobs' variable. At no time will this
164 * exceed the value of 'maxJobs', initialized by the Job_Init function.
165 *
166 * When a job is finished, the Make_Update function is called on each of the
167 * parents of the node which was just remade. This takes care of the upward
168 * traversal of the dependency graph.
169 */
170#define	JOB_BUFSIZE	1024
171typedef struct Job {
172	pid_t		pid;	/* The child's process ID */
173
174	struct GNode	*node;	/* The target the child is making */
175
176	/*
177	 * A LstNode for the first command to be saved after the job completes.
178	 * This is NULL if there was no "..." in the job's commands.
179	 */
180	LstNode		*tailCmds;
181
182	/*
183	 * An FILE* for writing out the commands. This is only
184	 * used before the job is actually started.
185	 */
186	FILE		*cmdFILE;
187
188	/*
189	 * A word of flags which determine how the module handles errors,
190	 * echoing, etc. for the job
191	 */
192	short		flags;	/* Flags to control treatment of job */
193#define	JOB_IGNERR	0x001	/* Ignore non-zero exits */
194#define	JOB_SILENT	0x002	/* no output */
195#define	JOB_SPECIAL	0x004	/* Target is a special one. i.e. run it locally
196				 * if we can't export it and maxLocal is 0 */
197#define	JOB_IGNDOTS	0x008	/* Ignore "..." lines when processing
198				 * commands */
199#define	JOB_FIRST	0x020	/* Job is first job for the node */
200#define	JOB_RESTART	0x080	/* Job needs to be completely restarted */
201#define	JOB_RESUME	0x100	/* Job needs to be resumed b/c it stopped,
202				 * for some reason */
203#define	JOB_CONTINUING	0x200	/* We are in the process of resuming this job.
204				 * Used to avoid infinite recursion between
205				 * JobFinish and JobRestart */
206
207	/* union for handling shell's output */
208	union {
209		/*
210		 * This part is used when usePipes is true.
211		 * The output is being caught via a pipe and the descriptors
212		 * of our pipe, an array in which output is line buffered and
213		 * the current position in that buffer are all maintained for
214		 * each job.
215		 */
216		struct {
217			/*
218			 * Input side of pipe associated with
219			 * job's output channel
220			 */
221			int	op_inPipe;
222
223			/*
224			 * Output side of pipe associated with job's
225			 * output channel
226			 */
227			int	op_outPipe;
228
229			/*
230			 * Buffer for storing the output of the
231			 * job, line by line
232			 */
233			char	op_outBuf[JOB_BUFSIZE + 1];
234
235			/* Current position in op_outBuf */
236			int	op_curPos;
237		}	o_pipe;
238
239		/*
240		 * If usePipes is false the output is routed to a temporary
241		 * file and all that is kept is the name of the file and the
242		 * descriptor open to the file.
243		 */
244		struct {
245			/* Name of file to which shell output was rerouted */
246			char	of_outFile[sizeof(TMPPAT)];
247
248			/*
249			 * Stream open to the output file. Used to funnel all
250			 * from a single job to one file while still allowing
251			 * multiple shell invocations
252			 */
253			int	of_outFd;
254		}	o_file;
255
256	}       output;	    /* Data for tracking a shell's output */
257
258	TAILQ_ENTRY(Job) link;	/* list link */
259} Job;
260
261#define	outPipe		output.o_pipe.op_outPipe
262#define	inPipe		output.o_pipe.op_inPipe
263#define	outBuf		output.o_pipe.op_outBuf
264#define	curPos		output.o_pipe.op_curPos
265#define	outFile		output.o_file.of_outFile
266#define	outFd		output.o_file.of_outFd
267
268TAILQ_HEAD(JobList, Job);
269
270/*
271 * Shell Specifications:
272 *
273 * Some special stuff goes on if a shell doesn't have error control. In such
274 * a case, errCheck becomes a printf template for echoing the command,
275 * should echoing be on and ignErr becomes another printf template for
276 * executing the command while ignoring the return status. If either of these
277 * strings is empty when hasErrCtl is FALSE, the command will be executed
278 * anyway as is and if it causes an error, so be it.
279 */
280struct Shell {
281	/*
282	 * the name of the shell. For Bourne and C shells, this is used
283	 * only to find the shell description when used as the single
284	 * source of a .SHELL target. For user-defined shells, this is
285	 * the full path of the shell.
286	 */
287	char	*name;
288	char	*path;
289
290	/* True if both echoOff and echoOn defined */
291	Boolean	hasEchoCtl;
292
293	char	*echoOff;	/* command to turn off echo */
294	char	*echoOn;	/* command to turn it back on */
295
296	/*
297	 * What the shell prints, when given the echo-off command.
298	 * This line will not be printed when received from the shell.
299	 * This is usually the command which was executed to turn off echoing.
300	 */
301	char	*noPrint;
302
303	/* set if can control error checking for individual commands */
304	Boolean	hasErrCtl;
305
306	/* string to turn error checking on */
307	char	*errCheck;
308
309	/* string to turn off error checking */
310	char	*ignErr;
311
312	char	*echo;	/* command line flag: echo commands */
313	char	*exit;	/* command line flag: exit on error */
314
315	ArgArray builtins;
316	char	*meta;
317};
318
319/*
320 * error handling variables
321 */
322static int	errors = 0;	/* number of errors reported */
323static int	aborting = 0;	/* why is the make aborting? */
324#define	ABORT_ERROR	1	/* Because of an error */
325#define	ABORT_INTERRUPT	2	/* Because it was interrupted */
326#define	ABORT_WAIT	3	/* Waiting for jobs to finish */
327
328/*
329 * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
330 * is a char! So when we go above 127 we turn negative!
331 */
332#define	FILENO(a) ((unsigned)fileno(a))
333
334/*
335 * post-make command processing. The node postCommands is really just the
336 * .END target but we keep it around to avoid having to search for it
337 * all the time.
338 */
339static GNode	*postCommands;
340
341/*
342 * The number of commands actually printed for a target. Should this
343 * number be 0, no shell will be executed.
344 */
345static int	numCommands;
346
347/*
348 * Return values from JobStart.
349 */
350#define	JOB_RUNNING	0	/* Job is running */
351#define	JOB_ERROR	1	/* Error in starting the job */
352#define	JOB_FINISHED	2	/* The job is already finished */
353#define	JOB_STOPPED	3	/* The job is stopped */
354
355/*
356 * Descriptions for various shells. What the list of builtins should contain
357 * is debatable: either all builtins or only those which may specified on
358 * a single line without use of meta-characters. For correct makefiles that
359 * contain only correct command lines there is no difference. But if a command
360 * line, for example, is: 'if -foo bar' and there is an executable named 'if'
361 * in the path, the first possibility would execute that 'if' while in the
362 * second case the shell would give an error. Histerically only a small
363 * subset of the builtins and no reserved words where given in the list which
364 * corresponds roughly to the first variant. So go with this but add missing
365 * words.
366 */
367#define	CSH_BUILTINS						\
368	"alias cd eval exec exit read set ulimit unalias "	\
369	"umask unset wait"
370
371#define	SH_BUILTINS						\
372	"alias cd eval exec exit read set ulimit unalias "	\
373	"umask unset wait"
374
375#define	CSH_META	"#=|^(){};&<>*?[]:$`\\@\n"
376#define	SH_META		"#=|^(){};&<>*?[]:$`\\\n"
377
378static const char *const shells[][2] = {
379	/*
380	 * CSH description. The csh can do echo control by playing
381	 * with the setting of the 'echo' shell variable. Sadly,
382	 * however, it is unable to do error control nicely.
383	 */
384	{ "csh",
385	  "name=csh path='" PATH_DEFSHELLDIR "/csh' "
386	  "quiet='unset verbose' echo='set verbose' filter='unset verbose' "
387	  "hasErrCtl=N check='echo \"%s\"\n' ignore='csh -c \"%s || exit 0\"' "
388	  "echoFlag=v errFlag=e "
389	  "meta='" CSH_META "' builtins='" CSH_BUILTINS "'"
390	},
391	/*
392	 * SH description. Echo control is also possible and, under
393	 * sun UNIX anyway, one can even control error checking.
394	 */
395	{
396	  "sh",
397	  "name=sh path='" PATH_DEFSHELLDIR "/sh' "
398	  "quiet='set -' echo='set -v' filter='set -' "
399	  "hasErrCtl=Y check='set -e' ignore='set +e' "
400	  "echoFlag=v errFlag=e "
401	  "meta='" SH_META "' builtins='" SH_BUILTINS "'"
402	},
403	/*
404	 * KSH description. The Korn shell has a superset of
405	 * the Bourne shell's functionality. There are probably builtins
406	 * missing here.
407	 */
408	{
409	  "ksh",
410	  "name=ksh path='" PATH_DEFSHELLDIR "/ksh' "
411	  "quiet='set -' echo='set -v' filter='set -' "
412	  "hasErrCtl=Y check='set -e' ignore='set +e' "
413	  "echoFlag=v errFlag=e "
414	  "meta='" SH_META "' builtins='" SH_BUILTINS "'"
415	},
416	{ NULL, NULL }
417};
418
419/*
420 * This is the shell to which we pass all commands in the Makefile.
421 * It is set by the Job_ParseShell function.
422 */
423static struct Shell *commandShell = NULL;
424
425/*
426 * The maximum number of jobs that may run. This is initialize from the
427 * -j argument for the leading make and from the FIFO for sub-makes.
428 */
429static int	maxJobs;
430
431static int	nJobs;		/* The number of children currently running */
432
433/* The structures that describe them */
434static struct JobList jobs = TAILQ_HEAD_INITIALIZER(jobs);
435
436static Boolean	jobFull;	/* Flag to tell when the job table is full. It
437				 * is set TRUE when (1) the total number of
438				 * running jobs equals the maximum allowed */
439#ifdef USE_KQUEUE
440static int	kqfd;		/* File descriptor obtained by kqueue() */
441#else
442static fd_set	outputs;	/* Set of descriptors of pipes connected to
443				 * the output channels of children */
444#endif
445
446static GNode	*lastNode;	/* The node for which output was most recently
447				 * produced. */
448static const char *targFmt;	/* Format string to use to head output from a
449				 * job when it's not the most-recent job heard
450				 * from */
451
452#define	TARG_FMT  "--- %s ---\n" /* Default format */
453#define	MESSAGE(fp, gn) \
454	 fprintf(fp, targFmt, gn->name);
455
456/*
457 * When JobStart attempts to run a job but isn't allowed to
458 * or when Job_CatchChildren detects a job that has
459 * been stopped somehow, the job is placed on the stoppedJobs queue to be run
460 * when the next job finishes.
461 *
462 * Lst of Job structures describing jobs that were stopped due to
463 * concurrency limits or externally
464 */
465static struct JobList stoppedJobs = TAILQ_HEAD_INITIALIZER(stoppedJobs);
466
467static int	fifoFd;		/* Fd of our job fifo */
468static char	fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
469static int	fifoMaster;
470
471static sig_atomic_t interrupted;
472
473
474#if defined(USE_PGRP) && defined(SYSV)
475# define KILL(pid, sig)		killpg(-(pid), (sig))
476#else
477# if defined(USE_PGRP)
478#  define KILL(pid, sig)	killpg((pid), (sig))
479# else
480#  define KILL(pid, sig)	kill((pid), (sig))
481# endif
482#endif
483
484/*
485 * Grmpf... There is no way to set bits of the wait structure
486 * anymore with the stupid W*() macros. I liked the union wait
487 * stuff much more. So, we devise our own macros... This is
488 * really ugly, use dramamine sparingly. You have been warned.
489 */
490#define	W_SETMASKED(st, val, fun)				\
491	{							\
492		int sh = (int)~0;				\
493		int mask = fun(sh);				\
494								\
495		for (sh = 0; ((mask >> sh) & 1) == 0; sh++)	\
496			continue;				\
497		*(st) = (*(st) & ~mask) | ((val) << sh);	\
498	}
499
500#define	W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
501#define	W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
502
503/**
504 * Information used to create a new process.
505 */
506typedef struct ProcStuff {
507	int	in;	/* stdin for new process */
508	int	out;	/* stdout for new process */
509	int	err;	/* stderr for new process */
510
511	int	merge_errors;	/* true if stderr is redirected to stdin */
512	int	pgroup;		/* true if new process a process leader */
513	int	searchpath;	/* true if binary should be found via $PATH */
514
515	char	**argv;
516	int	argv_free;	/* release argv after use */
517	int	errCheck;
518
519	pid_t	child_pid;
520} ProcStuff;
521
522static void JobRestart(Job *);
523static int JobStart(GNode *, int, Job *);
524static void JobDoOutput(Job *, Boolean);
525static struct Shell *JobMatchShell(const char *);
526static void JobInterrupt(int, int);
527static void JobRestartJobs(void);
528static void ProcExec(const ProcStuff *) __dead2;
529static int Compat_RunCommand(char *, struct GNode *);
530static void JobShellDump(const struct Shell *) __unused;
531
532static GNode	    *curTarg = NULL;
533static GNode	    *ENDNode;
534
535/**
536 * Create a fifo file with a uniq filename, and returns a file
537 * descriptor to that fifo.
538 */
539static int
540mkfifotemp(char *template)
541{
542	char *start;
543	char *pathend;
544	char *ptr;
545	const unsigned char padchar[] =
546	    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
547
548	if (template[0] == '\0') {
549		errno = EINVAL;	/* bad input string */
550		return (-1);
551	}
552
553	/* Find end of template string. */
554	pathend = strchr(template, '\0');
555	ptr = pathend - 1;
556
557	/*
558	 * Starting from the end of the template replace spaces with 'X' in
559	 * them with random characters until there are no more 'X'.
560	 */
561	while (ptr >= template && *ptr == 'X') {
562		uint32_t rand_num = arc4random() % (sizeof(padchar) - 1);
563		*ptr-- = padchar[rand_num];
564	}
565	start = ptr + 1;
566
567	/* Check the target directory. */
568	for (; ptr > template; --ptr) {
569		if (*ptr == '/') {
570			struct stat sbuf;
571
572			*ptr = '\0';
573			if (stat(template, &sbuf) != 0)
574				return (-1);
575
576			if (!S_ISDIR(sbuf.st_mode)) {
577				errno = ENOTDIR;
578				return (-1);
579			}
580			*ptr = '/';
581			break;
582		}
583	}
584
585	for (;;) {
586		if (mkfifo(template, 0600) == 0) {
587			int fd;
588
589			if ((fd = open(template, O_RDWR, 0600)) < 0) {
590				unlink(template);
591				return (-1);
592			} else {
593				return (fd);
594			}
595		} else {
596			if (errno != EEXIST) {
597				return (-1);
598			}
599		}
600
601		/*
602		 * If we have a collision, cycle through the space of
603		 * filenames.
604		 */
605		for (ptr = start;;) {
606			char *pad;
607
608			if (*ptr == '\0' || ptr == pathend)
609				return (-1);
610
611			pad = strchr(padchar, *ptr);
612			if (pad == NULL || *++pad == '\0') {
613				*ptr++ = padchar[0];
614			} else {
615				*ptr++ = *pad;
616				break;
617			}
618		}
619	}
620	/*NOTREACHED*/
621}
622
623static void
624catch_child(int sig __unused)
625{
626}
627
628/**
629 */
630void
631Proc_Init()
632{
633	/*
634	 * Catch SIGCHLD so that we get kicked out of select() when we
635	 * need to look at a child.  This is only known to matter for the
636	 * -j case (perhaps without -P).
637	 *
638	 * XXX this is intentionally misplaced.
639	 */
640	struct sigaction sa;
641
642	sigemptyset(&sa.sa_mask);
643	sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
644	sa.sa_handler = catch_child;
645	sigaction(SIGCHLD, &sa, NULL);
646
647#if DEFSHELL == 2
648	/*
649	 * Turn off ENV to make ksh happier.
650	 */
651	unsetenv("ENV");
652#endif
653}
654
655/**
656 * Replace the current process.
657 */
658static void
659ProcExec(const ProcStuff *ps)
660{
661
662	if (ps->in != STDIN_FILENO) {
663		/*
664		 * Redirect the child's stdin to the input fd
665		 * and reset it to the beginning (again).
666		 */
667		if (dup2(ps->in, STDIN_FILENO) == -1)
668			Punt("Cannot dup2: %s", strerror(errno));
669		lseek(STDIN_FILENO, (off_t)0, SEEK_SET);
670	}
671
672	if (ps->out != STDOUT_FILENO) {
673		/*
674		 * Redirect the child's stdout to the output fd.
675		 */
676		if (dup2(ps->out, STDOUT_FILENO) == -1)
677			Punt("Cannot dup2: %s", strerror(errno));
678		close(ps->out);
679	}
680
681	if (ps->err != STDERR_FILENO) {
682		/*
683		 * Redirect the child's stderr to the err fd.
684		 */
685		if (dup2(ps->err, STDERR_FILENO) == -1)
686			Punt("Cannot dup2: %s", strerror(errno));
687		close(ps->err);
688	}
689
690	if (ps->merge_errors) {
691		/*
692		 * Send stderr to parent process too.
693		 */
694		if (dup2(STDOUT_FILENO, STDERR_FILENO) == -1)
695			Punt("Cannot dup2: %s", strerror(errno));
696	}
697
698	/*
699	 * The file descriptors for stdin, stdout, or stderr might
700	 * have been marked close-on-exec.  Clear the flag on all
701	 * of them.
702	 */
703	fcntl(STDIN_FILENO, F_SETFD,
704	    fcntl(STDIN_FILENO, F_GETFD) & (~FD_CLOEXEC));
705	fcntl(STDOUT_FILENO, F_SETFD,
706	    fcntl(STDOUT_FILENO, F_GETFD) & (~FD_CLOEXEC));
707	fcntl(STDERR_FILENO, F_SETFD,
708	    fcntl(STDERR_FILENO, F_GETFD) & (~FD_CLOEXEC));
709
710	if (ps->pgroup) {
711#ifdef USE_PGRP
712		/*
713		 * Become a process group leader, so we can kill it and all
714		 * its descendants in one fell swoop, by killing its process
715		 * family, but not commit suicide.
716		 */
717#if defined(SYSV)
718		setsid();
719#else
720		setpgid(0, getpid());
721#endif
722#endif /* USE_PGRP */
723	}
724
725	if (ps->searchpath) {
726		execvp(ps->argv[0], ps->argv);
727
728		write(STDERR_FILENO, ps->argv[0], strlen(ps->argv[0]));
729		write(STDERR_FILENO, ":", 1);
730		write(STDERR_FILENO, strerror(errno), strlen(strerror(errno)));
731		write(STDERR_FILENO, "\n", 1);
732	} else {
733		execv(commandShell->path, ps->argv);
734
735		write(STDERR_FILENO,
736		      "Could not execute shell\n",
737		      sizeof("Could not execute shell"));
738	}
739
740	/*
741	 * Since we are the child process, exit without flushing buffers.
742	 */
743	_exit(1);
744	/* NOTREACHED */
745}
746
747/**
748 * Wait for child process to terminate.
749 */
750static int
751ProcWait(ProcStuff *ps)
752{
753	pid_t	pid;
754	int	status;
755
756	/*
757	 * Wait for the process to exit.
758	 */
759	for (;;) {
760		pid = wait(&status);
761		if (pid == -1 && errno != EINTR) {
762			Fatal("error in wait: %d", pid);
763			/* NOTREACHED */
764		}
765		if (pid == ps->child_pid) {
766			break;
767		}
768		if (interrupted) {
769			break;
770		}
771	}
772
773	return (status);
774}
775
776/**
777 * JobCatchSignal
778 *	Got a signal. Set global variables and hope that someone will
779 *	handle it.
780 */
781static void
782JobCatchSig(int signo)
783{
784
785	interrupted = signo;
786}
787
788/**
789 * JobPassSig --
790 *	Pass a signal on to all local jobs if
791 *	USE_PGRP is defined, then die ourselves.
792 *
793 * Side Effects:
794 *	We die by the same signal.
795 */
796static void
797JobPassSig(int signo)
798{
799	Job	*job;
800	sigset_t nmask, omask;
801	struct sigaction act;
802
803	sigemptyset(&nmask);
804	sigaddset(&nmask, signo);
805	sigprocmask(SIG_SETMASK, &nmask, &omask);
806
807	DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
808	TAILQ_FOREACH(job, &jobs, link) {
809		DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
810		    signo, (intmax_t)job->pid));
811		KILL(job->pid, signo);
812	}
813
814	/*
815	 * Deal with proper cleanup based on the signal received. We only run
816	 * the .INTERRUPT target if the signal was in fact an interrupt.
817	 * The other three termination signals are more of a "get out *now*"
818	 * command.
819	 */
820	if (signo == SIGINT) {
821		JobInterrupt(TRUE, signo);
822	} else if (signo == SIGHUP || signo == SIGTERM || signo == SIGQUIT) {
823		JobInterrupt(FALSE, signo);
824	}
825
826	/*
827	 * Leave gracefully if SIGQUIT, rather than core dumping.
828	 */
829	if (signo == SIGQUIT) {
830		signo = SIGINT;
831	}
832
833	/*
834	 * Send ourselves the signal now we've given the message to everyone
835	 * else. Note we block everything else possible while we're getting
836	 * the signal. This ensures that all our jobs get continued when we
837	 * wake up before we take any other signal.
838	 * XXX this comment seems wrong.
839	 */
840	act.sa_handler = SIG_DFL;
841	sigemptyset(&act.sa_mask);
842	act.sa_flags = 0;
843	sigaction(signo, &act, NULL);
844
845	DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
846	    ~0 & ~(1 << (signo - 1))));
847	signal(signo, SIG_DFL);
848
849	KILL(getpid(), signo);
850
851	signo = SIGCONT;
852	TAILQ_FOREACH(job, &jobs, link) {
853		DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
854		    signo, (intmax_t)job->pid));
855		KILL(job->pid, signo);
856	}
857
858	sigprocmask(SIG_SETMASK, &omask, NULL);
859	sigprocmask(SIG_SETMASK, &omask, NULL);
860	act.sa_handler = JobPassSig;
861	sigaction(signo, &act, NULL);
862}
863
864/**
865 * JobPrintCommand  --
866 *	Put out another command for the given job. If the command starts
867 *	with an @ or a - we process it specially. In the former case,
868 *	so long as the -s and -n flags weren't given to make, we stick
869 *	a shell-specific echoOff command in the script. In the latter,
870 *	we ignore errors for the entire job, unless the shell has error
871 *	control.
872 *	If the command is just "..." we take all future commands for this
873 *	job to be commands to be executed once the entire graph has been
874 *	made and return non-zero to signal that the end of the commands
875 *	was reached. These commands are later attached to the postCommands
876 *	node and executed by Job_Finish when all things are done.
877 *	This function is called from JobStart via LST_FOREACH.
878 *
879 * Results:
880 *	Always 0, unless the command was "..."
881 *
882 * Side Effects:
883 *	If the command begins with a '-' and the shell has no error control,
884 *	the JOB_IGNERR flag is set in the job descriptor.
885 *	If the command is "..." and we're not ignoring such things,
886 *	tailCmds is set to the successor node of the cmd.
887 *	numCommands is incremented if the command is actually printed.
888 */
889static int
890JobPrintCommand(char *cmd, Job *job)
891{
892	Boolean	noSpecials;	/* true if we shouldn't worry about
893				 * inserting special commands into
894				 * the input stream. */
895	Boolean	shutUp = FALSE;	/* true if we put a no echo command
896				 * into the command file */
897	Boolean	errOff = FALSE;	/* true if we turned error checking
898				 * off before printing the command
899				 * and need to turn it back on */
900	const char *cmdTemplate;/* Template to use when printing the command */
901	char	*cmdStart;	/* Start of expanded command */
902	LstNode	*cmdNode;	/* Node for replacing the command */
903
904	noSpecials = (noExecute && !(job->node->type & OP_MAKE));
905
906	if (strcmp(cmd, "...") == 0) {
907		job->node->type |= OP_SAVE_CMDS;
908		if ((job->flags & JOB_IGNDOTS) == 0) {
909			job->tailCmds =
910			    Lst_Succ(Lst_Member(&job->node->commands, cmd));
911			return (1);
912		}
913		return (0);
914	}
915
916#define	DBPRINTF(fmt, arg)			\
917	DEBUGF(JOB, (fmt, arg));		\
918	fprintf(job->cmdFILE, fmt, arg);	\
919	fflush(job->cmdFILE);
920
921	numCommands += 1;
922
923	/*
924	 * For debugging, we replace each command with the result of expanding
925	 * the variables in the command.
926	 */
927	cmdNode = Lst_Member(&job->node->commands, cmd);
928
929	cmd = Buf_Peel(Var_Subst(cmd, job->node, FALSE));
930	cmdStart = cmd;
931
932	Lst_Replace(cmdNode, cmdStart);
933
934	cmdTemplate = "%s\n";
935
936	/*
937	 * Check for leading @', -' or +'s to control echoing, error checking,
938	 * and execution on -n.
939	 */
940	while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
941		switch (*cmd) {
942
943		  case '@':
944			shutUp = DEBUG(LOUD) ? FALSE : TRUE;
945			break;
946
947		  case '-':
948			errOff = TRUE;
949			break;
950
951		  case '+':
952			if (noSpecials) {
953				/*
954				 * We're not actually exececuting anything...
955				 * but this one needs to be - use compat mode
956				 * just for it.
957				 */
958				Compat_RunCommand(cmd, job->node);
959				return (0);
960			}
961			break;
962		}
963		cmd++;
964	}
965
966	while (isspace((unsigned char)*cmd))
967		cmd++;
968
969	if (shutUp) {
970		if (!(job->flags & JOB_SILENT) && !noSpecials &&
971		    commandShell->hasEchoCtl) {
972			DBPRINTF("%s\n", commandShell->echoOff);
973		} else {
974			shutUp = FALSE;
975		}
976	}
977
978	if (errOff) {
979		if (!(job->flags & JOB_IGNERR) && !noSpecials) {
980			if (commandShell->hasErrCtl) {
981				/*
982				 * We don't want the error-control commands
983				 * showing up either, so we turn off echoing
984				 * while executing them. We could put another
985				 * field in the shell structure to tell
986				 * JobDoOutput to look for this string too,
987				 * but why make it any more complex than
988				 * it already is?
989				 */
990				if (!(job->flags & JOB_SILENT) && !shutUp &&
991				    commandShell->hasEchoCtl) {
992					DBPRINTF("%s\n", commandShell->echoOff);
993					DBPRINTF("%s\n", commandShell->ignErr);
994					DBPRINTF("%s\n", commandShell->echoOn);
995				} else {
996					DBPRINTF("%s\n", commandShell->ignErr);
997				}
998			} else if (commandShell->ignErr &&
999			    *commandShell->ignErr != '\0') {
1000				/*
1001				 * The shell has no error control, so we need to
1002				 * be weird to get it to ignore any errors from
1003				 * the command. If echoing is turned on, we turn
1004				 * it off and use the errCheck template to echo
1005				 * the command. Leave echoing off so the user
1006				 * doesn't see the weirdness we go through to
1007				 * ignore errors. Set cmdTemplate to use the
1008				 * weirdness instead of the simple "%s\n"
1009				 * template.
1010				 */
1011				if (!(job->flags & JOB_SILENT) && !shutUp &&
1012				    commandShell->hasEchoCtl) {
1013					DBPRINTF("%s\n", commandShell->echoOff);
1014					DBPRINTF(commandShell->errCheck, cmd);
1015					shutUp = TRUE;
1016				}
1017				cmdTemplate = commandShell->ignErr;
1018				/*
1019				 * The error ignoration (hee hee) is already
1020				 * taken care of by the ignErr template, so
1021				 * pretend error checking is still on.
1022				*/
1023				errOff = FALSE;
1024			} else {
1025				errOff = FALSE;
1026			}
1027		} else {
1028			errOff = FALSE;
1029		}
1030	}
1031
1032	DBPRINTF(cmdTemplate, cmd);
1033
1034	if (errOff) {
1035		/*
1036		 * If echoing is already off, there's no point in issuing the
1037		 * echoOff command. Otherwise we issue it and pretend it was on
1038		 * for the whole command...
1039		 */
1040		if (!shutUp && !(job->flags & JOB_SILENT) &&
1041		    commandShell->hasEchoCtl) {
1042			DBPRINTF("%s\n", commandShell->echoOff);
1043			shutUp = TRUE;
1044		}
1045		DBPRINTF("%s\n", commandShell->errCheck);
1046	}
1047	if (shutUp) {
1048		DBPRINTF("%s\n", commandShell->echoOn);
1049	}
1050	return (0);
1051}
1052
1053/**
1054 * JobClose --
1055 *	Called to close both input and output pipes when a job is finished.
1056 *
1057 * Side Effects:
1058 *	The file descriptors associated with the job are closed.
1059 */
1060static void
1061JobClose(Job *job)
1062{
1063
1064	if (usePipes) {
1065#if !defined(USE_KQUEUE)
1066		FD_CLR(job->inPipe, &outputs);
1067#endif
1068		if (job->outPipe != job->inPipe) {
1069			close(job->outPipe);
1070		}
1071		JobDoOutput(job, TRUE);
1072		close(job->inPipe);
1073	} else {
1074		close(job->outFd);
1075		JobDoOutput(job, TRUE);
1076	}
1077}
1078
1079/**
1080 * JobFinish  --
1081 *	Do final processing for the given job including updating
1082 *	parents and starting new jobs as available/necessary. Note
1083 *	that we pay no attention to the JOB_IGNERR flag here.
1084 *	This is because when we're called because of a noexecute flag
1085 *	or something, jstat.w_status is 0 and when called from
1086 *	Job_CatchChildren, the status is zeroed if it s/b ignored.
1087 *
1088 * Side Effects:
1089 *	Some nodes may be put on the toBeMade queue.
1090 *	Final commands for the job are placed on postCommands.
1091 *
1092 *	If we got an error and are aborting (aborting == ABORT_ERROR) and
1093 *	the job list is now empty, we are done for the day.
1094 *	If we recognized an error (errors !=0), we set the aborting flag
1095 *	to ABORT_ERROR so no more jobs will be started.
1096 */
1097static void
1098JobFinish(Job *job, int *status)
1099{
1100	Boolean	done;
1101	LstNode	*ln;
1102
1103	if (WIFEXITED(*status)) {
1104		int	job_status = WEXITSTATUS(*status);
1105
1106		JobClose(job);
1107		/*
1108		 * Deal with ignored errors in -B mode. We need to
1109		 * print a message telling of the ignored error as
1110		 * well as setting status.w_status to 0 so the next
1111		 * command gets run. To do this, we set done to be
1112		 * TRUE if in -B mode and the job exited non-zero.
1113		 */
1114		if (job_status == 0) {
1115			done = FALSE;
1116		} else {
1117			if (job->flags & JOB_IGNERR) {
1118				done = TRUE;
1119			} else {
1120				/*
1121				 * If it exited non-zero and either we're
1122				 * doing things our way or we're not ignoring
1123				 * errors, the job is finished. Similarly, if
1124				 * the shell died because of a signal the job
1125				 * is also finished. In these cases, finish
1126				 * out the job's output before printing the
1127				 * exit status...
1128				 */
1129				done = TRUE;
1130				if (job->cmdFILE != NULL &&
1131				    job->cmdFILE != stdout) {
1132					fclose(job->cmdFILE);
1133				}
1134
1135			}
1136		}
1137	} else if (WIFSIGNALED(*status)) {
1138		if (WTERMSIG(*status) == SIGCONT) {
1139			/*
1140			 * No need to close things down or anything.
1141			 */
1142			done = FALSE;
1143		} else {
1144			/*
1145			 * If it exited non-zero and either we're
1146			 * doing things our way or we're not ignoring
1147			 * errors, the job is finished. Similarly, if
1148			 * the shell died because of a signal the job
1149			 * is also finished. In these cases, finish
1150			 * out the job's output before printing the
1151			 * exit status...
1152			 */
1153			JobClose(job);
1154			if (job->cmdFILE != NULL &&
1155			    job->cmdFILE != stdout) {
1156				fclose(job->cmdFILE);
1157			}
1158			done = TRUE;
1159		}
1160	} else {
1161		/*
1162		 * No need to close things down or anything.
1163		 */
1164		done = FALSE;
1165	}
1166
1167	if (WIFEXITED(*status)) {
1168		if (done || DEBUG(JOB)) {
1169			FILE   *out;
1170
1171			if (compatMake &&
1172			    !usePipes &&
1173			    (job->flags & JOB_IGNERR)) {
1174				/*
1175				 * If output is going to a file and this job
1176				 * is ignoring errors, arrange to have the
1177				 * exit status sent to the output file as
1178				 * well.
1179				 */
1180				out = fdopen(job->outFd, "w");
1181				if (out == NULL)
1182					Punt("Cannot fdopen");
1183			} else {
1184				out = stdout;
1185			}
1186
1187			DEBUGF(JOB, ("Process %jd exited.\n",
1188			    (intmax_t)job->pid));
1189
1190			if (WEXITSTATUS(*status) == 0) {
1191				if (DEBUG(JOB)) {
1192					if (usePipes && job->node != lastNode) {
1193						MESSAGE(out, job->node);
1194						lastNode = job->node;
1195					}
1196					fprintf(out,
1197					    "*** Completed successfully\n");
1198				}
1199			} else {
1200				if (usePipes && job->node != lastNode) {
1201					MESSAGE(out, job->node);
1202					lastNode = job->node;
1203				}
1204				fprintf(out, "*** Error code %d%s\n",
1205					WEXITSTATUS(*status),
1206					(job->flags & JOB_IGNERR) ?
1207					"(ignored)" : "");
1208
1209				if (job->flags & JOB_IGNERR) {
1210					*status = 0;
1211				}
1212			}
1213
1214			fflush(out);
1215		}
1216	} else if (WIFSIGNALED(*status)) {
1217		if (done || DEBUG(JOB) || (WTERMSIG(*status) == SIGCONT)) {
1218			FILE   *out;
1219
1220			if (compatMake &&
1221			    !usePipes &&
1222			    (job->flags & JOB_IGNERR)) {
1223				/*
1224				 * If output is going to a file and this job
1225				 * is ignoring errors, arrange to have the
1226				 * exit status sent to the output file as
1227				 * well.
1228				 */
1229				out = fdopen(job->outFd, "w");
1230				if (out == NULL)
1231					Punt("Cannot fdopen");
1232			} else {
1233				out = stdout;
1234			}
1235
1236			if (WTERMSIG(*status) == SIGCONT) {
1237				/*
1238				 * If the beastie has continued, shift the
1239				 * Job from the stopped list to the running
1240				 * one (or re-stop it if concurrency is
1241				 * exceeded) and go and get another child.
1242				 */
1243				if (job->flags & (JOB_RESUME | JOB_RESTART)) {
1244					if (usePipes && job->node != lastNode) {
1245						MESSAGE(out, job->node);
1246						lastNode = job->node;
1247					}
1248					fprintf(out, "*** Continued\n");
1249				}
1250				if (!(job->flags & JOB_CONTINUING)) {
1251					DEBUGF(JOB, ("Warning: process %jd was not "
1252						     "continuing.\n", (intmax_t) job->pid));
1253#ifdef notdef
1254					/*
1255					 * We don't really want to restart a
1256					 * job from scratch just because it
1257					 * continued, especially not without
1258					 * killing the continuing process!
1259					 * That's why this is ifdef'ed out.
1260					 * FD - 9/17/90
1261					 */
1262					JobRestart(job);
1263#endif
1264				}
1265				job->flags &= ~JOB_CONTINUING;
1266				TAILQ_INSERT_TAIL(&jobs, job, link);
1267				nJobs += 1;
1268				DEBUGF(JOB, ("Process %jd is continuing locally.\n",
1269					     (intmax_t) job->pid));
1270				if (nJobs == maxJobs) {
1271					jobFull = TRUE;
1272					DEBUGF(JOB, ("Job queue is full.\n"));
1273				}
1274				fflush(out);
1275				return;
1276
1277			} else {
1278				if (usePipes && job->node != lastNode) {
1279					MESSAGE(out, job->node);
1280					lastNode = job->node;
1281				}
1282				fprintf(out,
1283				    "*** Signal %d\n", WTERMSIG(*status));
1284				fflush(out);
1285			}
1286		}
1287	} else {
1288		/* STOPPED */
1289		FILE   *out;
1290
1291		if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
1292			/*
1293			 * If output is going to a file and this job
1294			 * is ignoring errors, arrange to have the
1295			 * exit status sent to the output file as
1296			 * well.
1297			 */
1298			out = fdopen(job->outFd, "w");
1299			if (out == NULL)
1300				Punt("Cannot fdopen");
1301		} else {
1302			out = stdout;
1303		}
1304
1305		DEBUGF(JOB, ("Process %jd stopped.\n", (intmax_t) job->pid));
1306		if (usePipes && job->node != lastNode) {
1307			MESSAGE(out, job->node);
1308			lastNode = job->node;
1309		}
1310		fprintf(out, "*** Stopped -- signal %d\n", WSTOPSIG(*status));
1311		job->flags |= JOB_RESUME;
1312		TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1313		fflush(out);
1314		return;
1315	}
1316
1317	/*
1318	 * Now handle the -B-mode stuff. If the beast still isn't finished,
1319	 * try and restart the job on the next command. If JobStart says it's
1320	 * ok, it's ok. If there's an error, this puppy is done.
1321	 */
1322	if (compatMake && WIFEXITED(*status) &&
1323	    Lst_Succ(job->node->compat_command) != NULL) {
1324		switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
1325		  case JOB_RUNNING:
1326			done = FALSE;
1327			break;
1328		  case JOB_ERROR:
1329			done = TRUE;
1330			W_SETEXITSTATUS(status, 1);
1331			break;
1332		  case JOB_FINISHED:
1333			/*
1334			 * If we got back a JOB_FINISHED code, JobStart has
1335			 * already called Make_Update and freed the job
1336			 * descriptor. We set done to false here to avoid fake
1337			 * cycles and double frees. JobStart needs to do the
1338			 * update so we can proceed up the graph when given
1339			 * the -n flag..
1340			 */
1341			done = FALSE;
1342			break;
1343		  default:
1344			break;
1345		}
1346	} else {
1347		done = TRUE;
1348	}
1349
1350	if (done && aborting != ABORT_ERROR &&
1351	    aborting != ABORT_INTERRUPT && *status == 0) {
1352		/*
1353		 * As long as we aren't aborting and the job didn't return a
1354		 * non-zero status that we shouldn't ignore, we call
1355		 * Make_Update to update the parents. In addition, any saved
1356		 * commands for the node are placed on the .END target.
1357		 */
1358		for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
1359			Lst_AtEnd(&postCommands->commands,
1360			    Buf_Peel(
1361				Var_Subst(Lst_Datum(ln), job->node, FALSE)));
1362		}
1363
1364		job->node->made = MADE;
1365		Make_Update(job->node);
1366		free(job);
1367
1368	} else if (*status != 0) {
1369		errors += 1;
1370		free(job);
1371	}
1372
1373	JobRestartJobs();
1374
1375	/*
1376	 * Set aborting if any error.
1377	 */
1378	if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
1379		/*
1380		 * If we found any errors in this batch of children and the -k
1381		 * flag wasn't given, we set the aborting flag so no more jobs
1382		 * get started.
1383		 */
1384		aborting = ABORT_ERROR;
1385	}
1386
1387	if (aborting == ABORT_ERROR && Job_Empty()) {
1388		/*
1389		 * If we are aborting and the job table is now empty, we finish.
1390		 */
1391		Finish(errors);
1392	}
1393}
1394
1395/**
1396 * Job_Touch
1397 *	Touch the given target. Called by JobStart when the -t flag was
1398 *	given.  Prints messages unless told to be silent.
1399 *
1400 * Side Effects:
1401 *	The data modification of the file is changed. In addition, if the
1402 *	file did not exist, it is created.
1403 */
1404void
1405Job_Touch(GNode *gn, Boolean silent)
1406{
1407	int	streamID;	/* ID of stream opened to do the touch */
1408	struct utimbuf times;	/* Times for utime() call */
1409
1410	if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
1411		/*
1412		 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
1413		 * targets and, as such, shouldn't really be created.
1414		 */
1415		return;
1416	}
1417
1418	if (!silent) {
1419		fprintf(stdout, "touch %s\n", gn->name);
1420		fflush(stdout);
1421	}
1422
1423	if (noExecute) {
1424		return;
1425	}
1426
1427	if (gn->type & OP_ARCHV) {
1428		Arch_Touch(gn);
1429	} else if (gn->type & OP_LIB) {
1430		Arch_TouchLib(gn);
1431	} else {
1432		char	*file = gn->path ? gn->path : gn->name;
1433
1434		times.actime = times.modtime = now;
1435		if (utime(file, &times) < 0) {
1436			streamID = open(file, O_RDWR | O_CREAT, 0666);
1437
1438			if (streamID >= 0) {
1439				char	c;
1440
1441				/*
1442				 * Read and write a byte to the file to change
1443				 * the modification time, then close the file.
1444				 */
1445				if (read(streamID, &c, 1) == 1) {
1446					lseek(streamID, (off_t)0, SEEK_SET);
1447					write(streamID, &c, 1);
1448				}
1449
1450				close(streamID);
1451			} else {
1452				fprintf(stdout, "*** couldn't touch %s: %s",
1453				    file, strerror(errno));
1454				fflush(stdout);
1455			}
1456		}
1457	}
1458}
1459
1460/**
1461 * Job_CheckCommands
1462 *	Make sure the given node has all the commands it needs.
1463 *
1464 * Results:
1465 *	TRUE if the commands list is/was ok.
1466 *
1467 * Side Effects:
1468 *	The node will have commands from the .DEFAULT rule added to it
1469 *	if it needs them.
1470 */
1471Boolean
1472Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1473{
1474
1475	if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
1476	    (gn->type & OP_LIB) == 0) {
1477		/*
1478		 * No commands. Look for .DEFAULT rule from which we might infer
1479		 * commands.
1480		 */
1481		if (DEFAULT != NULL && !Lst_IsEmpty(&DEFAULT->commands)) {
1482			char *p1;
1483			/*
1484			 * Make only looks for a .DEFAULT if the node was
1485			 * never the target of an operator, so that's what we
1486			 * do too. If a .DEFAULT was given, we substitute its
1487			 * commands for gn's commands and set the IMPSRC
1488			 * variable to be the target's name The DEFAULT node
1489			 * acts like a transformation rule, in that gn also
1490			 * inherits any attributes or sources attached to
1491			 * .DEFAULT itself.
1492			 */
1493			Make_HandleUse(DEFAULT, gn);
1494			Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn);
1495			free(p1);
1496
1497		} else if (Dir_MTime(gn) == 0) {
1498			/*
1499			 * The node wasn't the target of an operator we have
1500			 * no .DEFAULT rule to go on and the target doesn't
1501			 * already exist. There's nothing more we can do for
1502			 * this branch. If the -k flag wasn't given, we stop
1503			 * in our tracks, otherwise we just don't update
1504			 * this node's parents so they never get examined.
1505			 */
1506			static const char msg[] =
1507			    "make: don't know how to make";
1508
1509			if (gn->type & OP_OPTIONAL) {
1510				fprintf(stdout, "%s %s(ignored)\n",
1511				    msg, gn->name);
1512				fflush(stdout);
1513			} else if (keepgoing) {
1514				fprintf(stdout, "%s %s(continuing)\n",
1515				    msg, gn->name);
1516				fflush(stdout);
1517				return (FALSE);
1518			} else {
1519#if OLD_JOKE
1520				if (strcmp(gn->name,"love") == 0)
1521					(*abortProc)("Not war.");
1522				else
1523#endif
1524					(*abortProc)("%s %s. Stop",
1525					    msg, gn->name);
1526				return (FALSE);
1527			}
1528		}
1529	}
1530	return (TRUE);
1531}
1532
1533/**
1534 * JobExec
1535 *	Execute the shell for the given job. Called from JobStart and
1536 *	JobRestart.
1537 *
1538 * Side Effects:
1539 *	A shell is executed, outputs is altered and the Job structure added
1540 *	to the job table.
1541 */
1542static void
1543JobExec(Job *job, char **argv)
1544{
1545	ProcStuff	ps;
1546
1547	if (DEBUG(JOB)) {
1548		int	  i;
1549
1550		DEBUGF(JOB, ("Running %s\n", job->node->name));
1551		DEBUGF(JOB, ("\tCommand: "));
1552		for (i = 0; argv[i] != NULL; i++) {
1553			DEBUGF(JOB, ("%s ", argv[i]));
1554		}
1555		DEBUGF(JOB, ("\n"));
1556	}
1557
1558	/*
1559	 * Some jobs produce no output and it's disconcerting to have
1560	 * no feedback of their running (since they produce no output, the
1561	 * banner with their name in it never appears). This is an attempt to
1562	 * provide that feedback, even if nothing follows it.
1563	 */
1564	if (lastNode != job->node && (job->flags & JOB_FIRST) &&
1565	    !(job->flags & JOB_SILENT)) {
1566		MESSAGE(stdout, job->node);
1567		lastNode = job->node;
1568	}
1569
1570	ps.in = FILENO(job->cmdFILE);
1571	if (usePipes) {
1572		/*
1573		 * Set up the child's output to be routed through the
1574		 * pipe we've created for it.
1575		 */
1576		ps.out = job->outPipe;
1577	} else {
1578		/*
1579		 * We're capturing output in a file, so we duplicate
1580		 * the descriptor to the temporary file into the
1581		 * standard output.
1582		 */
1583		ps.out = job->outFd;
1584	}
1585	ps.err = STDERR_FILENO;
1586
1587	ps.merge_errors = 1;
1588	ps.pgroup = 1;
1589	ps.searchpath = 0;
1590
1591	ps.argv = argv;
1592	ps.argv_free = 0;
1593
1594	/*
1595	 * Fork.  Warning since we are doing vfork() instead of fork(),
1596	 * do not allocate memory in the child process!
1597	 */
1598	if ((ps.child_pid = vfork()) == -1) {
1599		Punt("Cannot fork");
1600
1601
1602	} else if (ps.child_pid == 0) {
1603		/*
1604		 * Child
1605		 */
1606		if (fifoFd >= 0)
1607			close(fifoFd);
1608
1609		ProcExec(&ps);
1610		/* NOTREACHED */
1611	}
1612
1613	/*
1614	 * Parent
1615	 */
1616	job->pid = ps.child_pid;
1617
1618	if (usePipes && (job->flags & JOB_FIRST)) {
1619		/*
1620		 * The first time a job is run for a node, we set the
1621		 * current position in the buffer to the beginning and
1622		 * mark another stream to watch in the outputs mask.
1623		 */
1624#ifdef USE_KQUEUE
1625		struct kevent	kev[2];
1626#endif
1627		job->curPos = 0;
1628
1629#if defined(USE_KQUEUE)
1630		EV_SET(&kev[0], job->inPipe, EVFILT_READ, EV_ADD, 0, 0, job);
1631		EV_SET(&kev[1], job->pid, EVFILT_PROC,
1632		    EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
1633		if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1634			/*
1635			 * kevent() will fail if the job is already
1636			 * finished
1637			 */
1638			if (errno != EINTR && errno != EBADF && errno != ESRCH)
1639				Punt("kevent: %s", strerror(errno));
1640		}
1641#else
1642		FD_SET(job->inPipe, &outputs);
1643#endif /* USE_KQUEUE */
1644	}
1645
1646	if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1647		fclose(job->cmdFILE);
1648		job->cmdFILE = NULL;
1649	}
1650
1651	/*
1652	 * Now the job is actually running, add it to the table.
1653	 */
1654	nJobs += 1;
1655	TAILQ_INSERT_TAIL(&jobs, job, link);
1656	if (nJobs == maxJobs) {
1657		jobFull = TRUE;
1658	}
1659}
1660
1661/**
1662 * JobMakeArgv
1663 *	Create the argv needed to execute the shell for a given job.
1664 */
1665static void
1666JobMakeArgv(Job *job, char **argv)
1667{
1668	int		argc;
1669	static char	args[10];	/* For merged arguments */
1670
1671	argv[0] = commandShell->name;
1672	argc = 1;
1673
1674	if ((commandShell->exit && *commandShell->exit != '-') ||
1675	    (commandShell->echo && *commandShell->echo != '-')) {
1676		/*
1677		 * At least one of the flags doesn't have a minus before it, so
1678		 * merge them together. Have to do this because the *(&(@*#*&#$#
1679		 * Bourne shell thinks its second argument is a file to source.
1680		 * Grrrr. Note the ten-character limitation on the combined
1681		 * arguments.
1682		 */
1683		sprintf(args, "-%s%s", (job->flags & JOB_IGNERR) ? "" :
1684		    commandShell->exit ? commandShell->exit : "",
1685		    (job->flags & JOB_SILENT) ? "" :
1686		    commandShell->echo ? commandShell->echo : "");
1687
1688		if (args[1]) {
1689			argv[argc] = args;
1690			argc++;
1691		}
1692	} else {
1693		if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1694			argv[argc] = commandShell->exit;
1695			argc++;
1696		}
1697		if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1698			argv[argc] = commandShell->echo;
1699			argc++;
1700		}
1701	}
1702	argv[argc] = NULL;
1703}
1704
1705/**
1706 * JobRestart
1707 *	Restart a job that stopped for some reason. The job must be neither
1708 *	on the jobs nor on the stoppedJobs list.
1709 *
1710 * Side Effects:
1711 *	jobFull will be set if the job couldn't be run.
1712 */
1713static void
1714JobRestart(Job *job)
1715{
1716
1717	if (job->flags & JOB_RESTART) {
1718		/*
1719		 * Set up the control arguments to the shell. This is based on
1720		 * the flags set earlier for this job. If the JOB_IGNERR flag
1721		 * is clear, the 'exit' flag of the commandShell is used to
1722		 * cause it to exit upon receiving an error. If the JOB_SILENT
1723		 * flag is clear, the 'echo' flag of the commandShell is used
1724		 * to get it to start echoing as soon as it starts
1725		 * processing commands.
1726		 */
1727		char	*argv[4];
1728
1729		JobMakeArgv(job, argv);
1730
1731		DEBUGF(JOB, ("Restarting %s...", job->node->name));
1732		if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL)) {
1733			/*
1734			 * Not allowed to run -- put it back on the hold
1735			 * queue and mark the table full
1736			 */
1737			DEBUGF(JOB, ("holding\n"));
1738			TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1739			jobFull = TRUE;
1740			DEBUGF(JOB, ("Job queue is full.\n"));
1741			return;
1742		} else {
1743			/*
1744			 * Job may be run locally.
1745			 */
1746			DEBUGF(JOB, ("running locally\n"));
1747		}
1748		JobExec(job, argv);
1749
1750	} else {
1751		/*
1752		 * The job has stopped and needs to be restarted.
1753		 * Why it stopped, we don't know...
1754		 */
1755		DEBUGF(JOB, ("Resuming %s...", job->node->name));
1756		if ((nJobs < maxJobs || ((job->flags & JOB_SPECIAL) &&
1757		    maxJobs == 0)) && nJobs != maxJobs) {
1758			/*
1759			 * If we haven't reached the concurrency limit already
1760			 * (or the job must be run and maxJobs is 0), it's ok
1761			 * to resume it.
1762			 */
1763			Boolean error;
1764			int status;
1765
1766			error = (KILL(job->pid, SIGCONT) != 0);
1767
1768			if (!error) {
1769				/*
1770				 * Make sure the user knows we've continued
1771				 * the beast and actually put the thing in the
1772				 * job table.
1773				 */
1774				job->flags |= JOB_CONTINUING;
1775				status = 0;
1776				W_SETTERMSIG(&status, SIGCONT);
1777				JobFinish(job, &status);
1778
1779				job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1780				DEBUGF(JOB, ("done\n"));
1781			} else {
1782				Error("couldn't resume %s: %s",
1783				job->node->name, strerror(errno));
1784				status = 0;
1785				W_SETEXITSTATUS(&status, 1);
1786				JobFinish(job, &status);
1787			}
1788		} else {
1789			/*
1790			* Job cannot be restarted. Mark the table as full and
1791			* place the job back on the list of stopped jobs.
1792			*/
1793			DEBUGF(JOB, ("table full\n"));
1794			TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1795			jobFull = TRUE;
1796			DEBUGF(JOB, ("Job queue is full.\n"));
1797		}
1798	}
1799}
1800
1801/**
1802 * JobStart
1803 *	Start a target-creation process going for the target described
1804 *	by the graph node gn.
1805 *
1806 * Results:
1807 *	JOB_ERROR if there was an error in the commands, JOB_FINISHED
1808 *	if there isn't actually anything left to do for the job and
1809 *	JOB_RUNNING if the job has been started.
1810 *
1811 * Side Effects:
1812 *	A new Job node is created and added to the list of running
1813 *	jobs. PMake is forked and a child shell created.
1814 */
1815static int
1816JobStart(GNode *gn, int flags, Job *previous)
1817{
1818	Job	*job;		/* new job descriptor */
1819	char	*argv[4];	/* Argument vector to shell */
1820	Boolean	cmdsOK;		/* true if the nodes commands were all right */
1821	Boolean	noExec;		/* Set true if we decide not to run the job */
1822	int	tfd;		/* File descriptor for temp file */
1823	LstNode	*ln;
1824	char	tfile[sizeof(TMPPAT)];
1825
1826	if (interrupted) {
1827		JobPassSig(interrupted);
1828		return (JOB_ERROR);
1829	}
1830	if (previous != NULL) {
1831		previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1832		job = previous;
1833	} else {
1834		job = emalloc(sizeof(Job));
1835		flags |= JOB_FIRST;
1836	}
1837
1838	job->node = gn;
1839	job->tailCmds = NULL;
1840
1841	/*
1842	 * Set the initial value of the flags for this job based on the global
1843	 * ones and the node's attributes... Any flags supplied by the caller
1844	 * are also added to the field.
1845	 */
1846	job->flags = 0;
1847	if (Targ_Ignore(gn)) {
1848		job->flags |= JOB_IGNERR;
1849	}
1850	if (Targ_Silent(gn)) {
1851		job->flags |= JOB_SILENT;
1852	}
1853	job->flags |= flags;
1854
1855	/*
1856	 * Check the commands now so any attributes from .DEFAULT have a chance
1857	 * to migrate to the node.
1858	 */
1859	if (!compatMake && (job->flags & JOB_FIRST)) {
1860		cmdsOK = Job_CheckCommands(gn, Error);
1861	} else {
1862		cmdsOK = TRUE;
1863	}
1864
1865	/*
1866	 * If the -n flag wasn't given, we open up OUR (not the child's)
1867	 * temporary file to stuff commands in it. The thing is rd/wr so we
1868	 * don't need to reopen it to feed it to the shell. If the -n flag
1869	 * *was* given, we just set the file to be stdout. Cute, huh?
1870	 */
1871	if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1872		/*
1873		 * We're serious here, but if the commands were bogus, we're
1874		 * also dead...
1875		 */
1876		if (!cmdsOK) {
1877			DieHorribly();
1878		}
1879
1880		strcpy(tfile, TMPPAT);
1881		if ((tfd = mkstemp(tfile)) == -1)
1882			Punt("Cannot create temp file: %s", strerror(errno));
1883		job->cmdFILE = fdopen(tfd, "w+");
1884		eunlink(tfile);
1885		if (job->cmdFILE == NULL) {
1886			close(tfd);
1887			Punt("Could not open %s", tfile);
1888		}
1889		fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1890		/*
1891		 * Send the commands to the command file, flush all its
1892		 * buffers then rewind and remove the thing.
1893		 */
1894		noExec = FALSE;
1895
1896		/*
1897		 * Used to be backwards; replace when start doing multiple
1898		 * commands per shell.
1899		 */
1900		if (compatMake) {
1901			/*
1902			 * Be compatible: If this is the first time for this
1903			 * node, verify its commands are ok and open the
1904			 * commands list for sequential access by later
1905			 * invocations of JobStart. Once that is done, we take
1906			 * the next command off the list and print it to the
1907			 * command file. If the command was an ellipsis, note
1908			 * that there's nothing more to execute.
1909			 */
1910			if (job->flags & JOB_FIRST)
1911				gn->compat_command = Lst_First(&gn->commands);
1912			else
1913				gn->compat_command =
1914				    Lst_Succ(gn->compat_command);
1915
1916			if (gn->compat_command == NULL ||
1917			    JobPrintCommand(Lst_Datum(gn->compat_command), job))
1918				noExec = TRUE;
1919
1920			if (noExec && !(job->flags & JOB_FIRST)) {
1921				/*
1922				 * If we're not going to execute anything, the
1923				 * job is done and we need to close down the
1924				 * various file descriptors we've opened for
1925				 * output, then call JobDoOutput to catch the
1926				 * final characters or send the file to the
1927				 * screen... Note that the i/o streams are only
1928				 * open if this isn't the first job. Note also
1929				 * that this could not be done in
1930				 * Job_CatchChildren b/c it wasn't clear if
1931				 * there were more commands to execute or not...
1932				 */
1933				JobClose(job);
1934			}
1935		} else {
1936			/*
1937			 * We can do all the commands at once. hooray for sanity
1938			 */
1939			numCommands = 0;
1940			LST_FOREACH(ln, &gn->commands) {
1941				if (JobPrintCommand(Lst_Datum(ln), job))
1942					break;
1943			}
1944
1945			/*
1946			 * If we didn't print out any commands to the shell
1947			 * script, there's not much point in executing the
1948			 * shell, is there?
1949			 */
1950			if (numCommands == 0) {
1951				noExec = TRUE;
1952			}
1953		}
1954
1955	} else if (noExecute) {
1956		/*
1957		 * Not executing anything -- just print all the commands to
1958		 * stdout in one fell swoop. This will still set up
1959		 * job->tailCmds correctly.
1960		 */
1961		if (lastNode != gn) {
1962			MESSAGE(stdout, gn);
1963			lastNode = gn;
1964		}
1965		job->cmdFILE = stdout;
1966
1967		/*
1968		 * Only print the commands if they're ok, but don't die if
1969		 * they're not -- just let the user know they're bad and keep
1970		 * going. It doesn't do any harm in this case and may do
1971		 * some good.
1972		 */
1973		if (cmdsOK) {
1974			LST_FOREACH(ln, &gn->commands) {
1975				if (JobPrintCommand(Lst_Datum(ln), job))
1976					break;
1977			}
1978		}
1979		/*
1980		* Don't execute the shell, thank you.
1981		*/
1982		noExec = TRUE;
1983
1984	} else {
1985		/*
1986		 * Just touch the target and note that no shell should be
1987		 * executed. Set cmdFILE to stdout to make life easier. Check
1988		 * the commands, too, but don't die if they're no good -- it
1989		 * does no harm to keep working up the graph.
1990		 */
1991		job->cmdFILE = stdout;
1992		Job_Touch(gn, job->flags & JOB_SILENT);
1993		noExec = TRUE;
1994	}
1995
1996	/*
1997	 * If we're not supposed to execute a shell, don't.
1998	 */
1999	if (noExec) {
2000		/*
2001		 * Unlink and close the command file if we opened one
2002		 */
2003		if (job->cmdFILE != stdout) {
2004			if (job->cmdFILE != NULL)
2005				fclose(job->cmdFILE);
2006		} else {
2007			fflush(stdout);
2008		}
2009
2010		/*
2011		 * We only want to work our way up the graph if we aren't here
2012		 * because the commands for the job were no good.
2013		*/
2014		if (cmdsOK) {
2015			if (aborting == 0) {
2016				for (ln = job->tailCmds; ln != NULL;
2017				    ln = LST_NEXT(ln)) {
2018					Lst_AtEnd(&postCommands->commands,
2019					    Buf_Peel(Var_Subst(Lst_Datum(ln),
2020					    job->node, FALSE)));
2021				}
2022				job->node->made = MADE;
2023				Make_Update(job->node);
2024			}
2025			free(job);
2026			return(JOB_FINISHED);
2027		} else {
2028			free(job);
2029			return(JOB_ERROR);
2030		}
2031	} else {
2032		fflush(job->cmdFILE);
2033	}
2034
2035	/*
2036	 * Set up the control arguments to the shell. This is based on the flags
2037	 * set earlier for this job.
2038	 */
2039	JobMakeArgv(job, argv);
2040
2041	/*
2042	 * If we're using pipes to catch output, create the pipe by which we'll
2043	 * get the shell's output. If we're using files, print out that we're
2044	 * starting a job and then set up its temporary-file name.
2045	 */
2046	if (!compatMake || (job->flags & JOB_FIRST)) {
2047		if (usePipes) {
2048			int fd[2];
2049
2050			if (pipe(fd) == -1)
2051				Punt("Cannot create pipe: %s", strerror(errno));
2052			job->inPipe = fd[0];
2053			job->outPipe = fd[1];
2054			fcntl(job->inPipe, F_SETFD, 1);
2055			fcntl(job->outPipe, F_SETFD, 1);
2056		} else {
2057			fprintf(stdout, "Remaking `%s'\n", gn->name);
2058			fflush(stdout);
2059			strcpy(job->outFile, TMPPAT);
2060			if ((job->outFd = mkstemp(job->outFile)) == -1)
2061				Punt("cannot create temp file: %s",
2062				    strerror(errno));
2063			fcntl(job->outFd, F_SETFD, 1);
2064		}
2065	}
2066
2067	if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL) && maxJobs != 0) {
2068		/*
2069		 * We've hit the limit of concurrency, so put the job on hold
2070		 * until some other job finishes. Note that the special jobs
2071		 * (.BEGIN, .INTERRUPT and .END) may be run even when the
2072		 * limit has been reached (e.g. when maxJobs == 0).
2073		 */
2074		jobFull = TRUE;
2075
2076		DEBUGF(JOB, ("Can only run job locally.\n"));
2077		job->flags |= JOB_RESTART;
2078		TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
2079	} else {
2080		if (nJobs >= maxJobs) {
2081			/*
2082			 * If we're running this job as a special case
2083			 * (see above), at least say the table is full.
2084			 */
2085			jobFull = TRUE;
2086			DEBUGF(JOB, ("Local job queue is full.\n"));
2087		}
2088		JobExec(job, argv);
2089	}
2090	return (JOB_RUNNING);
2091}
2092
2093static char *
2094JobOutput(Job *job, char *cp, char *endp, int msg)
2095{
2096	char *ecp;
2097
2098	if (commandShell->noPrint) {
2099		ecp = strstr(cp, commandShell->noPrint);
2100		while (ecp != NULL) {
2101			if (cp != ecp) {
2102				*ecp = '\0';
2103				if (msg && job->node != lastNode) {
2104					MESSAGE(stdout, job->node);
2105					lastNode = job->node;
2106				}
2107				/*
2108				 * The only way there wouldn't be a newline
2109				 * after this line is if it were the last in
2110				 * the buffer. However, since the non-printable
2111				 * comes after it, there must be a newline, so
2112				 * we don't print one.
2113				 */
2114				fprintf(stdout, "%s", cp);
2115				fflush(stdout);
2116			}
2117			cp = ecp + strlen(commandShell->noPrint);
2118			if (cp != endp) {
2119				/*
2120				 * Still more to print, look again after
2121				 * skipping the whitespace following the
2122				 * non-printable command....
2123				 */
2124				cp++;
2125				while (*cp == ' ' || *cp == '\t' ||
2126				    *cp == '\n') {
2127					cp++;
2128				}
2129				ecp = strstr(cp, commandShell->noPrint);
2130			} else {
2131				return (cp);
2132			}
2133		}
2134	}
2135	return (cp);
2136}
2137
2138/**
2139 * JobDoOutput
2140 *	This function is called at different times depending on
2141 *	whether the user has specified that output is to be collected
2142 *	via pipes or temporary files. In the former case, we are called
2143 *	whenever there is something to read on the pipe. We collect more
2144 *	output from the given job and store it in the job's outBuf. If
2145 *	this makes up a line, we print it tagged by the job's identifier,
2146 *	as necessary.
2147 *	If output has been collected in a temporary file, we open the
2148 *	file and read it line by line, transfering it to our own
2149 *	output channel until the file is empty. At which point we
2150 *	remove the temporary file.
2151 *	In both cases, however, we keep our figurative eye out for the
2152 *	'noPrint' line for the shell from which the output came. If
2153 *	we recognize a line, we don't print it. If the command is not
2154 *	alone on the line (the character after it is not \0 or \n), we
2155 *	do print whatever follows it.
2156 *
2157 * Side Effects:
2158 *	curPos may be shifted as may the contents of outBuf.
2159 */
2160static void
2161JobDoOutput(Job *job, Boolean finish)
2162{
2163	Boolean	gotNL = FALSE;	/* true if got a newline */
2164	Boolean	fbuf;		/* true if our buffer filled up */
2165	int	nr;		/* number of bytes read */
2166	int	i;		/* auxiliary index into outBuf */
2167	int	max;		/* limit for i (end of current data) */
2168	int	nRead;		/* (Temporary) number of bytes read */
2169	FILE	*oFILE;		/* Stream pointer to shell's output file */
2170	char	inLine[132];
2171
2172	if (usePipes) {
2173		/*
2174		 * Read as many bytes as will fit in the buffer.
2175		 */
2176  end_loop:
2177		gotNL = FALSE;
2178		fbuf = FALSE;
2179
2180		nRead = read(job->inPipe, &job->outBuf[job->curPos],
2181		    JOB_BUFSIZE - job->curPos);
2182		/*
2183		 * Check for interrupt here too, because the above read may
2184		 * block when the child process is stopped. In this case the
2185		 * interrupt will unblock it (we don't use SA_RESTART).
2186		 */
2187		if (interrupted)
2188			JobPassSig(interrupted);
2189
2190		if (nRead < 0) {
2191			DEBUGF(JOB, ("JobDoOutput(piperead)"));
2192			nr = 0;
2193		} else {
2194			nr = nRead;
2195		}
2196
2197		/*
2198		 * If we hit the end-of-file (the job is dead), we must flush
2199		 * its remaining output, so pretend we read a newline if
2200		 * there's any output remaining in the buffer.
2201		 * Also clear the 'finish' flag so we stop looping.
2202		 */
2203		if (nr == 0 && job->curPos != 0) {
2204			job->outBuf[job->curPos] = '\n';
2205			nr = 1;
2206			finish = FALSE;
2207		} else if (nr == 0) {
2208			finish = FALSE;
2209		}
2210
2211		/*
2212		 * Look for the last newline in the bytes we just got. If there
2213		 * is one, break out of the loop with 'i' as its index and
2214		 * gotNL set TRUE.
2215		*/
2216		max = job->curPos + nr;
2217		for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
2218			if (job->outBuf[i] == '\n') {
2219				gotNL = TRUE;
2220				break;
2221			} else if (job->outBuf[i] == '\0') {
2222				/*
2223				 * Why?
2224				 */
2225				job->outBuf[i] = ' ';
2226			}
2227		}
2228
2229		if (!gotNL) {
2230			job->curPos += nr;
2231			if (job->curPos == JOB_BUFSIZE) {
2232				/*
2233				 * If we've run out of buffer space, we have
2234				 * no choice but to print the stuff. sigh.
2235				 */
2236				fbuf = TRUE;
2237				i = job->curPos;
2238			}
2239		}
2240		if (gotNL || fbuf) {
2241			/*
2242			 * Need to send the output to the screen. Null terminate
2243			 * it first, overwriting the newline character if there
2244			 * was one. So long as the line isn't one we should
2245			 * filter (according to the shell description), we print
2246			 * the line, preceded by a target banner if this target
2247			 * isn't the same as the one for which we last printed
2248			 * something. The rest of the data in the buffer are
2249			 * then shifted down to the start of the buffer and
2250			 * curPos is set accordingly.
2251			 */
2252			job->outBuf[i] = '\0';
2253			if (i >= job->curPos) {
2254				char *cp;
2255
2256				cp = JobOutput(job, job->outBuf,
2257				    &job->outBuf[i], FALSE);
2258
2259				/*
2260				 * There's still more in that buffer. This time,
2261				 * though, we know there's no newline at the
2262				 * end, so we add one of our own free will.
2263				 */
2264				if (*cp != '\0') {
2265					if (job->node != lastNode) {
2266						MESSAGE(stdout, job->node);
2267						lastNode = job->node;
2268					}
2269					fprintf(stdout, "%s%s", cp,
2270					    gotNL ? "\n" : "");
2271					fflush(stdout);
2272				}
2273			}
2274			if (i < max - 1) {
2275				/* shift the remaining characters down */
2276				memcpy(job->outBuf, &job->outBuf[i + 1],
2277				    max - (i + 1));
2278				job->curPos = max - (i + 1);
2279
2280			} else {
2281				/*
2282				 * We have written everything out, so we just
2283				 * start over from the start of the buffer.
2284				 * No copying. No nothing.
2285				 */
2286				job->curPos = 0;
2287			}
2288		}
2289		if (finish) {
2290			/*
2291			 * If the finish flag is true, we must loop until we hit
2292			 * end-of-file on the pipe. This is guaranteed to happen
2293			 * eventually since the other end of the pipe is now
2294			 * closed (we closed it explicitly and the child has
2295			 * exited). When we do get an EOF, finish will be set
2296			 * FALSE and we'll fall through and out.
2297			 */
2298			goto end_loop;
2299		}
2300
2301	} else {
2302		/*
2303		 * We've been called to retrieve the output of the job from the
2304		 * temporary file where it's been squirreled away. This consists
2305		 * of opening the file, reading the output line by line, being
2306		 * sure not to print the noPrint line for the shell we used,
2307		 * then close and remove the temporary file. Very simple.
2308		 *
2309		 * Change to read in blocks and do FindSubString type things
2310		 * as for pipes? That would allow for "@echo -n..."
2311		 */
2312		oFILE = fopen(job->outFile, "r");
2313		if (oFILE != NULL) {
2314			fprintf(stdout, "Results of making %s:\n",
2315			    job->node->name);
2316			fflush(stdout);
2317
2318			while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2319				char	*cp, *endp, *oendp;
2320
2321				cp = inLine;
2322				oendp = endp = inLine + strlen(inLine);
2323				if (endp[-1] == '\n') {
2324					*--endp = '\0';
2325				}
2326				cp = JobOutput(job, inLine, endp, FALSE);
2327
2328				/*
2329				 * There's still more in that buffer. This time,
2330				 * though, we know there's no newline at the
2331				 * end, so we add one of our own free will.
2332				 */
2333				fprintf(stdout, "%s", cp);
2334				fflush(stdout);
2335				if (endp != oendp) {
2336					fprintf(stdout, "\n");
2337					fflush(stdout);
2338				}
2339			}
2340			fclose(oFILE);
2341			eunlink(job->outFile);
2342		}
2343	}
2344}
2345
2346/**
2347 * Job_CatchChildren
2348 *	Handle the exit of a child. Called from Make_Make.
2349 *
2350 * Side Effects:
2351 *	The job descriptor is removed from the list of children.
2352 *
2353 * Notes:
2354 *	We do waits, blocking or not, according to the wisdom of our
2355 *	caller, until there are no more children to report. For each
2356 *	job, call JobFinish to finish things off. This will take care of
2357 *	putting jobs on the stoppedJobs queue.
2358 */
2359void
2360Job_CatchChildren(Boolean block)
2361{
2362	pid_t	pid;	/* pid of dead child */
2363	Job	*job;	/* job descriptor for dead child */
2364	int	status;	/* Exit/termination status */
2365
2366	/*
2367	 * Don't even bother if we know there's no one around.
2368	 */
2369	if (nJobs == 0) {
2370		return;
2371	}
2372
2373	for (;;) {
2374		pid = waitpid((pid_t)-1, &status,
2375		    (block ? 0 : WNOHANG) | WUNTRACED);
2376		if (pid <= 0)
2377			break;
2378
2379		DEBUGF(JOB, ("Process %jd exited or stopped.\n",
2380		    (intmax_t)pid));
2381
2382		TAILQ_FOREACH(job, &jobs, link) {
2383			if (job->pid == pid)
2384				break;
2385		}
2386
2387		if (job == NULL) {
2388			if (WIFSIGNALED(status) &&
2389			    (WTERMSIG(status) == SIGCONT)) {
2390				TAILQ_FOREACH(job, &jobs, link) {
2391					if (job->pid == pid)
2392						break;
2393				}
2394				if (job == NULL) {
2395					Error("Resumed child (%jd) "
2396					    "not in table", (intmax_t)pid);
2397					continue;
2398				}
2399				TAILQ_REMOVE(&stoppedJobs, job, link);
2400			} else {
2401				Error("Child (%jd) not in table?",
2402				    (intmax_t)pid);
2403				continue;
2404			}
2405		} else {
2406			TAILQ_REMOVE(&jobs, job, link);
2407			nJobs -= 1;
2408			if (fifoFd >= 0 && maxJobs > 1) {
2409				write(fifoFd, "+", 1);
2410				maxJobs--;
2411				if (nJobs >= maxJobs)
2412					jobFull = TRUE;
2413				else
2414					jobFull = FALSE;
2415			} else {
2416				DEBUGF(JOB, ("Job queue is no longer full.\n"));
2417				jobFull = FALSE;
2418			}
2419		}
2420
2421		JobFinish(job, &status);
2422	}
2423	if (interrupted)
2424		JobPassSig(interrupted);
2425}
2426
2427/**
2428 * Job_CatchOutput
2429 *	Catch the output from our children, if we're using
2430 *	pipes do so. Otherwise just block time until we get a
2431 *	signal(most likely a SIGCHLD) since there's no point in
2432 *	just spinning when there's nothing to do and the reaping
2433 *	of a child can wait for a while.
2434 *
2435 * Side Effects:
2436 *	Output is read from pipes if we're piping.
2437 * -----------------------------------------------------------------------
2438 */
2439void
2440#ifdef USE_KQUEUE
2441Job_CatchOutput(int flag __unused)
2442#else
2443Job_CatchOutput(int flag)
2444#endif
2445{
2446	int		nfds;
2447#ifdef USE_KQUEUE
2448#define KEV_SIZE	4
2449	struct kevent	kev[KEV_SIZE];
2450	int		i;
2451#else
2452	struct timeval	timeout;
2453	fd_set		readfds;
2454	Job		*job;
2455#endif
2456
2457	fflush(stdout);
2458
2459	if (usePipes) {
2460#ifdef USE_KQUEUE
2461		if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
2462			if (errno != EINTR)
2463				Punt("kevent: %s", strerror(errno));
2464			if (interrupted)
2465				JobPassSig(interrupted);
2466		} else {
2467			for (i = 0; i < nfds; i++) {
2468				if (kev[i].flags & EV_ERROR) {
2469					warnc(kev[i].data, "kevent");
2470					continue;
2471				}
2472				switch (kev[i].filter) {
2473				  case EVFILT_READ:
2474					JobDoOutput(kev[i].udata, FALSE);
2475					break;
2476				  case EVFILT_PROC:
2477					/*
2478					 * Just wake up and let
2479					 * Job_CatchChildren() collect the
2480					 * terminated job.
2481					 */
2482					break;
2483				}
2484			}
2485		}
2486#else
2487		readfds = outputs;
2488		timeout.tv_sec = SEL_SEC;
2489		timeout.tv_usec = SEL_USEC;
2490		if (flag && jobFull && fifoFd >= 0)
2491			FD_SET(fifoFd, &readfds);
2492
2493		nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
2494		    (fd_set *)NULL, &timeout);
2495		if (nfds <= 0) {
2496			if (interrupted)
2497				JobPassSig(interrupted);
2498			return;
2499		}
2500		if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2501			if (--nfds <= 0)
2502				return;
2503		}
2504		job = TAILQ_FIRST(&jobs);
2505		while (nfds != 0 && job != NULL) {
2506			if (FD_ISSET(job->inPipe, &readfds)) {
2507				JobDoOutput(job, FALSE);
2508				nfds--;
2509			}
2510			job = TAILQ_NEXT(job, link);
2511		}
2512#endif /* !USE_KQUEUE */
2513	}
2514}
2515
2516/**
2517 * Job_Make
2518 *	Start the creation of a target. Basically a front-end for
2519 *	JobStart used by the Make module.
2520 *
2521 * Side Effects:
2522 *	Another job is started.
2523 */
2524void
2525Job_Make(GNode *gn)
2526{
2527
2528	JobStart(gn, 0, NULL);
2529}
2530
2531static int
2532sort_builtins(const void *p1, const void *p2)
2533{
2534
2535	return (strcmp(*(const char* const*)p1, *(const char* const*)p2));
2536}
2537
2538/**
2539 * JobFreeShell
2540 *	Free a shell structure and all associated strings.
2541 */
2542static void
2543JobFreeShell(struct Shell *sh)
2544{
2545
2546	if (sh != NULL) {
2547		free(sh->name);
2548		free(sh->path);
2549		free(sh->echoOff);
2550		free(sh->echoOn);
2551		free(sh->noPrint);
2552		free(sh->errCheck);
2553		free(sh->ignErr);
2554		free(sh->echo);
2555		free(sh->exit);
2556		ArgArray_Done(&sh->builtins);
2557		free(sh->meta);
2558		free(sh);
2559	}
2560}
2561
2562/**
2563 * Dump a shell specification to stderr.
2564 */
2565static void
2566JobShellDump(const struct Shell *sh)
2567{
2568	int i;
2569
2570	fprintf(stderr, "Shell %p:\n", sh);
2571	fprintf(stderr, "  name='%s' path='%s'\n", sh->name, sh->path);
2572	fprintf(stderr, "  hasEchoCtl=%d echoOff='%s' echoOn='%s'\n",
2573	    sh->hasEchoCtl, sh->echoOff, sh->echoOn);
2574	fprintf(stderr, "  noPrint='%s'\n", sh->noPrint);
2575	fprintf(stderr, "  hasErrCtl=%d errCheck='%s' ignErr='%s'\n",
2576	    sh->hasErrCtl, sh->errCheck, sh->ignErr);
2577	fprintf(stderr, "  echo='%s' exit='%s'\n", sh->echo, sh->exit);
2578	fprintf(stderr, "  builtins=%d\n", sh->builtins.argc - 1);
2579	for (i = 1; i < sh->builtins.argc; i++)
2580		fprintf(stderr, " '%s'", sh->builtins.argv[i]);
2581	fprintf(stderr, "\n  meta='%s'\n", sh->meta);
2582}
2583
2584static void
2585Shell_Init(void)
2586{
2587
2588	if (commandShell == NULL) {
2589		commandShell = JobMatchShell(shells[DEFSHELL][0]);
2590	}
2591}
2592
2593/**
2594 * Job_Init
2595 *	Initialize the process module, given a maximum number of jobs.
2596 *
2597 * Side Effects:
2598 *	lists and counters are initialized
2599 */
2600void
2601Job_Init(int maxproc)
2602{
2603	GNode		*begin;	/* node for commands to do at the very start */
2604	const char	*env;
2605	struct sigaction sa;
2606
2607	fifoFd = -1;
2608	env = getenv("MAKE_JOBS_FIFO");
2609
2610	if (env == NULL && maxproc > 1) {
2611		/*
2612		 * We did not find the environment variable so we are the
2613		 * leader. Create the fifo, open it, write one char per
2614		 * allowed job into the pipe.
2615		 */
2616		fifoFd = mkfifotemp(fifoName);
2617		if (fifoFd < 0) {
2618			env = NULL;
2619		} else {
2620			fifoMaster = 1;
2621			fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2622			env = fifoName;
2623			setenv("MAKE_JOBS_FIFO", env, 1);
2624			while (maxproc-- > 0) {
2625				write(fifoFd, "+", 1);
2626			}
2627			/* The master make does not get a magic token */
2628			jobFull = TRUE;
2629			maxJobs = 0;
2630		}
2631
2632	} else if (env != NULL) {
2633		/*
2634		 * We had the environment variable so we are a slave.
2635		 * Open fifo and give ourselves a magic token which represents
2636		 * the token our parent make has grabbed to start his make
2637		 * process. Otherwise the sub-makes would gobble up tokens and
2638		 * the proper number of tokens to specify to -j would depend
2639		 * on the depth of the tree and the order of execution.
2640		 */
2641		fifoFd = open(env, O_RDWR, 0);
2642		if (fifoFd >= 0) {
2643			fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2644			maxJobs = 1;
2645			jobFull = FALSE;
2646		}
2647	}
2648	if (fifoFd <= 0) {
2649		maxJobs = maxproc;
2650		jobFull = FALSE;
2651	} else {
2652	}
2653	nJobs = 0;
2654
2655	aborting = 0;
2656	errors = 0;
2657
2658	lastNode = NULL;
2659
2660	if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2661		/*
2662		 * If only one job can run at a time, there's no need for a
2663		 * banner, no is there?
2664		 */
2665		targFmt = "";
2666	} else {
2667		targFmt = TARG_FMT;
2668	}
2669
2670	Shell_Init();
2671
2672	/*
2673	 * Catch the four signals that POSIX specifies if they aren't ignored.
2674	 * JobCatchSignal will just set global variables and hope someone
2675	 * else is going to handle the interrupt.
2676	 */
2677	sa.sa_handler = JobCatchSig;
2678	sigemptyset(&sa.sa_mask);
2679	sa.sa_flags = 0;
2680
2681	if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2682		sigaction(SIGINT, &sa, NULL);
2683	}
2684	if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2685		sigaction(SIGHUP, &sa, NULL);
2686	}
2687	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2688		sigaction(SIGQUIT, &sa, NULL);
2689	}
2690	if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2691		sigaction(SIGTERM, &sa, NULL);
2692	}
2693	/*
2694	 * There are additional signals that need to be caught and passed if
2695	 * either the export system wants to be told directly of signals or if
2696	 * we're giving each job its own process group (since then it won't get
2697	 * signals from the terminal driver as we own the terminal)
2698	 */
2699#if defined(USE_PGRP)
2700	if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2701		sigaction(SIGTSTP, &sa, NULL);
2702	}
2703	if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2704		sigaction(SIGTTOU, &sa, NULL);
2705	}
2706	if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2707		sigaction(SIGTTIN, &sa, NULL);
2708	}
2709	if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2710		sigaction(SIGWINCH, &sa, NULL);
2711	}
2712#endif
2713
2714#ifdef USE_KQUEUE
2715	if ((kqfd = kqueue()) == -1) {
2716		Punt("kqueue: %s", strerror(errno));
2717	}
2718#endif
2719
2720	begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2721
2722	if (begin != NULL) {
2723		JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2724		while (nJobs) {
2725			Job_CatchOutput(0);
2726			Job_CatchChildren(!usePipes);
2727		}
2728	}
2729	postCommands = Targ_FindNode(".END", TARG_CREATE);
2730}
2731
2732/**
2733 * Job_Full
2734 *	See if the job table is full. It is considered full if it is OR
2735 *	if we are in the process of aborting OR if we have
2736 *	reached/exceeded our local quota. This prevents any more jobs
2737 *	from starting up.
2738 *
2739 * Results:
2740 *	TRUE if the job table is full, FALSE otherwise
2741 */
2742Boolean
2743Job_Full(void)
2744{
2745	char c;
2746	int i;
2747
2748	if (aborting)
2749		return (aborting);
2750	if (fifoFd >= 0 && jobFull) {
2751		i = read(fifoFd, &c, 1);
2752		if (i > 0) {
2753			maxJobs++;
2754			jobFull = FALSE;
2755		}
2756	}
2757	return (jobFull);
2758}
2759
2760/**
2761 * Job_Empty
2762 *	See if the job table is empty.  Because the local concurrency may
2763 *	be set to 0, it is possible for the job table to become empty,
2764 *	while the list of stoppedJobs remains non-empty. In such a case,
2765 *	we want to restart as many jobs as we can.
2766 *
2767 * Results:
2768 *	TRUE if it is. FALSE if it ain't.
2769 */
2770Boolean
2771Job_Empty(void)
2772{
2773	if (nJobs == 0) {
2774		if (!TAILQ_EMPTY(&stoppedJobs) && !aborting) {
2775			/*
2776			 * The job table is obviously not full if it has no
2777			 * jobs in it...Try and restart the stopped jobs.
2778			 */
2779			jobFull = FALSE;
2780			JobRestartJobs();
2781			return (FALSE);
2782		} else {
2783			return (TRUE);
2784		}
2785	} else {
2786		return (FALSE);
2787	}
2788}
2789
2790static struct Shell *
2791JobParseShellSpec(const char *spec, Boolean *fullSpec)
2792{
2793	ArgArray	aa;
2794	struct Shell	*sh;
2795	char		*eq;
2796	char		*keyw;
2797	int		arg;
2798
2799	*fullSpec = FALSE;
2800
2801	sh = emalloc(sizeof(*sh));
2802	memset(sh, 0, sizeof(*sh));
2803	ArgArray_Init(&sh->builtins);
2804
2805	/*
2806	 * Parse the specification by keyword but skip the first word
2807	 */
2808	brk_string(&aa, spec, TRUE);
2809
2810	for (arg = 1; arg < aa.argc; arg++) {
2811		/*
2812		 * Split keyword and value
2813		 */
2814		keyw = aa.argv[arg];
2815		if ((eq = strchr(keyw, '=')) == NULL) {
2816			Parse_Error(PARSE_FATAL, "missing '=' in shell "
2817			    "specification keyword '%s'", keyw);
2818			ArgArray_Done(&aa);
2819			JobFreeShell(sh);
2820			return (NULL);
2821		}
2822		*eq++ = '\0';
2823
2824		if (strcmp(keyw, "path") == 0) {
2825			free(sh->path);
2826			sh->path = estrdup(eq);
2827		} else if (strcmp(keyw, "name") == 0) {
2828			free(sh->name);
2829			sh->name = estrdup(eq);
2830		} else if (strcmp(keyw, "quiet") == 0) {
2831			free(sh->echoOff);
2832			sh->echoOff = estrdup(eq);
2833			*fullSpec = TRUE;
2834		} else if (strcmp(keyw, "echo") == 0) {
2835			free(sh->echoOn);
2836			sh->echoOn = estrdup(eq);
2837			*fullSpec = TRUE;
2838		} else if (strcmp(keyw, "filter") == 0) {
2839			free(sh->noPrint);
2840			sh->noPrint = estrdup(eq);
2841			*fullSpec = TRUE;
2842		} else if (strcmp(keyw, "echoFlag") == 0) {
2843			free(sh->echo);
2844			sh->echo = estrdup(eq);
2845			*fullSpec = TRUE;
2846		} else if (strcmp(keyw, "errFlag") == 0) {
2847			free(sh->exit);
2848			sh->exit = estrdup(eq);
2849			*fullSpec = TRUE;
2850		} else if (strcmp(keyw, "hasErrCtl") == 0) {
2851			sh->hasErrCtl = (*eq == 'Y' || *eq == 'y' ||
2852			    *eq == 'T' || *eq == 't');
2853			*fullSpec = TRUE;
2854		} else if (strcmp(keyw, "check") == 0) {
2855			free(sh->errCheck);
2856			sh->errCheck = estrdup(eq);
2857			*fullSpec = TRUE;
2858		} else if (strcmp(keyw, "ignore") == 0) {
2859			free(sh->ignErr);
2860			sh->ignErr = estrdup(eq);
2861			*fullSpec = TRUE;
2862		} else if (strcmp(keyw, "builtins") == 0) {
2863			ArgArray_Done(&sh->builtins);
2864			brk_string(&sh->builtins, eq, TRUE);
2865			qsort(sh->builtins.argv + 1, sh->builtins.argc - 1,
2866			    sizeof(char *), sort_builtins);
2867			*fullSpec = TRUE;
2868		} else if (strcmp(keyw, "meta") == 0) {
2869			free(sh->meta);
2870			sh->meta = estrdup(eq);
2871			*fullSpec = TRUE;
2872		} else {
2873			Parse_Error(PARSE_FATAL, "unknown keyword in shell "
2874			    "specification '%s'", keyw);
2875			ArgArray_Done(&aa);
2876			JobFreeShell(sh);
2877			return (NULL);
2878		}
2879	}
2880	ArgArray_Done(&aa);
2881
2882	/*
2883	 * Some checks (could be more)
2884	 */
2885	if (*fullSpec) {
2886		if ((sh->echoOn != NULL) ^ (sh->echoOff != NULL)) {
2887			Parse_Error(PARSE_FATAL, "Shell must have either both "
2888			    "echoOff and echoOn or none of them");
2889			JobFreeShell(sh);
2890			return (NULL);
2891		}
2892
2893		if (sh->echoOn != NULL && sh->echoOff != NULL)
2894			sh->hasEchoCtl = TRUE;
2895	}
2896
2897	return (sh);
2898}
2899
2900/**
2901 * Find a matching shell in 'shells' given its final component.
2902 *
2903 * Results:
2904 *	A pointer to a freshly allocated Shell structure with the contents
2905 *	from static description or NULL if no shell with the given name
2906 *	is found.
2907 */
2908static struct Shell *
2909JobMatchShell(const char *name)
2910{
2911	u_int			sh;
2912	Boolean			fullSpec;
2913
2914	for (sh = 0; shells[sh][0] != NULL; sh++)
2915		if (strcmp(shells[sh][0], name) == 0)
2916			return (JobParseShellSpec(shells[sh][1], &fullSpec));
2917
2918	return (NULL);
2919}
2920
2921/**
2922 * Job_ParseShell
2923 *	Parse a shell specification and set up commandShell appropriately.
2924 *
2925 * Results:
2926 *	TRUE if the specification was correct. FALSE otherwise.
2927 *
2928 * Side Effects:
2929 *	commandShell points to a Shell structure (either predefined or
2930 *	created from the shell spec).
2931 *
2932 * Notes:
2933 *	A shell specification consists of a .SHELL target, with dependency
2934 *	operator, followed by a series of blank-separated words. Double
2935 *	quotes can be used to use blanks in words. A backslash escapes
2936 *	anything (most notably a double-quote and a space) and
2937 *	provides the functionality it does in C. Each word consists of
2938 *	keyword and value separated by an equal sign. There should be no
2939 *	unnecessary spaces in the word. The keywords are as follows:
2940 *	    name	    Name of shell.
2941 *	    path	    Location of shell. Overrides "name" if given
2942 *	    quiet	    Command to turn off echoing.
2943 *	    echo	    Command to turn echoing on
2944 *	    filter	    Result of turning off echoing that shouldn't be
2945 *			    printed.
2946 *	    echoFlag	    Flag to turn echoing on at the start
2947 *	    errFlag	    Flag to turn error checking on at the start
2948 *	    hasErrCtl	    True if shell has error checking control
2949 *	    check	    Command to turn on error checking if hasErrCtl
2950 *			    is TRUE or template of command to echo a command
2951 *			    for which error checking is off if hasErrCtl is
2952 *			    FALSE.
2953 *	    ignore	    Command to turn off error checking if hasErrCtl
2954 *			    is TRUE or template of command to execute a
2955 *			    command so as to ignore any errors it returns if
2956 *			    hasErrCtl is FALSE.
2957 *	    builtins	    A space separated list of builtins. If one
2958 *			    of these builtins is detected when make wants
2959 *			    to execute a command line, the command line is
2960 *			    handed to the shell. Otherwise make may try to
2961 *			    execute the command directly. If this list is empty
2962 *			    it is assumed, that the command must always be
2963 *			    handed over to the shell.
2964 *	    meta	    The shell meta characters. If this is not specified
2965 *			    or empty, commands are alway passed to the shell.
2966 *			    Otherwise they are not passed when they contain
2967 *			    neither a meta character nor a builtin command.
2968 */
2969Boolean
2970Job_ParseShell(const char line[])
2971{
2972	Boolean		fullSpec;
2973	struct Shell	*sh;
2974	struct Shell	*match;
2975
2976	/* parse the specification */
2977	if ((sh = JobParseShellSpec(line, &fullSpec)) == NULL)
2978		return (FALSE);
2979
2980	if (sh->path == NULL) {
2981		/*
2982		 * If no path was given, the user wants one of the pre-defined
2983		 * shells, yes? So we find the one s/he wants with the help of
2984		 * JobMatchShell and set things up the right way.
2985		 */
2986		if (sh->name == NULL) {
2987			Parse_Error(PARSE_FATAL,
2988			    "Neither path nor name specified");
2989			JobFreeShell(sh);
2990			return (FALSE);
2991		}
2992		if (fullSpec) {
2993			Parse_Error(PARSE_FATAL, "No path specified");
2994			JobFreeShell(sh);
2995			return (FALSE);
2996		}
2997		if ((match = JobMatchShell(sh->name)) == NULL) {
2998			Parse_Error(PARSE_FATAL, "%s: no matching shell",
2999			    sh->name);
3000			JobFreeShell(sh);
3001			return (FALSE);
3002		}
3003		JobFreeShell(sh);
3004		sh = match;
3005
3006	} else {
3007		/*
3008		 * The user provided a path. If s/he gave nothing else
3009		 * (fullSpec is FALSE), try and find a matching shell in the
3010		 * ones we know of. Else we just take the specification at its
3011		 * word and copy it to a new location. In either case, we need
3012		 * to record the path the user gave for the shell.
3013		 */
3014		if (sh->name == NULL) {
3015			/* get the base name as the name */
3016			if ((sh->name = strrchr(sh->path, '/')) == NULL) {
3017				sh->name = estrdup(sh->path);
3018			} else {
3019				sh->name = estrdup(sh->name + 1);
3020			}
3021		}
3022
3023		if (!fullSpec) {
3024			if ((match = JobMatchShell(sh->name)) == NULL) {
3025				Parse_Error(PARSE_FATAL,
3026				    "%s: no matching shell", sh->name);
3027				JobFreeShell(sh);
3028				return (FALSE);
3029			}
3030			free(match->path);
3031			match->path = sh->path;
3032			sh->path = NULL;
3033			JobFreeShell(sh);
3034			sh = match;
3035		}
3036	}
3037
3038	/* set the new shell */
3039	JobFreeShell(commandShell);
3040	commandShell = sh;
3041
3042	return (TRUE);
3043}
3044
3045/**
3046 * JobInterrupt
3047 *	Handle the receipt of an interrupt.
3048 *
3049 * Side Effects:
3050 *	All children are killed. Another job will be started if the
3051 *	.INTERRUPT target was given.
3052 */
3053static void
3054JobInterrupt(int runINTERRUPT, int signo)
3055{
3056	Job	*job;		/* job descriptor in that element */
3057	GNode	*interrupt;	/* the node describing the .INTERRUPT target */
3058
3059	aborting = ABORT_INTERRUPT;
3060
3061	TAILQ_FOREACH(job, &jobs, link) {
3062		if (!Targ_Precious(job->node)) {
3063			char *file = (job->node->path == NULL ?
3064			    job->node->name : job->node->path);
3065
3066			if (!noExecute && eunlink(file) != -1) {
3067				Error("*** %s removed", file);
3068			}
3069		}
3070		if (job->pid) {
3071			DEBUGF(JOB, ("JobInterrupt passing signal to child "
3072			    "%jd.\n", (intmax_t)job->pid));
3073			KILL(job->pid, signo);
3074		}
3075	}
3076
3077	if (runINTERRUPT && !touchFlag) {
3078		/*
3079		 * clear the interrupted flag because we would get an
3080		 * infinite loop otherwise.
3081		 */
3082		interrupted = 0;
3083
3084		interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
3085		if (interrupt != NULL) {
3086			ignoreErrors = FALSE;
3087
3088			JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
3089			while (nJobs) {
3090				Job_CatchOutput(0);
3091				Job_CatchChildren(!usePipes);
3092			}
3093		}
3094	}
3095}
3096
3097/**
3098 * Job_Finish
3099 *	Do final processing such as the running of the commands
3100 *	attached to the .END target.
3101 *
3102 * Results:
3103 *	Number of errors reported.
3104 */
3105int
3106Job_Finish(void)
3107{
3108
3109	if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
3110		if (errors) {
3111			Error("Errors reported so .END ignored");
3112		} else {
3113			JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
3114
3115			while (nJobs) {
3116				Job_CatchOutput(0);
3117				Job_CatchChildren(!usePipes);
3118			}
3119		}
3120	}
3121	if (fifoFd >= 0) {
3122		close(fifoFd);
3123		fifoFd = -1;
3124		if (fifoMaster)
3125			unlink(fifoName);
3126	}
3127	return (errors);
3128}
3129
3130/**
3131 * Job_Wait
3132 *	Waits for all running jobs to finish and returns. Sets 'aborting'
3133 *	to ABORT_WAIT to prevent other jobs from starting.
3134 *
3135 * Side Effects:
3136 *	Currently running jobs finish.
3137 */
3138void
3139Job_Wait(void)
3140{
3141
3142	aborting = ABORT_WAIT;
3143	while (nJobs != 0) {
3144		Job_CatchOutput(0);
3145		Job_CatchChildren(!usePipes);
3146	}
3147	aborting = 0;
3148}
3149
3150/**
3151 * Job_AbortAll
3152 *	Abort all currently running jobs without handling output or anything.
3153 *	This function is to be called only in the event of a major
3154 *	error. Most definitely NOT to be called from JobInterrupt.
3155 *
3156 * Side Effects:
3157 *	All children are killed, not just the firstborn
3158 */
3159void
3160Job_AbortAll(void)
3161{
3162	Job	*job;	/* the job descriptor in that element */
3163	int	foo;
3164
3165	aborting = ABORT_ERROR;
3166
3167	if (nJobs) {
3168		TAILQ_FOREACH(job, &jobs, link) {
3169			/*
3170			 * kill the child process with increasingly drastic
3171			 * signals to make darn sure it's dead.
3172			 */
3173			KILL(job->pid, SIGINT);
3174			KILL(job->pid, SIGKILL);
3175		}
3176	}
3177
3178	/*
3179	 * Catch as many children as want to report in at first, then give up
3180	 */
3181	while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
3182		;
3183}
3184
3185/**
3186 * JobRestartJobs
3187 *	Tries to restart stopped jobs if there are slots available.
3188 *	Note that this tries to restart them regardless of pending errors.
3189 *	It's not good to leave stopped jobs lying around!
3190 *
3191 * Side Effects:
3192 *	Resumes(and possibly migrates) jobs.
3193 */
3194static void
3195JobRestartJobs(void)
3196{
3197	Job *job;
3198
3199	while (!jobFull && (job = TAILQ_FIRST(&stoppedJobs)) != NULL) {
3200		DEBUGF(JOB, ("Job queue is not full. "
3201		    "Restarting a stopped job.\n"));
3202		TAILQ_REMOVE(&stoppedJobs, job, link);
3203		JobRestart(job);
3204	}
3205}
3206
3207/**
3208 * Cmd_Exec
3209 *	Execute the command in cmd, and return the output of that command
3210 *	in a string.
3211 *
3212 * Results:
3213 *	A string containing the output of the command, or the empty string
3214 *	If error is not NULL, it contains the reason for the command failure
3215 *	Any output sent to stderr in the child process is passed to stderr,
3216 *	and not captured in the string.
3217 *
3218 * Side Effects:
3219 *	The string must be freed by the caller.
3220 */
3221Buffer *
3222Cmd_Exec(const char *cmd, const char **error)
3223{
3224	int	fds[2];	/* Pipe streams */
3225	int	status;	/* command exit status */
3226	Buffer	*buf;	/* buffer to store the result */
3227	ssize_t	rcnt;
3228	ProcStuff	ps;
3229
3230	*error = NULL;
3231	buf = Buf_Init(0);
3232
3233	if (commandShell == NULL)
3234		Shell_Init();
3235	/*
3236	 * Open a pipe for fetching its output
3237	 */
3238	if (pipe(fds) == -1) {
3239		*error = "Couldn't create pipe for \"%s\"";
3240		return (buf);
3241	}
3242
3243	/* Set close-on-exec on read side of pipe. */
3244	fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC);
3245
3246	ps.in = STDIN_FILENO;
3247	ps.out = fds[1];
3248	ps.err = STDERR_FILENO;
3249
3250	ps.merge_errors = 0;
3251	ps.pgroup = 0;
3252	ps.searchpath = 0;
3253
3254	/* Set up arguments for shell */
3255	ps.argv = emalloc(4 * sizeof(char *));
3256	ps.argv[0] = strdup(commandShell->name);
3257	ps.argv[1] = strdup("-c");
3258	ps.argv[2] = strdup(cmd);
3259	ps.argv[3] = NULL;
3260	ps.argv_free = 1;
3261
3262	/*
3263	 * Fork.  Warning since we are doing vfork() instead of fork(),
3264	 * do not allocate memory in the child process!
3265	 */
3266	if ((ps.child_pid = vfork()) == -1) {
3267		*error = "Couldn't exec \"%s\"";
3268		return (buf);
3269
3270	} else if (ps.child_pid == 0) {
3271  		/*
3272		 * Child
3273  		 */
3274		ProcExec(&ps);
3275		/* NOTREACHED */
3276	}
3277
3278	free(ps.argv[2]);
3279	free(ps.argv[1]);
3280	free(ps.argv[0]);
3281	free(ps.argv);
3282
3283	close(fds[1]); /* No need for the writing half of the pipe. */
3284
3285	do {
3286		char	result[BUFSIZ];
3287
3288		rcnt = read(fds[0], result, sizeof(result));
3289		if (rcnt != -1)
3290			Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
3291	} while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
3292
3293	if (rcnt == -1)
3294		*error = "Error reading shell's output for \"%s\"";
3295
3296	/*
3297	 * Close the input side of the pipe.
3298	 */
3299	close(fds[0]);
3300
3301	status = ProcWait(&ps);
3302
3303	if (status)
3304		*error = "\"%s\" returned non-zero status";
3305
3306	Buf_StripNewlines(buf);
3307
3308	return (buf);
3309}
3310
3311
3312/*
3313 * Interrupt handler - set flag and defer handling to the main code
3314 */
3315static void
3316CompatCatchSig(int signo)
3317{
3318
3319	interrupted = signo;
3320}
3321
3322/*-
3323 *-----------------------------------------------------------------------
3324 * CompatInterrupt --
3325 *	Interrupt the creation of the current target and remove it if
3326 *	it ain't precious.
3327 *
3328 * Results:
3329 *	None.
3330 *
3331 * Side Effects:
3332 *	The target is removed and the process exits. If .INTERRUPT exists,
3333 *	its commands are run first WITH INTERRUPTS IGNORED..
3334 *
3335 *-----------------------------------------------------------------------
3336 */
3337static void
3338CompatInterrupt(int signo)
3339{
3340	GNode		*gn;
3341	sigset_t	nmask, omask;
3342	LstNode		*ln;
3343
3344	sigemptyset(&nmask);
3345	sigaddset(&nmask, SIGINT);
3346	sigaddset(&nmask, SIGTERM);
3347	sigaddset(&nmask, SIGHUP);
3348	sigaddset(&nmask, SIGQUIT);
3349	sigprocmask(SIG_SETMASK, &nmask, &omask);
3350
3351	/* prevent recursion in evaluation of .INTERRUPT */
3352	interrupted = 0;
3353
3354	if (curTarg != NULL && !Targ_Precious(curTarg)) {
3355		char	  *p1;
3356		char	  *file = Var_Value(TARGET, curTarg, &p1);
3357
3358		if (!noExecute && eunlink(file) != -1) {
3359			printf("*** %s removed\n", file);
3360		}
3361		free(p1);
3362	}
3363
3364	/*
3365	 * Run .INTERRUPT only if hit with interrupt signal
3366	 */
3367	if (signo == SIGINT) {
3368		gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
3369		if (gn != NULL) {
3370			LST_FOREACH(ln, &gn->commands) {
3371				if (Compat_RunCommand(Lst_Datum(ln), gn))
3372					break;
3373			}
3374		}
3375	}
3376
3377	sigprocmask(SIG_SETMASK, &omask, NULL);
3378
3379	if (signo == SIGQUIT)
3380		exit(signo);
3381	signal(signo, SIG_DFL);
3382	kill(getpid(), signo);
3383}
3384
3385/**
3386 * shellneed
3387 *
3388 * Results:
3389 *	Returns NULL if a specified line must be executed by the shell,
3390 *	and an argument vector if it can be run via execvp().
3391 *
3392 * Side Effects:
3393 *	Uses brk_string so destroys the contents of argv.
3394 */
3395static char **
3396shellneed(ArgArray *aa, char *cmd)
3397{
3398	char	**p;
3399	int	ret;
3400
3401	if (commandShell->meta == NULL || commandShell->builtins.argc <= 1)
3402		/* use shell */
3403		return (NULL);
3404
3405	if (strpbrk(cmd, commandShell->meta) != NULL)
3406		return (NULL);
3407
3408	/*
3409	 * Break the command into words to form an argument
3410	 * vector we can execute.
3411	 */
3412	brk_string(aa, cmd, TRUE);
3413	for (p = commandShell->builtins.argv + 1; *p != 0; p++) {
3414		if ((ret = strcmp(aa->argv[1], *p)) == 0) {
3415			/* found - use shell */
3416			ArgArray_Done(aa);
3417			return (NULL);
3418		}
3419		if (ret < 0) {
3420			/* not found */
3421			break;
3422		}
3423	}
3424	return (aa->argv + 1);
3425}
3426
3427/**
3428 * Execute the next command for a target. If the command returns an
3429 * error, the node's made field is set to ERROR and creation stops.
3430 * The node from which the command came is also given. This is used
3431 * to execute the commands in compat mode and when executing commands
3432 * with the '+' flag in non-compat mode. In these modes each command
3433 * line should be executed by its own shell. We do some optimisation here:
3434 * if the shell description defines both a string of meta characters and
3435 * a list of builtins and the command line neither contains a meta character
3436 * nor starts with one of the builtins then we execute the command directly
3437 * without invoking a shell.
3438 *
3439 * Results:
3440 *	0 if the command succeeded, 1 if an error occurred.
3441 *
3442 * Side Effects:
3443 *	The node's 'made' field may be set to ERROR.
3444 */
3445static int
3446Compat_RunCommand(char *cmd, GNode *gn)
3447{
3448	ArgArray	aa;
3449	char		*cmdStart;	/* Start of expanded command */
3450	Boolean		silent;		/* Don't print command */
3451	Boolean		doit;		/* Execute even in -n */
3452	Boolean		errCheck;	/* Check errors */
3453	int		reason;		/* Reason for child's death */
3454	int		status;		/* Description of child's death */
3455	LstNode		*cmdNode;	/* Node where current cmd is located */
3456	char		**av;		/* Argument vector for thing to exec */
3457	ProcStuff	ps;
3458
3459	silent = gn->type & OP_SILENT;
3460	errCheck = !(gn->type & OP_IGNORE);
3461	doit = FALSE;
3462
3463	cmdNode = Lst_Member(&gn->commands, cmd);
3464	cmdStart = Buf_Peel(Var_Subst(cmd, gn, FALSE));
3465
3466	/*
3467	 * brk_string will return an argv with a NULL in av[0], thus causing
3468	 * execvp() to choke and die horribly. Besides, how can we execute a
3469	 * null command? In any case, we warn the user that the command
3470	 * expanded to nothing (is this the right thing to do?).
3471	 */
3472	if (*cmdStart == '\0') {
3473		free(cmdStart);
3474		Error("%s expands to empty string", cmd);
3475		return (0);
3476	} else {
3477		cmd = cmdStart;
3478	}
3479	Lst_Replace(cmdNode, cmdStart);
3480
3481	if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
3482		Lst_AtEnd(&ENDNode->commands, cmdStart);
3483		return (0);
3484	} else if (strcmp(cmdStart, "...") == 0) {
3485		gn->type |= OP_SAVE_CMDS;
3486		return (0);
3487	}
3488
3489	while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
3490		switch (*cmd) {
3491
3492		  case '@':
3493			silent = DEBUG(LOUD) ? FALSE : TRUE;
3494			break;
3495
3496		  case '-':
3497			errCheck = FALSE;
3498			break;
3499
3500		  case '+':
3501			doit = TRUE;
3502			break;
3503		}
3504		cmd++;
3505	}
3506
3507	while (isspace((unsigned char)*cmd))
3508		cmd++;
3509
3510	/*
3511	 * Print the command before echoing if we're not supposed to be quiet
3512	 * for this one. We also print the command if -n given, but not if '+'.
3513	 */
3514	if (!silent || (noExecute && !doit)) {
3515		printf("%s\n", cmd);
3516		fflush(stdout);
3517	}
3518
3519	/*
3520	 * If we're not supposed to execute any commands, this is as far as
3521	 * we go...
3522	 */
3523	if (!doit && noExecute) {
3524		return (0);
3525	}
3526
3527	ps.in = STDIN_FILENO;
3528	ps.out = STDOUT_FILENO;
3529	ps.err = STDERR_FILENO;
3530
3531	ps.merge_errors = 0;
3532	ps.pgroup = 0;
3533	ps.searchpath = 1;
3534
3535	if ((av = shellneed(&aa, cmd)) == NULL) {
3536		/*
3537		 * Shell meta character or shell builtin found - pass
3538		 * command to shell. We give the shell the -e flag as
3539		 * well as -c if it is supposed to exit when it hits an error.
3540		 */
3541		ps.argv = emalloc(4 * sizeof(char *));
3542		ps.argv[0] = strdup(commandShell->path);
3543		ps.argv[1] = strdup(errCheck ? "-ec" : "-c");
3544		ps.argv[2] = strdup(cmd);
3545		ps.argv[3] = NULL;
3546		ps.argv_free = 1;
3547	} else {
3548		ps.argv = av;
3549		ps.argv_free = 0;
3550	}
3551	ps.errCheck = errCheck;
3552
3553	/*
3554	 * Warning since we are doing vfork() instead of fork(),
3555	 * do not allocate memory in the child process!
3556	 */
3557	if ((ps.child_pid = vfork()) == -1) {
3558		Fatal("Could not fork");
3559
3560	} else if (ps.child_pid == 0) {
3561		/*
3562		 * Child
3563		 */
3564		ProcExec(&ps);
3565  		/* NOTREACHED */
3566
3567	} else {
3568		if (ps.argv_free) {
3569			free(ps.argv[2]);
3570			free(ps.argv[1]);
3571			free(ps.argv[0]);
3572			free(ps.argv);
3573		} else {
3574			ArgArray_Done(&aa);
3575		}
3576
3577		/*
3578		 * we need to print out the command associated with this
3579		 * Gnode in Targ_PrintCmd from Targ_PrintGraph when debugging
3580		 * at level g2, in main(), Fatal() and DieHorribly(),
3581		 * therefore do not free it when debugging.
3582		 */
3583		if (!DEBUG(GRAPH2)) {
3584			free(cmdStart);
3585		}
3586
3587		/*
3588		 * The child is off and running. Now all we can do is wait...
3589		 */
3590		reason = ProcWait(&ps);
3591
3592		if (interrupted)
3593			CompatInterrupt(interrupted);
3594
3595		/*
3596		 * Decode and report the reason child exited, then
3597		 * indicate how we handled it.
3598		 */
3599		if (WIFEXITED(reason)) {
3600			status = WEXITSTATUS(reason);
3601			if (status == 0) {
3602				return (0);
3603  			} else {
3604				printf("*** Error code %d", status);
3605  			}
3606		} else if (WIFSTOPPED(reason)) {
3607			status = WSTOPSIG(reason);
3608		} else {
3609			status = WTERMSIG(reason);
3610			printf("*** Signal %d", status);
3611  		}
3612
3613		if (ps.errCheck) {
3614			gn->made = ERROR;
3615			if (keepgoing) {
3616				/*
3617				 * Abort the current
3618				 * target, but let
3619				 * others continue.
3620				 */
3621				printf(" (continuing)\n");
3622			}
3623			return (status);
3624		} else {
3625			/*
3626			 * Continue executing
3627			 * commands for this target.
3628			 * If we return 0, this will
3629			 * happen...
3630			 */
3631			printf(" (ignored)\n");
3632			return (0);
3633		}
3634	}
3635}
3636
3637/*-
3638 *-----------------------------------------------------------------------
3639 * CompatMake --
3640 *	Make a target, given the parent, to abort if necessary.
3641 *
3642 * Side Effects:
3643 *	If an error is detected and not being ignored, the process exits.
3644 *
3645 *-----------------------------------------------------------------------
3646 */
3647static int
3648CompatMake(GNode *gn, GNode *pgn)
3649{
3650	LstNode	*ln;
3651
3652	if (gn->type & OP_USE) {
3653		Make_HandleUse(gn, pgn);
3654
3655	} else if (gn->made == UNMADE) {
3656		/*
3657		 * First mark ourselves to be made, then apply whatever
3658		 * transformations the suffix module thinks are necessary.
3659		 * Once that's done, we can descend and make all our children.
3660		 * If any of them has an error but the -k flag was given, our
3661		 * 'make' field will be set FALSE again. This is our signal to
3662		 * not attempt to do anything but abort our parent as well.
3663		 */
3664		gn->make = TRUE;
3665		gn->made = BEINGMADE;
3666		Suff_FindDeps(gn);
3667		LST_FOREACH(ln, &gn->children)
3668			CompatMake(Lst_Datum(ln), gn);
3669		if (!gn->make) {
3670			gn->made = ABORTED;
3671			pgn->make = FALSE;
3672			return (0);
3673		}
3674
3675		if (Lst_Member(&gn->iParents, pgn) != NULL) {
3676			char *p1;
3677			Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
3678			free(p1);
3679		}
3680
3681		/*
3682		 * All the children were made ok. Now cmtime contains the
3683		 * modification time of the newest child, we need to find out
3684		 * if we exist and when we were modified last. The criteria for
3685		 * datedness are defined by the Make_OODate function.
3686		 */
3687		DEBUGF(MAKE, ("Examining %s...", gn->name));
3688		if (!Make_OODate(gn)) {
3689			gn->made = UPTODATE;
3690			DEBUGF(MAKE, ("up-to-date.\n"));
3691			return (0);
3692		} else {
3693			DEBUGF(MAKE, ("out-of-date.\n"));
3694		}
3695
3696		/*
3697		 * If the user is just seeing if something is out-of-date,
3698		 * exit now to tell him/her "yes".
3699		 */
3700		if (queryFlag) {
3701			exit(1);
3702		}
3703
3704		/*
3705		 * We need to be re-made. We also have to make sure we've got
3706		 * a $? variable. To be nice, we also define the $> variable
3707		 * using Make_DoAllVar().
3708		 */
3709		Make_DoAllVar(gn);
3710
3711		/*
3712		 * Alter our type to tell if errors should be ignored or things
3713		 * should not be printed so Compat_RunCommand knows what to do.
3714		 */
3715		if (Targ_Ignore(gn)) {
3716			gn->type |= OP_IGNORE;
3717		}
3718		if (Targ_Silent(gn)) {
3719			gn->type |= OP_SILENT;
3720		}
3721
3722		if (Job_CheckCommands(gn, Fatal)) {
3723			/*
3724			 * Our commands are ok, but we still have to worry
3725			 * about the -t flag...
3726			 */
3727			if (!touchFlag) {
3728				curTarg = gn;
3729				LST_FOREACH(ln, &gn->commands) {
3730					if (Compat_RunCommand(Lst_Datum(ln),
3731					    gn))
3732						break;
3733				}
3734				curTarg = NULL;
3735			} else {
3736				Job_Touch(gn, gn->type & OP_SILENT);
3737			}
3738		} else {
3739			gn->made = ERROR;
3740		}
3741
3742		if (gn->made != ERROR) {
3743			/*
3744			 * If the node was made successfully, mark it so, update
3745			 * its modification time and timestamp all its parents.
3746			 * Note that for .ZEROTIME targets, the timestamping
3747			 * isn't done. This is to keep its state from affecting
3748			 * that of its parent.
3749			 */
3750			gn->made = MADE;
3751#ifndef RECHECK
3752			/*
3753			 * We can't re-stat the thing, but we can at least take
3754			 * care of rules where a target depends on a source that
3755			 * actually creates the target, but only if it has
3756			 * changed, e.g.
3757			 *
3758			 * parse.h : parse.o
3759			 *
3760			 * parse.o : parse.y
3761			 *	yacc -d parse.y
3762			 *	cc -c y.tab.c
3763			 *	mv y.tab.o parse.o
3764			 *	cmp -s y.tab.h parse.h || mv y.tab.h parse.h
3765			 *
3766			 * In this case, if the definitions produced by yacc
3767			 * haven't changed from before, parse.h won't have been
3768			 * updated and gn->mtime will reflect the current
3769			 * modification time for parse.h. This is something of a
3770			 * kludge, I admit, but it's a useful one..
3771			 *
3772			 * XXX: People like to use a rule like
3773			 *
3774			 * FRC:
3775			 *
3776			 * To force things that depend on FRC to be made, so we
3777			 * have to check for gn->children being empty as well...
3778			 */
3779			if (!Lst_IsEmpty(&gn->commands) ||
3780			    Lst_IsEmpty(&gn->children)) {
3781				gn->mtime = now;
3782			}
3783#else
3784			/*
3785			 * This is what Make does and it's actually a good
3786			 * thing, as it allows rules like
3787			 *
3788			 *	cmp -s y.tab.h parse.h || cp y.tab.h parse.h
3789			 *
3790			 * to function as intended. Unfortunately, thanks to
3791			 * the stateless nature of NFS (and the speed of this
3792			 * program), there are times when the modification time
3793			 * of a file created on a remote machine will not be
3794			 * modified before the stat() implied by the Dir_MTime
3795			 * occurs, thus leading us to believe that the file
3796			 * is unchanged, wreaking havoc with files that depend
3797			 * on this one.
3798			 *
3799			 * I have decided it is better to make too much than to
3800			 * make too little, so this stuff is commented out
3801			 * unless you're sure it's ok.
3802			 * -- ardeb 1/12/88
3803			 */
3804			if (noExecute || Dir_MTime(gn) == 0) {
3805				gn->mtime = now;
3806			}
3807			if (gn->cmtime > gn->mtime)
3808				gn->mtime = gn->cmtime;
3809			DEBUGF(MAKE, ("update time: %s\n",
3810			    Targ_FmtTime(gn->mtime)));
3811#endif
3812			if (!(gn->type & OP_EXEC)) {
3813				pgn->childMade = TRUE;
3814				Make_TimeStamp(pgn, gn);
3815			}
3816
3817		} else if (keepgoing) {
3818			pgn->make = FALSE;
3819
3820		} else {
3821			char *p1;
3822
3823			printf("\n\nStop in %s.\n",
3824			    Var_Value(".CURDIR", gn, &p1));
3825			free(p1);
3826			exit(1);
3827		}
3828	} else if (gn->made == ERROR) {
3829		/*
3830		 * Already had an error when making this beastie. Tell the
3831		 * parent to abort.
3832		 */
3833		pgn->make = FALSE;
3834	} else {
3835		if (Lst_Member(&gn->iParents, pgn) != NULL) {
3836			char *p1;
3837			Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
3838			free(p1);
3839		}
3840		switch(gn->made) {
3841		  case BEINGMADE:
3842			Error("Graph cycles through %s\n", gn->name);
3843			gn->made = ERROR;
3844			pgn->make = FALSE;
3845			break;
3846		  case MADE:
3847			if ((gn->type & OP_EXEC) == 0) {
3848			    pgn->childMade = TRUE;
3849			    Make_TimeStamp(pgn, gn);
3850			}
3851			break;
3852		  case UPTODATE:
3853			if ((gn->type & OP_EXEC) == 0) {
3854			    Make_TimeStamp(pgn, gn);
3855			}
3856			break;
3857		  default:
3858			break;
3859		}
3860	}
3861
3862	return (0);
3863}
3864
3865/*-
3866 *-----------------------------------------------------------------------
3867 * Compat_Run --
3868 *	Start making again, given a list of target nodes.
3869 *
3870 * Results:
3871 *	None.
3872 *
3873 * Side Effects:
3874 *	Guess what?
3875 *
3876 *-----------------------------------------------------------------------
3877 */
3878void
3879Compat_Run(Lst *targs)
3880{
3881	GNode	*gn = NULL;	/* Current root target */
3882	int	error_cnt;		/* Number of targets not remade due to errors */
3883	LstNode	*ln;
3884
3885	Shell_Init();		/* Set up shell. */
3886
3887	if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
3888		signal(SIGINT, CompatCatchSig);
3889	}
3890	if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
3891		signal(SIGTERM, CompatCatchSig);
3892	}
3893	if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
3894		signal(SIGHUP, CompatCatchSig);
3895	}
3896	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
3897		signal(SIGQUIT, CompatCatchSig);
3898	}
3899
3900	ENDNode = Targ_FindNode(".END", TARG_CREATE);
3901	/*
3902	 * If the user has defined a .BEGIN target, execute the commands
3903	 * attached to it.
3904	*/
3905	if (!queryFlag) {
3906		gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
3907		if (gn != NULL) {
3908			LST_FOREACH(ln, &gn->commands) {
3909				if (Compat_RunCommand(Lst_Datum(ln), gn))
3910					break;
3911			}
3912			if (gn->made == ERROR) {
3913				printf("\n\nStop.\n");
3914				exit(1);
3915			}
3916		}
3917	}
3918
3919	/*
3920	 * For each entry in the list of targets to create, call CompatMake on
3921	 * it to create the thing. CompatMake will leave the 'made' field of gn
3922	 * in one of several states:
3923	 *	UPTODATE  gn was already up-to-date
3924	 *	MADE	  gn was recreated successfully
3925	 *	ERROR	  An error occurred while gn was being created
3926	 *	ABORTED	  gn was not remade because one of its inferiors
3927	 *		  could not be made due to errors.
3928	 */
3929	error_cnt = 0;
3930	while (!Lst_IsEmpty(targs)) {
3931		gn = Lst_DeQueue(targs);
3932		CompatMake(gn, gn);
3933
3934		if (gn->made == UPTODATE) {
3935			printf("`%s' is up to date.\n", gn->name);
3936		} else if (gn->made == ABORTED) {
3937			printf("`%s' not remade because of errors.\n",
3938			    gn->name);
3939			error_cnt += 1;
3940		}
3941	}
3942
3943	/*
3944	 * If the user has defined a .END target, run its commands.
3945	 */
3946	if (error_cnt == 0) {
3947		LST_FOREACH(ln, &ENDNode->commands) {
3948			if (Compat_RunCommand(Lst_Datum(ln), gn))
3949				break;
3950		}
3951	}
3952}
3953
3954