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