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