job.c revision 146155
1141104Sharti/*-
294589Sobrien * Copyright (c) 1988, 1989, 1990, 1993
394589Sobrien *	The Regents of the University of California.  All rights reserved.
45814Sjkh * Copyright (c) 1988, 1989 by Adam de Boor
51590Srgrimes * Copyright (c) 1989 by Berkeley Softworks
61590Srgrimes * All rights reserved.
71590Srgrimes *
81590Srgrimes * This code is derived from software contributed to Berkeley by
91590Srgrimes * Adam de Boor.
101590Srgrimes *
111590Srgrimes * Redistribution and use in source and binary forms, with or without
121590Srgrimes * modification, are permitted provided that the following conditions
131590Srgrimes * are met:
141590Srgrimes * 1. Redistributions of source code must retain the above copyright
151590Srgrimes *    notice, this list of conditions and the following disclaimer.
161590Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
171590Srgrimes *    notice, this list of conditions and the following disclaimer in the
181590Srgrimes *    documentation and/or other materials provided with the distribution.
191590Srgrimes * 3. All advertising materials mentioning features or use of this software
201590Srgrimes *    must display the following acknowledgement:
211590Srgrimes *	This product includes software developed by the University of
221590Srgrimes *	California, Berkeley and its contributors.
231590Srgrimes * 4. Neither the name of the University nor the names of its contributors
241590Srgrimes *    may be used to endorse or promote products derived from this software
251590Srgrimes *    without specific prior written permission.
261590Srgrimes *
271590Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
281590Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
291590Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
301590Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
311590Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
321590Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
331590Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
341590Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
351590Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
361590Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
371590Srgrimes * SUCH DAMAGE.
3862833Swsanchez *
3962833Swsanchez * @(#)job.c	8.2 (Berkeley) 3/19/94
401590Srgrimes */
411590Srgrimes
4262833Swsanchez#include <sys/cdefs.h>
4394587Sobrien__FBSDID("$FreeBSD: head/usr.bin/make/job.c 146155 2005-05-12 15:45:14Z harti $");
441590Srgrimes
4535483Simp#ifndef OLD_JOKE
46103503Sjmallett#define	OLD_JOKE 0
4735483Simp#endif /* OLD_JOKE */
4835483Simp
491590Srgrimes/*-
501590Srgrimes * job.c --
511590Srgrimes *	handle the creation etc. of our child processes.
521590Srgrimes *
531590Srgrimes * Interface:
54144467Sharti *	Job_Make	Start the creation of the given target.
551590Srgrimes *
56144467Sharti *	Job_CatchChildren
57144467Sharti *			Check for and handle the termination of any children.
58144467Sharti *			This must be called reasonably frequently to keep the
59144467Sharti *			whole make going at a decent clip, since job table
60144467Sharti *			entries aren't removed until their process is caught
61144467Sharti *			this way. Its single argument is TRUE if the function
62144467Sharti *			should block waiting for a child to terminate.
631590Srgrimes *
64144467Sharti *	Job_CatchOutput	Print any output our children have produced. Should
65144467Sharti *			also be called fairly frequently to keep the user
66144467Sharti *			informed of what's going on. If no output is waiting,
67144467Sharti *			it will block for a time given by the SEL_* constants,
68144467Sharti *			below, or until output is ready.
691590Srgrimes *
70144467Sharti *	Job_Init	Called to intialize this module. in addition, any
71144467Sharti *			commands attached to the .BEGIN target are executed
72144467Sharti *			before this function returns. Hence, the makefile must
73144467Sharti *			have been parsed before this function is called.
741590Srgrimes *
75144467Sharti *	Job_Full	Return TRUE if the job table is filled.
761590Srgrimes *
77144467Sharti *	Job_Empty	Return TRUE if the job table is completely empty.
781590Srgrimes *
79144467Sharti *	Job_ParseShell	Given the line following a .SHELL target, parse the
80144467Sharti *			line as a shell specification. Returns FAILURE if the
81144467Sharti *			spec was incorrect.
821590Srgrimes *
83144467Sharti *	Job_Finish	Perform any final processing which needs doing. This
84144467Sharti *			includes the execution of any commands which have
85144467Sharti *			been/were attached to the .END target. It should only
86144467Sharti *			be called when the job table is empty.
871590Srgrimes *
88144467Sharti *	Job_AbortAll	Abort all currently running jobs. It doesn't handle
89144467Sharti *			output or do anything for the jobs, just kills them.
90144467Sharti *			It should only be called in an emergency, as it were.
911590Srgrimes *
92144467Sharti *	Job_CheckCommands
93144467Sharti *			Verify that the commands for a target are ok. Provide
94144467Sharti *			them if necessary and possible.
951590Srgrimes *
96144467Sharti *	Job_Touch	Update a target without really updating it.
971590Srgrimes *
98144467Sharti *	Job_Wait	Wait for all currently-running jobs to finish.
99146132Sharti *
100146132Sharti * compat.c --
101146132Sharti *	The routines in this file implement the full-compatibility
102146132Sharti *	mode of PMake. Most of the special functionality of PMake
103146132Sharti *	is available in this mode. Things not supported:
104146132Sharti *	    - different shells.
105146132Sharti *	    - friendly variable substitution.
106146132Sharti *
107146132Sharti * Interface:
108146132Sharti *	Compat_Run	    Initialize things for this module and recreate
109146132Sharti *			    thems as need creatin'
1101590Srgrimes */
1111590Srgrimes
112144494Sharti#include <sys/queue.h>
1131590Srgrimes#include <sys/types.h>
114141104Sharti#include <sys/select.h>
1151590Srgrimes#include <sys/stat.h>
116107447Sru#ifdef USE_KQUEUE
117104475Sphk#include <sys/event.h>
118107447Sru#endif
1191590Srgrimes#include <sys/wait.h>
120141104Sharti#include <ctype.h>
12194506Scharnier#include <errno.h>
1225814Sjkh#include <fcntl.h>
123144665Sharti#include <inttypes.h>
1241590Srgrimes#include <string.h>
1255814Sjkh#include <signal.h>
126141104Sharti#include <stdlib.h>
12780381Ssheldonh#include <unistd.h>
12894506Scharnier#include <utime.h>
129141104Sharti
130141104Sharti#include "arch.h"
131142457Sharti#include "buf.h"
132146056Sharti#include "config.h"
1331590Srgrimes#include "dir.h"
134141104Sharti#include "globals.h"
135141104Sharti#include "GNode.h"
1361590Srgrimes#include "job.h"
137141104Sharti#include "make.h"
138141104Sharti#include "parse.h"
1391590Srgrimes#include "pathnames.h"
140141104Sharti#include "str.h"
141146056Sharti#include "suff.h"
142141104Sharti#include "targ.h"
143141104Sharti#include "util.h"
144141104Sharti#include "var.h"
1451590Srgrimes
146146057Sharti#define	TMPPAT	"/tmp/makeXXXXXXXXXX"
147146057Sharti
148146057Sharti#ifndef USE_KQUEUE
1491590Srgrimes/*
150146057Sharti * The SEL_ constants determine the maximum amount of time spent in select
151146057Sharti * before coming out to see if a child has finished. SEL_SEC is the number of
152146057Sharti * seconds and SEL_USEC is the number of micro-seconds
153146057Sharti */
154146057Sharti#define	SEL_SEC		2
155146057Sharti#define	SEL_USEC	0
156146057Sharti#endif /* !USE_KQUEUE */
157146057Sharti
158146057Sharti/*
159144483Sharti * Job Table definitions.
160144483Sharti *
161144483Sharti * The job "table" is kept as a linked Lst in 'jobs', with the number of
162144483Sharti * active jobs maintained in the 'nJobs' variable. At no time will this
163144483Sharti * exceed the value of 'maxJobs', initialized by the Job_Init function.
164144483Sharti *
165144483Sharti * When a job is finished, the Make_Update function is called on each of the
166144483Sharti * parents of the node which was just remade. This takes care of the upward
167144483Sharti * traversal of the dependency graph.
168144483Sharti */
169144483Sharti#define	JOB_BUFSIZE	1024
170144483Shartitypedef struct Job {
171144665Sharti	pid_t		pid;	/* The child's process ID */
172144483Sharti
173144483Sharti	struct GNode	*node;	/* The target the child is making */
174144483Sharti
175144483Sharti	/*
176144483Sharti	 * A LstNode for the first command to be saved after the job completes.
177144483Sharti	 * This is NULL if there was no "..." in the job's commands.
178144483Sharti	 */
179144483Sharti	LstNode		*tailCmds;
180144483Sharti
181144483Sharti	/*
182144483Sharti	 * An FILE* for writing out the commands. This is only
183144483Sharti	 * used before the job is actually started.
184144483Sharti	 */
185144483Sharti	FILE		*cmdFILE;
186144483Sharti
187144483Sharti	/*
188144483Sharti	 * A word of flags which determine how the module handles errors,
189144483Sharti	 * echoing, etc. for the job
190144483Sharti	 */
191144483Sharti	short		flags;	/* Flags to control treatment of job */
192144483Sharti#define	JOB_IGNERR	0x001	/* Ignore non-zero exits */
193144483Sharti#define	JOB_SILENT	0x002	/* no output */
194144483Sharti#define	JOB_SPECIAL	0x004	/* Target is a special one. i.e. run it locally
195144483Sharti				 * if we can't export it and maxLocal is 0 */
196146061Sharti#define	JOB_IGNDOTS	0x008	/* Ignore "..." lines when processing
197144483Sharti				 * commands */
198144483Sharti#define	JOB_FIRST	0x020	/* Job is first job for the node */
199144483Sharti#define	JOB_RESTART	0x080	/* Job needs to be completely restarted */
200144483Sharti#define	JOB_RESUME	0x100	/* Job needs to be resumed b/c it stopped,
201144483Sharti				 * for some reason */
202144483Sharti#define	JOB_CONTINUING	0x200	/* We are in the process of resuming this job.
203144483Sharti				 * Used to avoid infinite recursion between
204144483Sharti				 * JobFinish and JobRestart */
205144483Sharti
206144483Sharti	/* union for handling shell's output */
207144483Sharti	union {
208144483Sharti		/*
209144483Sharti		 * This part is used when usePipes is true.
210146061Sharti		 * The output is being caught via a pipe and the descriptors
211144483Sharti		 * of our pipe, an array in which output is line buffered and
212144483Sharti		 * the current position in that buffer are all maintained for
213144483Sharti		 * each job.
214144483Sharti		 */
215144483Sharti		struct {
216144483Sharti			/*
217144483Sharti			 * Input side of pipe associated with
218144483Sharti			 * job's output channel
219144483Sharti			 */
220144483Sharti			int	op_inPipe;
221144483Sharti
222144483Sharti			/*
223144483Sharti			 * Output side of pipe associated with job's
224144483Sharti			 * output channel
225144483Sharti			 */
226144483Sharti			int	op_outPipe;
227144483Sharti
228144483Sharti			/*
229144483Sharti			 * Buffer for storing the output of the
230144483Sharti			 * job, line by line
231144483Sharti			 */
232144483Sharti			char	op_outBuf[JOB_BUFSIZE + 1];
233144483Sharti
234144483Sharti			/* Current position in op_outBuf */
235144483Sharti			int	op_curPos;
236144483Sharti		}	o_pipe;
237144483Sharti
238144483Sharti		/*
239144483Sharti		 * If usePipes is false the output is routed to a temporary
240144483Sharti		 * file and all that is kept is the name of the file and the
241144483Sharti		 * descriptor open to the file.
242144483Sharti		 */
243144483Sharti		struct {
244144483Sharti			/* Name of file to which shell output was rerouted */
245144483Sharti			char	of_outFile[sizeof(TMPPAT)];
246144483Sharti
247144483Sharti			/*
248144483Sharti			 * Stream open to the output file. Used to funnel all
249144483Sharti			 * from a single job to one file while still allowing
250144483Sharti			 * multiple shell invocations
251144483Sharti			 */
252144483Sharti			int	of_outFd;
253144483Sharti		}	o_file;
254144483Sharti
255144483Sharti	}       output;	    /* Data for tracking a shell's output */
256144494Sharti
257144494Sharti	TAILQ_ENTRY(Job) link;	/* list link */
258144483Sharti} Job;
259144483Sharti
260146061Sharti#define	outPipe		output.o_pipe.op_outPipe
261146061Sharti#define	inPipe		output.o_pipe.op_inPipe
262144483Sharti#define	outBuf		output.o_pipe.op_outBuf
263144483Sharti#define	curPos		output.o_pipe.op_curPos
264144483Sharti#define	outFile		output.o_file.of_outFile
265146061Sharti#define	outFd		output.o_file.of_outFd
266144483Sharti
267144494ShartiTAILQ_HEAD(JobList, Job);
268144494Sharti
269144483Sharti/*
270144483Sharti * Shell Specifications:
271144483Sharti *
272144483Sharti * Some special stuff goes on if a shell doesn't have error control. In such
273144483Sharti * a case, errCheck becomes a printf template for echoing the command,
274144483Sharti * should echoing be on and ignErr becomes another printf template for
275144483Sharti * executing the command while ignoring the return status. If either of these
276144483Sharti * strings is empty when hasErrCtl is FALSE, the command will be executed
277144483Sharti * anyway as is and if it causes an error, so be it.
278144483Sharti */
279144483Sharti#define	DEF_SHELL_STRUCT(TAG, CONST)					\
280144483Shartistruct TAG {								\
281144483Sharti	/*								\
282144483Sharti	 * the name of the shell. For Bourne and C shells, this is used	\
283144483Sharti	 * only to find the shell description when used as the single	\
284144483Sharti	 * source of a .SHELL target. For user-defined shells, this is	\
285144483Sharti	 * the full path of the shell.					\
286144483Sharti	 */								\
287144483Sharti	CONST char	*name;						\
288144483Sharti									\
289144483Sharti	/* True if both echoOff and echoOn defined */			\
290144483Sharti	Boolean		hasEchoCtl;					\
291144483Sharti									\
292144483Sharti	CONST char	*echoOff;	/* command to turn off echo */	\
293144483Sharti	CONST char	*echoOn;	/* command to turn it back on */\
294144483Sharti									\
295144483Sharti	/*								\
296144483Sharti	 * What the shell prints, and its length, when given the	\
297144483Sharti	 * echo-off command. This line will not be printed when		\
298144483Sharti	 * received from the shell. This is usually the command which	\
299144483Sharti	 * was executed to turn off echoing				\
300144483Sharti	 */								\
301144483Sharti	CONST char	*noPrint;					\
302144483Sharti									\
303144483Sharti	/* set if can control error checking for individual commands */	\
304144483Sharti	Boolean		hasErrCtl;					\
305144483Sharti									\
306144483Sharti	/* string to turn error checking on */				\
307144483Sharti	CONST char	*errCheck;					\
308144483Sharti									\
309144483Sharti	/* string to turn off error checking */				\
310144483Sharti	CONST char	*ignErr;					\
311144483Sharti									\
312144483Sharti	CONST char	*echo;	/* command line flag: echo commands */	\
313144483Sharti	CONST char	*exit;	/* command line flag: exit on error */	\
314144483Sharti}
315144483Sharti
316144483ShartiDEF_SHELL_STRUCT(Shell,);
317144483ShartiDEF_SHELL_STRUCT(CShell, const);
318144483Sharti
319144483Sharti/*
3208874Srgrimes * error handling variables
3211590Srgrimes */
322144467Shartistatic int	errors = 0;	/* number of errors reported */
323144467Shartistatic int	aborting = 0;	/* why is the make aborting? */
324144467Sharti#define	ABORT_ERROR	1	/* Because of an error */
325144467Sharti#define	ABORT_INTERRUPT	2	/* Because it was interrupted */
326144467Sharti#define	ABORT_WAIT	3	/* Waiting for jobs to finish */
3271590Srgrimes
32818730Ssteve/*
32918730Ssteve * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
33018730Ssteve * is a char! So when we go above 127 we turn negative!
33118730Ssteve */
332138232Sharti#define	FILENO(a) ((unsigned)fileno(a))
3331590Srgrimes
3341590Srgrimes/*
3351590Srgrimes * post-make command processing. The node postCommands is really just the
3361590Srgrimes * .END target but we keep it around to avoid having to search for it
3371590Srgrimes * all the time.
3381590Srgrimes */
339144467Shartistatic GNode	*postCommands;
3401590Srgrimes
3411590Srgrimes/*
342144467Sharti * The number of commands actually printed for a target. Should this
343144467Sharti * number be 0, no shell will be executed.
344144467Sharti */
345144467Shartistatic int	numCommands;
346144467Sharti
347144467Sharti/*
3481590Srgrimes * Return values from JobStart.
3491590Srgrimes */
350144467Sharti#define	JOB_RUNNING	0	/* Job is running */
351146061Sharti#define	JOB_ERROR	1	/* Error in starting the job */
352144467Sharti#define	JOB_FINISHED	2	/* The job is already finished */
353144467Sharti#define	JOB_STOPPED	3	/* The job is stopped */
3541590Srgrimes
3551590Srgrimes/*
3561590Srgrimes * Descriptions for various shells.
3571590Srgrimes */
358144483Shartistatic const struct CShell shells[] = {
359144467Sharti	/*
360144467Sharti	 * CSH description. The csh can do echo control by playing
361144467Sharti	 * with the setting of the 'echo' shell variable. Sadly,
362144467Sharti	 * however, it is unable to do error control nicely.
363144467Sharti	 */
364144467Sharti	{
365144467Sharti		"csh",
366144741Sharti		TRUE, "unset verbose", "set verbose", "unset verbose",
367144467Sharti		FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"",
368144467Sharti		"v", "e",
369144467Sharti	},
370144467Sharti	/*
371144467Sharti	 * SH description. Echo control is also possible and, under
372144467Sharti	 * sun UNIX anyway, one can even control error checking.
373144467Sharti	 */
374144467Sharti	{
375144467Sharti		"sh",
376144741Sharti		TRUE, "set -", "set -v", "set -",
377144467Sharti		TRUE, "set -e", "set +e",
37818730Ssteve#ifdef OLDBOURNESHELL
379144467Sharti		FALSE, "echo \"%s\"\n", "sh -c '%s || exit 0'\n",
38018730Ssteve#endif
381144467Sharti		"v", "e",
382144467Sharti	},
383144467Sharti	/*
384144467Sharti	 * KSH description. The Korn shell has a superset of
385144467Sharti	 * the Bourne shell's functionality.
386144467Sharti	 */
387144467Sharti	{
388144467Sharti		"ksh",
389144741Sharti		TRUE, "set -", "set -v", "set -",
390144467Sharti		TRUE, "set -e", "set +e",
391144467Sharti		"v", "e",
392144467Sharti	},
3931590Srgrimes};
3941590Srgrimes
395144467Sharti/*
396144467Sharti * This is the shell to which we pass all commands in the Makefile.
397144467Sharti * It is set by the Job_ParseShell function.
398144467Sharti */
399144483Shartistatic struct Shell *commandShell = NULL;
400146059Shartistatic char	*shellPath = NULL;	/* full pathname of executable image */
401146059Shartistatic char	*shellName = NULL;	/* last component of shell */
4021590Srgrimes
403146140Sharti/*
404146140Sharti * The maximum number of jobs that may run. This is initialize from the
405146140Sharti * -j argument for the leading make and from the FIFO for sub-makes.
406146140Sharti */
407146140Shartistatic int	maxJobs;
408146140Sharti
409144656Shartistatic int	nJobs;		/* The number of children currently running */
410138916Sharti
411138916Sharti/* The structures that describe them */
412144494Shartistatic struct JobList jobs = TAILQ_HEAD_INITIALIZER(jobs);
413138916Sharti
414146061Shartistatic Boolean	jobFull;	/* Flag to tell when the job table is full. It
4151590Srgrimes				 * is set TRUE when (1) the total number of
416137572Sphk				 * running jobs equals the maximum allowed */
417104475Sphk#ifdef USE_KQUEUE
418104475Sphkstatic int	kqfd;		/* File descriptor obtained by kqueue() */
419104475Sphk#else
420146061Shartistatic fd_set	outputs;	/* Set of descriptors of pipes connected to
4211590Srgrimes				 * the output channels of children */
4221590Srgrimes#endif
4231590Srgrimes
424146061Shartistatic GNode	*lastNode;	/* The node for which output was most recently
4251590Srgrimes				 * produced. */
426146061Shartistatic const char *targFmt;	/* Format string to use to head output from a
4271590Srgrimes				 * job when it's not the most-recent job heard
4281590Srgrimes				 * from */
4291590Srgrimes
430137202Sharti#define	TARG_FMT  "--- %s ---\n" /* Default format */
431137202Sharti#define	MESSAGE(fp, gn) \
432138232Sharti	 fprintf(fp, targFmt, gn->name);
43318730Ssteve
4341590Srgrimes/*
435137252Sharti * When JobStart attempts to run a job but isn't allowed to
436137252Sharti * or when Job_CatchChildren detects a job that has
437137252Sharti * been stopped somehow, the job is placed on the stoppedJobs queue to be run
4388874Srgrimes * when the next job finishes.
439138916Sharti *
440138916Sharti * Lst of Job structures describing jobs that were stopped due to
441138916Sharti * concurrency limits or externally
4421590Srgrimes */
443144494Shartistatic struct JobList stoppedJobs = TAILQ_HEAD_INITIALIZER(stoppedJobs);
4441590Srgrimes
445144656Shartistatic int	fifoFd;		/* Fd of our job fifo */
446144656Shartistatic char	fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
447144656Shartistatic int	fifoMaster;
4481590Srgrimes
449137605Shartistatic sig_atomic_t interrupted;
450137605Sharti
451137605Sharti
4521590Srgrimes#if defined(USE_PGRP) && defined(SYSV)
45318730Ssteve# define KILL(pid, sig)		killpg(-(pid), (sig))
4541590Srgrimes#else
4551590Srgrimes# if defined(USE_PGRP)
45618730Ssteve#  define KILL(pid, sig)	killpg((pid), (sig))
4571590Srgrimes# else
45818730Ssteve#  define KILL(pid, sig)	kill((pid), (sig))
4591590Srgrimes# endif
4601590Srgrimes#endif
4611590Srgrimes
46218730Ssteve/*
46318730Ssteve * Grmpf... There is no way to set bits of the wait structure
46418730Ssteve * anymore with the stupid W*() macros. I liked the union wait
46518730Ssteve * stuff much more. So, we devise our own macros... This is
46618730Ssteve * really ugly, use dramamine sparingly. You have been warned.
46718730Ssteve */
468103503Sjmallett#define	W_SETMASKED(st, val, fun)				\
46918730Ssteve	{							\
470138232Sharti		int sh = (int)~0;				\
47118730Ssteve		int mask = fun(sh);				\
47218730Ssteve								\
47318730Ssteve		for (sh = 0; ((mask >> sh) & 1) == 0; sh++)	\
47418730Ssteve			continue;				\
47518730Ssteve		*(st) = (*(st) & ~mask) | ((val) << sh);	\
47618730Ssteve	}
47718730Ssteve
478103503Sjmallett#define	W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
479103503Sjmallett#define	W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
48018730Ssteve
481146129Sharti/**
482146129Sharti * Information used to create a new process.
483146129Sharti */
484146129Shartitypedef struct ProcStuff {
485146129Sharti	int	in;	/* stdin for new process */
486146129Sharti	int	out;	/* stdout for new process */
487146129Sharti	int	err;	/* stderr for new process */
488146129Sharti
489146129Sharti	int	merge_errors;	/* true if stderr is redirected to stdin */
490146129Sharti	int	pgroup;		/* true if new process a process leader */
491146129Sharti	int	searchpath;	/* true if binary should be found via $PATH */
492146129Sharti
493146129Sharti	char	**argv;
494146130Sharti
495146130Sharti	pid_t	child_pid;
496146129Sharti} ProcStuff;
497146129Sharti
49892921Simpstatic void JobRestart(Job *);
49992921Simpstatic int JobStart(GNode *, int, Job *);
50092921Simpstatic void JobDoOutput(Job *, Boolean);
501144483Shartistatic struct Shell *JobMatchShell(const char *);
50292921Simpstatic void JobInterrupt(int, int);
50392921Simpstatic void JobRestartJobs(void);
504146129Shartistatic void ProcExec(const ProcStuff *) __dead2;
505146142Shartistatic int Compat_RunCommand(char *, struct GNode *);
5061590Srgrimes
507146132Sharti/*
508146132Sharti * The following array is used to make a fast determination of which
509146132Sharti * commands and characters are interpreted specially by the shell.
510146132Sharti * If a command is one of these or contains any of these characters,
511146132Sharti * it is executed by the shell, not directly by us.
512146132Sharti * XXX Both of these arrays should be configurable via .SHELL
513146132Sharti */
514146132Shartistatic const char const* sh_builtin[] = {
515146132Sharti	"alias", "cd", "eval", "exec",
516146132Sharti	"exit", "read", "set", "ulimit",
517146132Sharti	"unalias", "umask", "unset", "wait",
518146132Sharti	":", NULL
519146132Sharti};
520146132Shartistatic const char *sh_meta = "#=|^(){};&<>*?[]:$`\\\n";
521146132Sharti
522146132Shartistatic GNode	    *curTarg = NULL;
523146132Shartistatic GNode	    *ENDNode;
524146132Sharti
525146155Sharti/**
526146155Sharti * Create a fifo file with a uniq filename, and returns a file
527146155Sharti * descriptor to that fifo.
528146155Sharti */
529146155Shartistatic int
530146155Shartimkfifotemp(char *template)
531146155Sharti{
532146155Sharti	char *start;
533146155Sharti	char *pathend;
534146155Sharti	char *ptr;
535146155Sharti	const unsigned char padchar[] =
536146155Sharti	    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
537146155Sharti
538146155Sharti	if (template[0] == '\0') {
539146155Sharti		errno = EINVAL;	/* bad input string */
540146155Sharti		return (-1);
541146155Sharti	}
542146155Sharti
543146155Sharti	/* Find end of template string. */
544146155Sharti	pathend = strchr(template, '\0');
545146155Sharti	ptr = pathend - 1;
546146155Sharti
547146155Sharti	/*
548146155Sharti	 * Starting from the end of the template replace spaces with 'X' in
549146155Sharti	 * them with random characters until there are no more 'X'.
550146155Sharti	 */
551146155Sharti	while (ptr >= template && *ptr == 'X') {
552146155Sharti		uint32_t rand_num = arc4random() % (sizeof(padchar) - 1);
553146155Sharti		*ptr-- = padchar[rand_num];
554146155Sharti	}
555146155Sharti	start = ptr + 1;
556146155Sharti
557146155Sharti	/* Check the target directory. */
558146155Sharti	for (; ptr > template; --ptr) {
559146155Sharti		if (*ptr == '/') {
560146155Sharti			struct stat sbuf;
561146155Sharti
562146155Sharti			*ptr = '\0';
563146155Sharti			if (stat(template, &sbuf) != 0)
564146155Sharti				return (-1);
565146155Sharti
566146155Sharti			if (!S_ISDIR(sbuf.st_mode)) {
567146155Sharti				errno = ENOTDIR;
568146155Sharti				return (-1);
569146155Sharti			}
570146155Sharti			*ptr = '/';
571146155Sharti			break;
572146155Sharti		}
573146155Sharti	}
574146155Sharti
575146155Sharti	for (;;) {
576146155Sharti		if (mkfifo(template, 0600) == 0) {
577146155Sharti			int fd;
578146155Sharti
579146155Sharti			if ((fd = open(template, O_RDWR, 0600)) < 0) {
580146155Sharti				unlink(template);
581146155Sharti				return (-1);
582146155Sharti			} else {
583146155Sharti				return (fd);
584146155Sharti			}
585146155Sharti		} else {
586146155Sharti			if (errno != EEXIST) {
587146155Sharti				return (-1);
588146155Sharti			}
589146155Sharti		}
590146155Sharti
591146155Sharti		/*
592146155Sharti		 * If we have a collision, cycle through the space of
593146155Sharti		 * filenames.
594146155Sharti		 */
595146155Sharti		for (ptr = start;;) {
596146155Sharti			char *pad;
597146155Sharti
598146155Sharti			if (*ptr == '\0' || ptr == pathend)
599146155Sharti				return (-1);
600146155Sharti
601146155Sharti			pad = strchr(padchar, *ptr);
602146155Sharti			if (pad == NULL || *++pad == '\0') {
603146155Sharti				*ptr++ = padchar[0];
604146155Sharti			} else {
605146155Sharti				*ptr++ = *pad;
606146155Sharti				break;
607146155Sharti			}
608146155Sharti		}
609146155Sharti	}
610146155Sharti	/*NOTREACHED*/
611146155Sharti}
612146155Sharti
613146144Shartistatic void
614146144Sharticatch_child(int sig __unused)
615146144Sharti{
616146144Sharti}
617146144Sharti
618144467Sharti/**
619146144Sharti */
620146144Shartivoid
621146144ShartiProc_Init()
622146144Sharti{
623146144Sharti	/*
624146144Sharti	 * Catch SIGCHLD so that we get kicked out of select() when we
625146144Sharti	 * need to look at a child.  This is only known to matter for the
626146144Sharti	 * -j case (perhaps without -P).
627146144Sharti	 *
628146144Sharti	 * XXX this is intentionally misplaced.
629146144Sharti	 */
630146144Sharti	struct sigaction sa;
631146144Sharti
632146144Sharti	sigemptyset(&sa.sa_mask);
633146144Sharti	sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
634146144Sharti	sa.sa_handler = catch_child;
635146144Sharti	sigaction(SIGCHLD, &sa, NULL);
636146144Sharti
637146144Sharti#if DEFSHELL == 2
638146144Sharti	/*
639146144Sharti	 * Turn off ENV to make ksh happier.
640146144Sharti	 */
641146144Sharti	unsetenv("ENV");
642146144Sharti#endif
643146144Sharti}
644146144Sharti
645146144Sharti/**
646146129Sharti * Replace the current process.
647146129Sharti */
648146129Shartistatic void
649146129ShartiProcExec(const ProcStuff *ps)
650146129Sharti{
651146129Sharti
652146129Sharti	if (ps->in != STDIN_FILENO) {
653146129Sharti		/*
654146129Sharti		 * Redirect the child's stdin to the input fd
655146129Sharti		 * and reset it to the beginning (again).
656146129Sharti		 */
657146129Sharti		if (dup2(ps->in, STDIN_FILENO) == -1)
658146129Sharti			Punt("Cannot dup2: %s", strerror(errno));
659146129Sharti		lseek(STDIN_FILENO, (off_t)0, SEEK_SET);
660146129Sharti	}
661146129Sharti
662146129Sharti	if (ps->out != STDOUT_FILENO) {
663146129Sharti		/*
664146129Sharti		 * Redirect the child's stdout to the output fd.
665146129Sharti		 */
666146129Sharti		if (dup2(ps->out, STDOUT_FILENO) == -1)
667146129Sharti			Punt("Cannot dup2: %s", strerror(errno));
668146129Sharti		close(ps->out);
669146129Sharti	}
670146129Sharti
671146129Sharti	if (ps->err != STDERR_FILENO) {
672146129Sharti		/*
673146129Sharti		 * Redirect the child's stderr to the err fd.
674146129Sharti		 */
675146129Sharti		if (dup2(ps->err, STDERR_FILENO) == -1)
676146129Sharti			Punt("Cannot dup2: %s", strerror(errno));
677146129Sharti		close(ps->err);
678146129Sharti	}
679146129Sharti
680146129Sharti	if (ps->merge_errors) {
681146129Sharti		/*
682146129Sharti		 * Send stderr to parent process too.
683146129Sharti		 */
684146129Sharti		if (dup2(STDOUT_FILENO, STDERR_FILENO) == -1)
685146129Sharti			Punt("Cannot dup2: %s", strerror(errno));
686146129Sharti	}
687146129Sharti
688146129Sharti	/*
689146129Sharti	 * The file descriptors for stdin, stdout, or stderr might
690146129Sharti	 * have been marked close-on-exec.  Clear the flag on all
691146129Sharti	 * of them.
692146129Sharti	 */
693146129Sharti	fcntl(STDIN_FILENO, F_SETFD,
694146129Sharti	    fcntl(STDIN_FILENO, F_GETFD) & (~FD_CLOEXEC));
695146129Sharti	fcntl(STDOUT_FILENO, F_SETFD,
696146129Sharti	    fcntl(STDOUT_FILENO, F_GETFD) & (~FD_CLOEXEC));
697146129Sharti	fcntl(STDERR_FILENO, F_SETFD,
698146129Sharti	    fcntl(STDERR_FILENO, F_GETFD) & (~FD_CLOEXEC));
699146129Sharti
700146129Sharti	if (ps->pgroup) {
701146129Sharti#ifdef USE_PGRP
702146129Sharti		/*
703146129Sharti		 * Become a process group leader, so we can kill it and all
704146129Sharti		 * its descendants in one fell swoop, by killing its process
705146129Sharti		 * family, but not commit suicide.
706146129Sharti		 */
707146129Sharti#if defined(SYSV)
708146129Sharti		setsid();
709146129Sharti#else
710146129Sharti		setpgid(0, getpid());
711146129Sharti#endif
712146129Sharti#endif /* USE_PGRP */
713146129Sharti	}
714146129Sharti
715146129Sharti	if (ps->searchpath) {
716146129Sharti		execvp(ps->argv[0], ps->argv);
717146129Sharti
718146129Sharti		write(STDERR_FILENO, ps->argv[0], strlen(ps->argv[0]));
719146129Sharti		write(STDERR_FILENO, ":", 1);
720146129Sharti		write(STDERR_FILENO, strerror(errno), strlen(strerror(errno)));
721146129Sharti		write(STDERR_FILENO, "\n", 1);
722146129Sharti	} else {
723146129Sharti		execv(shellPath, ps->argv);
724146129Sharti
725146129Sharti		write(STDERR_FILENO,
726146129Sharti		      "Could not execute shell\n",
727146129Sharti		      sizeof("Could not execute shell"));
728146129Sharti	}
729146129Sharti
730146129Sharti	/*
731146129Sharti	 * Since we are the child process, exit without flushing buffers.
732146129Sharti	 */
733146129Sharti	_exit(1);
734146129Sharti	/* NOTREACHED */
735146129Sharti}
736146129Sharti
737146129Sharti/**
738146131Sharti * Wait for child process to terminate.
739146130Sharti */
740146130Shartistatic int
741146130ShartiProcWait(ProcStuff *ps)
742146130Sharti{
743146130Sharti	pid_t	pid;
744146130Sharti	int	status;
745146130Sharti
746146130Sharti	/*
747146130Sharti	 * Wait for the process to exit.
748146130Sharti	 */
749146131Sharti	for (;;) {
750146131Sharti		pid = wait(&status);
751146131Sharti		if (pid == -1 && errno != EINTR) {
752146131Sharti			Fatal("error in wait: %d", pid);
753146131Sharti			/* NOTREACHED */
754146131Sharti		}
755146131Sharti		if (pid == ps->child_pid) {
756146131Sharti			break;
757146131Sharti		}
758146131Sharti		if (interrupted) {
759146131Sharti			break;
760146131Sharti		}
761146130Sharti	}
762146130Sharti
763146130Sharti	return (status);
764146130Sharti}
765146130Sharti
766146130Sharti/**
767137605Sharti * JobCatchSignal
768144467Sharti *	Got a signal. Set global variables and hope that someone will
769144467Sharti *	handle it.
770137605Sharti */
771137605Shartistatic void
772137605ShartiJobCatchSig(int signo)
773137605Sharti{
774137605Sharti
775137605Sharti	interrupted = signo;
776137605Sharti}
777137605Sharti
778144467Sharti/**
7791590Srgrimes * JobPassSig --
780137252Sharti *	Pass a signal on to all local jobs if
7811590Srgrimes *	USE_PGRP is defined, then die ourselves.
7821590Srgrimes *
7831590Srgrimes * Side Effects:
7841590Srgrimes *	We die by the same signal.
7851590Srgrimes */
7861590Srgrimesstatic void
787104696SjmallettJobPassSig(int signo)
7881590Srgrimes{
789144741Sharti	Job	*job;
790144467Sharti	sigset_t nmask, omask;
791144467Sharti	struct sigaction act;
7928874Srgrimes
793144467Sharti	sigemptyset(&nmask);
794144467Sharti	sigaddset(&nmask, signo);
795144467Sharti	sigprocmask(SIG_SETMASK, &nmask, &omask);
796137605Sharti
797144467Sharti	DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
798144741Sharti	TAILQ_FOREACH(job, &jobs, link) {
799144741Sharti		DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
800144741Sharti		    signo, (intmax_t)job->pid));
801144741Sharti		KILL(job->pid, signo);
802144741Sharti	}
8031590Srgrimes
804144467Sharti	/*
805144467Sharti	 * Deal with proper cleanup based on the signal received. We only run
806144467Sharti	 * the .INTERRUPT target if the signal was in fact an interrupt.
807144467Sharti	 * The other three termination signals are more of a "get out *now*"
808144467Sharti	 * command.
809144467Sharti	 */
810144467Sharti	if (signo == SIGINT) {
811144467Sharti		JobInterrupt(TRUE, signo);
812144657Sharti	} else if (signo == SIGHUP || signo == SIGTERM || signo == SIGQUIT) {
813144467Sharti		JobInterrupt(FALSE, signo);
814144467Sharti	}
8158874Srgrimes
816144467Sharti	/*
817144467Sharti	 * Leave gracefully if SIGQUIT, rather than core dumping.
818144467Sharti	 */
819144467Sharti	if (signo == SIGQUIT) {
820144467Sharti		signo = SIGINT;
821144467Sharti	}
8228874Srgrimes
823144467Sharti	/*
824144467Sharti	 * Send ourselves the signal now we've given the message to everyone
825144467Sharti	 * else. Note we block everything else possible while we're getting
826144467Sharti	 * the signal. This ensures that all our jobs get continued when we
827144467Sharti	 * wake up before we take any other signal.
828144467Sharti	 * XXX this comment seems wrong.
829144467Sharti	 */
830144467Sharti	act.sa_handler = SIG_DFL;
831144467Sharti	sigemptyset(&act.sa_mask);
832144467Sharti	act.sa_flags = 0;
833144467Sharti	sigaction(signo, &act, NULL);
8341590Srgrimes
835144467Sharti	DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
836144467Sharti	    ~0 & ~(1 << (signo - 1))));
837144467Sharti	signal(signo, SIG_DFL);
8381590Srgrimes
839144467Sharti	KILL(getpid(), signo);
84018730Ssteve
841144467Sharti	signo = SIGCONT;
842144741Sharti	TAILQ_FOREACH(job, &jobs, link) {
843144741Sharti		DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
844144741Sharti		    signo, (intmax_t)job->pid));
845144741Sharti		KILL(job->pid, signo);
846144741Sharti	}
8471590Srgrimes
848144467Sharti	sigprocmask(SIG_SETMASK, &omask, NULL);
849144467Sharti	sigprocmask(SIG_SETMASK, &omask, NULL);
850144467Sharti	act.sa_handler = JobPassSig;
851144467Sharti	sigaction(signo, &act, NULL);
8521590Srgrimes}
8531590Srgrimes
854144467Sharti/**
8551590Srgrimes * JobPrintCommand  --
8561590Srgrimes *	Put out another command for the given job. If the command starts
8571590Srgrimes *	with an @ or a - we process it specially. In the former case,
8581590Srgrimes *	so long as the -s and -n flags weren't given to make, we stick
8591590Srgrimes *	a shell-specific echoOff command in the script. In the latter,
8601590Srgrimes *	we ignore errors for the entire job, unless the shell has error
8611590Srgrimes *	control.
8621590Srgrimes *	If the command is just "..." we take all future commands for this
8631590Srgrimes *	job to be commands to be executed once the entire graph has been
8641590Srgrimes *	made and return non-zero to signal that the end of the commands
8651590Srgrimes *	was reached. These commands are later attached to the postCommands
86694594Sobrien *	node and executed by Job_Finish when all things are done.
867142993Sharti *	This function is called from JobStart via LST_FOREACH.
8681590Srgrimes *
8691590Srgrimes * Results:
8701590Srgrimes *	Always 0, unless the command was "..."
8711590Srgrimes *
8721590Srgrimes * Side Effects:
8731590Srgrimes *	If the command begins with a '-' and the shell has no error control,
8741590Srgrimes *	the JOB_IGNERR flag is set in the job descriptor.
8751590Srgrimes *	If the command is "..." and we're not ignoring such things,
8761590Srgrimes *	tailCmds is set to the successor node of the cmd.
8771590Srgrimes *	numCommands is incremented if the command is actually printed.
8781590Srgrimes */
8791590Srgrimesstatic int
880144741ShartiJobPrintCommand(char *cmd, Job *job)
8811590Srgrimes{
882144467Sharti	Boolean	noSpecials;	/* true if we shouldn't worry about
883141258Sharti				 * inserting special commands into
884141258Sharti				 * the input stream. */
885144467Sharti	Boolean	shutUp = FALSE;	/* true if we put a no echo command
886141258Sharti				 * into the command file */
887144467Sharti	Boolean	errOff = FALSE;	/* true if we turned error checking
888141258Sharti				 * off before printing the command
889141258Sharti				 * and need to turn it back on */
890144467Sharti	const char *cmdTemplate;/* Template to use when printing the command */
891144467Sharti	char	*cmdStart;	/* Start of expanded command */
892144467Sharti	LstNode	*cmdNode;	/* Node for replacing the command */
8931590Srgrimes
894144467Sharti	noSpecials = (noExecute && !(job->node->type & OP_MAKE));
8951590Srgrimes
896144467Sharti	if (strcmp(cmd, "...") == 0) {
897144467Sharti		job->node->type |= OP_SAVE_CMDS;
898144467Sharti		if ((job->flags & JOB_IGNDOTS) == 0) {
899144467Sharti			job->tailCmds =
900144467Sharti			    Lst_Succ(Lst_Member(&job->node->commands, cmd));
901144467Sharti			return (1);
902144467Sharti		}
903144467Sharti		return (0);
9041590Srgrimes	}
9051590Srgrimes
906144467Sharti#define	DBPRINTF(fmt, arg)			\
907144467Sharti	DEBUGF(JOB, (fmt, arg));		\
908144467Sharti	fprintf(job->cmdFILE, fmt, arg);	\
909144467Sharti	fflush(job->cmdFILE);
9101590Srgrimes
911144467Sharti	numCommands += 1;
9121590Srgrimes
913144467Sharti	/*
914144467Sharti	 * For debugging, we replace each command with the result of expanding
915144467Sharti	 * the variables in the command.
916144467Sharti	 */
917144467Sharti	cmdNode = Lst_Member(&job->node->commands, cmd);
918142457Sharti
919146027Sharti	cmd = Buf_Peel(Var_Subst(cmd, job->node, FALSE));
920144467Sharti	cmdStart = cmd;
921142457Sharti
922144467Sharti	Lst_Replace(cmdNode, cmdStart);
9231590Srgrimes
924144467Sharti	cmdTemplate = "%s\n";
9251590Srgrimes
926144467Sharti	/*
927144467Sharti	 * Check for leading @', -' or +'s to control echoing, error checking,
928144467Sharti	 * and execution on -n.
929144467Sharti	 */
930144467Sharti	while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
931144467Sharti		switch (*cmd) {
932132839Sharti
933144467Sharti		  case '@':
934144467Sharti			shutUp = DEBUG(LOUD) ? FALSE : TRUE;
935144467Sharti			break;
936132839Sharti
937144467Sharti		  case '-':
938144467Sharti			errOff = TRUE;
939144467Sharti			break;
940132839Sharti
941144467Sharti		  case '+':
942144467Sharti			if (noSpecials) {
943144467Sharti				/*
944144467Sharti				 * We're not actually exececuting anything...
945144467Sharti				 * but this one needs to be - use compat mode
946144467Sharti				 * just for it.
947144467Sharti				 */
948144741Sharti				Compat_RunCommand(cmd, job->node);
949144467Sharti				return (0);
950144467Sharti			}
951144467Sharti			break;
952144467Sharti		}
953144467Sharti		cmd++;
9541590Srgrimes	}
9551590Srgrimes
956144467Sharti	while (isspace((unsigned char)*cmd))
957144467Sharti		cmd++;
9581590Srgrimes
959144467Sharti	if (shutUp) {
960144467Sharti		if (!(job->flags & JOB_SILENT) && !noSpecials &&
9611590Srgrimes		    commandShell->hasEchoCtl) {
96218730Ssteve			DBPRINTF("%s\n", commandShell->echoOff);
9631590Srgrimes		} else {
964144467Sharti			shutUp = FALSE;
9651590Srgrimes		}
966144467Sharti	}
967144467Sharti
968144467Sharti	if (errOff) {
969144467Sharti		if (!(job->flags & JOB_IGNERR) && !noSpecials) {
970144467Sharti			if (commandShell->hasErrCtl) {
971144467Sharti				/*
972144467Sharti				 * We don't want the error-control commands
973144467Sharti				 * showing up either, so we turn off echoing
974144467Sharti				 * while executing them. We could put another
975144467Sharti				 * field in the shell structure to tell
976144467Sharti				 * JobDoOutput to look for this string too,
977144467Sharti				 * but why make it any more complex than
978144467Sharti				 * it already is?
979144467Sharti				 */
980144467Sharti				if (!(job->flags & JOB_SILENT) && !shutUp &&
981144467Sharti				    commandShell->hasEchoCtl) {
982144467Sharti					DBPRINTF("%s\n", commandShell->echoOff);
983144467Sharti					DBPRINTF("%s\n", commandShell->ignErr);
984144467Sharti					DBPRINTF("%s\n", commandShell->echoOn);
985144467Sharti				} else {
986144467Sharti					DBPRINTF("%s\n", commandShell->ignErr);
987144467Sharti				}
988144467Sharti			} else if (commandShell->ignErr &&
989144657Sharti			    *commandShell->ignErr != '\0') {
990144467Sharti				/*
991144467Sharti				 * The shell has no error control, so we need to
992144467Sharti				 * be weird to get it to ignore any errors from
993144467Sharti				 * the command. If echoing is turned on, we turn
994144467Sharti				 * it off and use the errCheck template to echo
995144467Sharti				 * the command. Leave echoing off so the user
996144467Sharti				 * doesn't see the weirdness we go through to
997144467Sharti				 * ignore errors. Set cmdTemplate to use the
998144467Sharti				 * weirdness instead of the simple "%s\n"
999144467Sharti				 * template.
1000144467Sharti				 */
1001144467Sharti				if (!(job->flags & JOB_SILENT) && !shutUp &&
1002144467Sharti				    commandShell->hasEchoCtl) {
1003144467Sharti					DBPRINTF("%s\n", commandShell->echoOff);
1004144467Sharti					DBPRINTF(commandShell->errCheck, cmd);
1005144467Sharti					shutUp = TRUE;
1006144467Sharti				}
1007144467Sharti				cmdTemplate = commandShell->ignErr;
1008144467Sharti				/*
1009144467Sharti				 * The error ignoration (hee hee) is already
1010144467Sharti				 * taken care of by the ignErr template, so
1011144467Sharti				 * pretend error checking is still on.
1012144467Sharti				*/
1013144467Sharti				errOff = FALSE;
1014144467Sharti			} else {
1015144467Sharti				errOff = FALSE;
1016144467Sharti			}
1017144467Sharti		} else {
1018144467Sharti			errOff = FALSE;
1019144467Sharti		}
1020144467Sharti	}
1021144467Sharti
1022144467Sharti	DBPRINTF(cmdTemplate, cmd);
1023144467Sharti
1024144467Sharti	if (errOff) {
10251590Srgrimes		/*
1026144467Sharti		 * If echoing is already off, there's no point in issuing the
1027144467Sharti		 * echoOff command. Otherwise we issue it and pretend it was on
1028144467Sharti		 * for the whole command...
10291590Srgrimes		 */
1030144467Sharti		if (!shutUp && !(job->flags & JOB_SILENT) &&
10311590Srgrimes		    commandShell->hasEchoCtl) {
103218730Ssteve			DBPRINTF("%s\n", commandShell->echoOff);
10331590Srgrimes			shutUp = TRUE;
10341590Srgrimes		}
1035144467Sharti		DBPRINTF("%s\n", commandShell->errCheck);
10361590Srgrimes	}
1037144467Sharti	if (shutUp) {
1038144467Sharti		DBPRINTF("%s\n", commandShell->echoOn);
10391590Srgrimes	}
1040144467Sharti	return (0);
10411590Srgrimes}
10421590Srgrimes
1043144467Sharti/**
104418730Ssteve * JobClose --
104518730Ssteve *	Called to close both input and output pipes when a job is finished.
104618730Ssteve *
104718730Ssteve * Side Effects:
104818730Ssteve *	The file descriptors associated with the job are closed.
104918730Ssteve */
105018730Sstevestatic void
1051104696SjmallettJobClose(Job *job)
105218730Ssteve{
1053138232Sharti
1054144467Sharti	if (usePipes) {
1055137202Sharti#if !defined(USE_KQUEUE)
1056144467Sharti		FD_CLR(job->inPipe, &outputs);
105718730Ssteve#endif
1058144467Sharti		if (job->outPipe != job->inPipe) {
1059144467Sharti			close(job->outPipe);
1060144467Sharti		}
1061144467Sharti		JobDoOutput(job, TRUE);
1062144467Sharti		close(job->inPipe);
1063144467Sharti	} else {
1064144467Sharti		close(job->outFd);
1065144467Sharti		JobDoOutput(job, TRUE);
106618730Ssteve	}
106718730Ssteve}
106818730Ssteve
1069144467Sharti/**
10701590Srgrimes * JobFinish  --
10711590Srgrimes *	Do final processing for the given job including updating
10721590Srgrimes *	parents and starting new jobs as available/necessary. Note
10731590Srgrimes *	that we pay no attention to the JOB_IGNERR flag here.
10741590Srgrimes *	This is because when we're called because of a noexecute flag
10751590Srgrimes *	or something, jstat.w_status is 0 and when called from
10761590Srgrimes *	Job_CatchChildren, the status is zeroed if it s/b ignored.
10771590Srgrimes *
10781590Srgrimes * Side Effects:
10791590Srgrimes *	Some nodes may be put on the toBeMade queue.
10801590Srgrimes *	Final commands for the job are placed on postCommands.
10811590Srgrimes *
10821590Srgrimes *	If we got an error and are aborting (aborting == ABORT_ERROR) and
10831590Srgrimes *	the job list is now empty, we are done for the day.
10841590Srgrimes *	If we recognized an error (errors !=0), we set the aborting flag
10851590Srgrimes *	to ABORT_ERROR so no more jobs will be started.
10861590Srgrimes */
10871590Srgrimesstatic void
1088104696SjmallettJobFinish(Job *job, int *status)
10891590Srgrimes{
1090144467Sharti	Boolean	done;
1091144467Sharti	LstNode	*ln;
10921590Srgrimes
1093146133Sharti	if (WIFEXITED(*status)) {
1094146133Sharti		int	job_status = WEXITSTATUS(*status);
1095146133Sharti
1096144467Sharti		JobClose(job);
1097144467Sharti		/*
1098146133Sharti		 * Deal with ignored errors in -B mode. We need to
1099146133Sharti		 * print a message telling of the ignored error as
1100146133Sharti		 * well as setting status.w_status to 0 so the next
1101146133Sharti		 * command gets run. To do this, we set done to be
1102146133Sharti		 * TRUE if in -B mode and the job exited non-zero.
1103144467Sharti		 */
1104146133Sharti		if (job_status == 0) {
1105146133Sharti			done = FALSE;
1106146133Sharti		} else {
1107146133Sharti			if (job->flags & JOB_IGNERR) {
1108146133Sharti				done = TRUE;
1109146133Sharti			} else {
1110146133Sharti				/*
1111146133Sharti				 * If it exited non-zero and either we're
1112146133Sharti				 * doing things our way or we're not ignoring
1113146133Sharti				 * errors, the job is finished. Similarly, if
1114146133Sharti				 * the shell died because of a signal the job
1115146133Sharti				 * is also finished. In these cases, finish
1116146133Sharti				 * out the job's output before printing the
1117146133Sharti				 * exit status...
1118146133Sharti				 */
1119146133Sharti				done = TRUE;
1120146133Sharti				if (job->cmdFILE != NULL &&
1121146133Sharti				    job->cmdFILE != stdout) {
1122146133Sharti					fclose(job->cmdFILE);
1123146133Sharti				}
11248874Srgrimes
1125146133Sharti			}
1126146133Sharti		}
1127146133Sharti	} else if (WIFSIGNALED(*status)) {
1128146133Sharti		if (WTERMSIG(*status) == SIGCONT) {
1129146133Sharti			/*
1130146133Sharti			 * No need to close things down or anything.
1131146133Sharti			 */
1132146133Sharti			done = FALSE;
1133146133Sharti		} else {
1134146133Sharti			/*
1135146133Sharti			 * If it exited non-zero and either we're
1136146133Sharti			 * doing things our way or we're not ignoring
1137146133Sharti			 * errors, the job is finished. Similarly, if
1138146133Sharti			 * the shell died because of a signal the job
1139146133Sharti			 * is also finished. In these cases, finish
1140146133Sharti			 * out the job's output before printing the
1141146133Sharti			 * exit status...
1142146133Sharti			 */
1143146133Sharti			JobClose(job);
1144146133Sharti			if (job->cmdFILE != NULL &&
1145146133Sharti			    job->cmdFILE != stdout) {
1146146133Sharti				fclose(job->cmdFILE);
1147146133Sharti			}
1148146133Sharti			done = TRUE;
1149146133Sharti		}
11501590Srgrimes	} else {
1151144467Sharti		/*
1152144467Sharti		 * No need to close things down or anything.
1153144467Sharti		 */
1154144467Sharti		done = FALSE;
11551590Srgrimes	}
11561590Srgrimes
1157146133Sharti	if (WIFEXITED(*status)) {
1158146133Sharti		if (done || DEBUG(JOB)) {
1159146133Sharti			FILE   *out;
1160144467Sharti
1161146133Sharti			if (compatMake &&
1162146133Sharti			    !usePipes &&
1163146133Sharti			    (job->flags & JOB_IGNERR)) {
1164146133Sharti				/*
1165146133Sharti				 * If output is going to a file and this job
1166146133Sharti				 * is ignoring errors, arrange to have the
1167146133Sharti				 * exit status sent to the output file as
1168146133Sharti				 * well.
1169146133Sharti				 */
1170146133Sharti				out = fdopen(job->outFd, "w");
1171146133Sharti				if (out == NULL)
1172146133Sharti					Punt("Cannot fdopen");
1173146133Sharti			} else {
1174146133Sharti				out = stdout;
1175146133Sharti			}
11761590Srgrimes
1177144665Sharti			DEBUGF(JOB, ("Process %jd exited.\n",
1178144665Sharti			    (intmax_t)job->pid));
1179146133Sharti
1180146133Sharti			if (WEXITSTATUS(*status) == 0) {
1181146133Sharti				if (DEBUG(JOB)) {
1182146133Sharti					if (usePipes && job->node != lastNode) {
1183146133Sharti						MESSAGE(out, job->node);
1184146133Sharti						lastNode = job->node;
1185146133Sharti					}
1186146133Sharti					fprintf(out,
1187146133Sharti					    "*** Completed successfully\n");
1188146133Sharti				}
1189146133Sharti			} else {
1190144467Sharti				if (usePipes && job->node != lastNode) {
1191144467Sharti					MESSAGE(out, job->node);
1192144467Sharti					lastNode = job->node;
1193144467Sharti				}
1194144467Sharti				fprintf(out, "*** Error code %d%s\n",
1195146133Sharti					WEXITSTATUS(*status),
1196146133Sharti					(job->flags & JOB_IGNERR) ?
1197146133Sharti					"(ignored)" : "");
1198144467Sharti
1199144467Sharti				if (job->flags & JOB_IGNERR) {
1200144467Sharti					*status = 0;
1201144467Sharti				}
1202144467Sharti			}
1203144467Sharti
1204144467Sharti			fflush(out);
1205146133Sharti		}
1206146133Sharti	} else if (WIFSIGNALED(*status)) {
1207146133Sharti		if (done || DEBUG(JOB) || (WTERMSIG(*status) == SIGCONT)) {
1208146133Sharti			FILE   *out;
1209144467Sharti
1210146133Sharti			if (compatMake &&
1211146133Sharti			    !usePipes &&
1212146133Sharti			    (job->flags & JOB_IGNERR)) {
1213146133Sharti				/*
1214146133Sharti				 * If output is going to a file and this job
1215146133Sharti				 * is ignoring errors, arrange to have the
1216146133Sharti				 * exit status sent to the output file as
1217146133Sharti				 * well.
1218146133Sharti				 */
1219146133Sharti				out = fdopen(job->outFd, "w");
1220146133Sharti				if (out == NULL)
1221146133Sharti					Punt("Cannot fdopen");
1222146133Sharti			} else {
1223146133Sharti				out = stdout;
1224146133Sharti			}
1225146133Sharti
1226146133Sharti			if (WTERMSIG(*status) == SIGCONT) {
1227146133Sharti				/*
1228146133Sharti				 * If the beastie has continued, shift the
1229146133Sharti				 * Job from the stopped list to the running
1230146133Sharti				 * one (or re-stop it if concurrency is
1231146133Sharti				 * exceeded) and go and get another child.
1232146133Sharti				 */
1233146133Sharti				if (job->flags & (JOB_RESUME | JOB_RESTART)) {
1234146133Sharti					if (usePipes && job->node != lastNode) {
1235146133Sharti						MESSAGE(out, job->node);
1236146133Sharti						lastNode = job->node;
1237146133Sharti					}
1238146133Sharti					fprintf(out, "*** Continued\n");
1239146133Sharti				}
1240146133Sharti				if (!(job->flags & JOB_CONTINUING)) {
1241146133Sharti					DEBUGF(JOB, ("Warning: process %jd was not "
1242146133Sharti						     "continuing.\n", (intmax_t) job->pid));
1243146133Sharti#ifdef notdef
1244146133Sharti					/*
1245146133Sharti					 * We don't really want to restart a
1246146133Sharti					 * job from scratch just because it
1247146133Sharti					 * continued, especially not without
1248146133Sharti					 * killing the continuing process!
1249146133Sharti					 * That's why this is ifdef'ed out.
1250146133Sharti					 * FD - 9/17/90
1251146133Sharti					 */
1252146133Sharti					JobRestart(job);
1253146133Sharti#endif
1254146133Sharti				}
1255146133Sharti				job->flags &= ~JOB_CONTINUING;
1256146133Sharti				TAILQ_INSERT_TAIL(&jobs, job, link);
1257146133Sharti				nJobs += 1;
1258146133Sharti				DEBUGF(JOB, ("Process %jd is continuing locally.\n",
1259146133Sharti					     (intmax_t) job->pid));
1260146133Sharti				if (nJobs == maxJobs) {
1261146133Sharti					jobFull = TRUE;
1262146133Sharti					DEBUGF(JOB, ("Job queue is full.\n"));
1263146133Sharti				}
1264146133Sharti				fflush(out);
1265146133Sharti				return;
1266146133Sharti
1267146133Sharti			} else {
1268144467Sharti				if (usePipes && job->node != lastNode) {
1269144467Sharti					MESSAGE(out, job->node);
1270144467Sharti					lastNode = job->node;
1271144467Sharti				}
1272146133Sharti				fprintf(out,
1273146133Sharti				    "*** Signal %d\n", WTERMSIG(*status));
1274146133Sharti				fflush(out);
1275144467Sharti			}
1276146133Sharti		}
1277146133Sharti	} else {
1278146133Sharti		/* STOPPED */
1279146133Sharti		FILE   *out;
12801590Srgrimes
1281146133Sharti		if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
1282146133Sharti			/*
1283146133Sharti			 * If output is going to a file and this job
1284146133Sharti			 * is ignoring errors, arrange to have the
1285146133Sharti			 * exit status sent to the output file as
1286146133Sharti			 * well.
1287146133Sharti			 */
1288146133Sharti			out = fdopen(job->outFd, "w");
1289146133Sharti			if (out == NULL)
1290146133Sharti				Punt("Cannot fdopen");
1291144467Sharti		} else {
1292146133Sharti			out = stdout;
1293144467Sharti		}
12941590Srgrimes
1295146133Sharti		DEBUGF(JOB, ("Process %jd stopped.\n", (intmax_t) job->pid));
1296146133Sharti		if (usePipes && job->node != lastNode) {
1297146133Sharti			MESSAGE(out, job->node);
1298146133Sharti			lastNode = job->node;
1299146133Sharti		}
1300146133Sharti		fprintf(out, "*** Stopped -- signal %d\n", WSTOPSIG(*status));
1301146133Sharti		job->flags |= JOB_RESUME;
1302146133Sharti		TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1303144467Sharti		fflush(out);
1304146133Sharti		return;
13051590Srgrimes	}
13061590Srgrimes
13071590Srgrimes	/*
1308144467Sharti	 * Now handle the -B-mode stuff. If the beast still isn't finished,
1309144467Sharti	 * try and restart the job on the next command. If JobStart says it's
1310144467Sharti	 * ok, it's ok. If there's an error, this puppy is done.
13111590Srgrimes	 */
1312144467Sharti	if (compatMake && WIFEXITED(*status) &&
1313144467Sharti	    Lst_Succ(job->node->compat_command) != NULL) {
1314144467Sharti		switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
1315144467Sharti		  case JOB_RUNNING:
1316144467Sharti			done = FALSE;
1317144467Sharti			break;
1318144467Sharti		  case JOB_ERROR:
1319144467Sharti			done = TRUE;
1320144467Sharti			W_SETEXITSTATUS(status, 1);
1321144467Sharti			break;
1322144467Sharti		  case JOB_FINISHED:
1323144467Sharti			/*
1324144467Sharti			 * If we got back a JOB_FINISHED code, JobStart has
1325144467Sharti			 * already called Make_Update and freed the job
1326144467Sharti			 * descriptor. We set done to false here to avoid fake
1327144467Sharti			 * cycles and double frees. JobStart needs to do the
1328144467Sharti			 * update so we can proceed up the graph when given
1329144467Sharti			 * the -n flag..
1330144467Sharti			 */
1331144467Sharti			done = FALSE;
1332144467Sharti			break;
1333144467Sharti		  default:
1334144467Sharti			break;
1335144467Sharti		}
1336144467Sharti	} else {
1337144467Sharti		done = TRUE;
13381590Srgrimes	}
1339143703Sharti
1340144657Sharti	if (done && aborting != ABORT_ERROR &&
1341144657Sharti	    aborting != ABORT_INTERRUPT && *status == 0) {
1342144467Sharti		/*
1343144467Sharti		 * As long as we aren't aborting and the job didn't return a
1344144467Sharti		 * non-zero status that we shouldn't ignore, we call
1345144467Sharti		 * Make_Update to update the parents. In addition, any saved
1346144467Sharti		 * commands for the node are placed on the .END target.
1347144467Sharti		 */
1348144467Sharti		for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
1349144467Sharti			Lst_AtEnd(&postCommands->commands,
1350146027Sharti			    Buf_Peel(
1351146027Sharti				Var_Subst(Lst_Datum(ln), job->node, FALSE)));
1352144467Sharti		}
13531590Srgrimes
1354144467Sharti		job->node->made = MADE;
1355144467Sharti		Make_Update(job->node);
1356144467Sharti		free(job);
13571590Srgrimes
1358144467Sharti	} else if (*status != 0) {
1359144467Sharti		errors += 1;
1360144467Sharti		free(job);
1361144467Sharti	}
1362144467Sharti
1363144467Sharti	JobRestartJobs();
1364144467Sharti
13651590Srgrimes	/*
1366144467Sharti	 * Set aborting if any error.
13671590Srgrimes	 */
1368144657Sharti	if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
1369144467Sharti		/*
1370144467Sharti		 * If we found any errors in this batch of children and the -k
1371144467Sharti		 * flag wasn't given, we set the aborting flag so no more jobs
1372144467Sharti		 * get started.
1373144467Sharti		 */
1374144467Sharti		aborting = ABORT_ERROR;
1375144467Sharti	}
13768874Srgrimes
1377144657Sharti	if (aborting == ABORT_ERROR && Job_Empty()) {
1378144467Sharti		/*
1379144467Sharti		 * If we are aborting and the job table is now empty, we finish.
1380144467Sharti		 */
1381144467Sharti		Finish(errors);
1382144467Sharti	}
13831590Srgrimes}
13841590Srgrimes
1385144467Sharti/**
1386144467Sharti * Job_Touch
13871590Srgrimes *	Touch the given target. Called by JobStart when the -t flag was
1388104696Sjmallett *	given.  Prints messages unless told to be silent.
13891590Srgrimes *
13901590Srgrimes * Side Effects:
13911590Srgrimes *	The data modification of the file is changed. In addition, if the
13921590Srgrimes *	file did not exist, it is created.
13931590Srgrimes */
13941590Srgrimesvoid
1395104696SjmallettJob_Touch(GNode *gn, Boolean silent)
13961590Srgrimes{
1397144467Sharti	int	streamID;	/* ID of stream opened to do the touch */
1398144467Sharti	struct utimbuf times;	/* Times for utime() call */
13991590Srgrimes
1400144467Sharti	if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
1401144467Sharti		/*
1402144467Sharti		 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
1403144467Sharti		 * targets and, as such, shouldn't really be created.
1404144467Sharti		 */
1405144467Sharti		return;
1406144467Sharti	}
14078874Srgrimes
1408144467Sharti	if (!silent) {
1409144467Sharti		fprintf(stdout, "touch %s\n", gn->name);
1410144467Sharti		fflush(stdout);
1411144467Sharti	}
14121590Srgrimes
1413144467Sharti	if (noExecute) {
1414144467Sharti		return;
1415144467Sharti	}
14161590Srgrimes
1417144467Sharti	if (gn->type & OP_ARCHV) {
1418144467Sharti		Arch_Touch(gn);
1419144467Sharti	} else if (gn->type & OP_LIB) {
1420144467Sharti		Arch_TouchLib(gn);
1421144467Sharti	} else {
1422144467Sharti		char	*file = gn->path ? gn->path : gn->name;
14231590Srgrimes
1424144467Sharti		times.actime = times.modtime = now;
1425144467Sharti		if (utime(file, &times) < 0) {
1426144467Sharti			streamID = open(file, O_RDWR | O_CREAT, 0666);
14271590Srgrimes
1428144467Sharti			if (streamID >= 0) {
1429144467Sharti				char	c;
14301590Srgrimes
1431144467Sharti				/*
1432144467Sharti				 * Read and write a byte to the file to change
1433144467Sharti				 * the modification time, then close the file.
1434144467Sharti				 */
1435144467Sharti				if (read(streamID, &c, 1) == 1) {
1436144467Sharti					lseek(streamID, (off_t)0, SEEK_SET);
1437144467Sharti					write(streamID, &c, 1);
1438144467Sharti				}
1439144467Sharti
1440144467Sharti				close(streamID);
1441144467Sharti			} else {
1442144467Sharti				fprintf(stdout, "*** couldn't touch %s: %s",
1443144467Sharti				    file, strerror(errno));
1444144467Sharti				fflush(stdout);
1445144467Sharti			}
14461590Srgrimes		}
14471590Srgrimes	}
14481590Srgrimes}
14491590Srgrimes
1450144467Sharti/**
1451144467Sharti * Job_CheckCommands
14528874Srgrimes *	Make sure the given node has all the commands it needs.
14531590Srgrimes *
14541590Srgrimes * Results:
14551590Srgrimes *	TRUE if the commands list is/was ok.
14561590Srgrimes *
14571590Srgrimes * Side Effects:
14581590Srgrimes *	The node will have commands from the .DEFAULT rule added to it
14591590Srgrimes *	if it needs them.
14601590Srgrimes */
14611590SrgrimesBoolean
1462104696SjmallettJob_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
14631590Srgrimes{
1464138232Sharti
1465144467Sharti	if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
1466144467Sharti	    (gn->type & OP_LIB) == 0) {
1467144467Sharti		/*
1468144467Sharti		 * No commands. Look for .DEFAULT rule from which we might infer
1469144467Sharti		 * commands.
1470144467Sharti		 */
1471144657Sharti		if (DEFAULT != NULL && !Lst_IsEmpty(&DEFAULT->commands)) {
1472144467Sharti			char *p1;
1473144467Sharti			/*
1474144467Sharti			 * Make only looks for a .DEFAULT if the node was
1475144467Sharti			 * never the target of an operator, so that's what we
1476144467Sharti			 * do too. If a .DEFAULT was given, we substitute its
1477144467Sharti			 * commands for gn's commands and set the IMPSRC
1478144467Sharti			 * variable to be the target's name The DEFAULT node
1479144467Sharti			 * acts like a transformation rule, in that gn also
1480144467Sharti			 * inherits any attributes or sources attached to
1481144467Sharti			 * .DEFAULT itself.
1482144467Sharti			 */
1483144467Sharti			Make_HandleUse(DEFAULT, gn);
1484144467Sharti			Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn);
1485144467Sharti			free(p1);
148618730Ssteve
1487144467Sharti		} else if (Dir_MTime(gn) == 0) {
1488144467Sharti			/*
1489144467Sharti			 * The node wasn't the target of an operator we have
1490144467Sharti			 * no .DEFAULT rule to go on and the target doesn't
1491144467Sharti			 * already exist. There's nothing more we can do for
1492144467Sharti			 * this branch. If the -k flag wasn't given, we stop
1493144467Sharti			 * in our tracks, otherwise we just don't update
1494144467Sharti			 * this node's parents so they never get examined.
1495144467Sharti			 */
1496144467Sharti			static const char msg[] =
1497144467Sharti			    "make: don't know how to make";
1498144467Sharti
1499144467Sharti			if (gn->type & OP_OPTIONAL) {
1500144467Sharti				fprintf(stdout, "%s %s(ignored)\n",
1501144467Sharti				    msg, gn->name);
1502144467Sharti				fflush(stdout);
1503144467Sharti			} else if (keepgoing) {
1504144467Sharti				fprintf(stdout, "%s %s(continuing)\n",
1505144467Sharti				    msg, gn->name);
1506144467Sharti				fflush(stdout);
1507144467Sharti				return (FALSE);
1508144467Sharti			} else {
150935483Simp#if OLD_JOKE
1510144467Sharti				if (strcmp(gn->name,"love") == 0)
1511144467Sharti					(*abortProc)("Not war.");
1512144467Sharti				else
151335483Simp#endif
1514144467Sharti					(*abortProc)("%s %s. Stop",
1515144467Sharti					    msg, gn->name);
1516144467Sharti				return (FALSE);
1517144467Sharti			}
1518144467Sharti		}
15191590Srgrimes	}
1520144467Sharti	return (TRUE);
15211590Srgrimes}
15221590Srgrimes
1523144467Sharti/**
1524144467Sharti * JobExec
15251590Srgrimes *	Execute the shell for the given job. Called from JobStart and
15261590Srgrimes *	JobRestart.
15271590Srgrimes *
15281590Srgrimes * Side Effects:
15291590Srgrimes *	A shell is executed, outputs is altered and the Job structure added
15301590Srgrimes *	to the job table.
15311590Srgrimes */
15321590Srgrimesstatic void
1533104696SjmallettJobExec(Job *job, char **argv)
15341590Srgrimes{
1535146129Sharti	ProcStuff	ps;
15368874Srgrimes
1537144467Sharti	if (DEBUG(JOB)) {
1538146061Sharti		int	  i;
15398874Srgrimes
1540144467Sharti		DEBUGF(JOB, ("Running %s\n", job->node->name));
1541144467Sharti		DEBUGF(JOB, ("\tCommand: "));
1542144467Sharti		for (i = 0; argv[i] != NULL; i++) {
1543144467Sharti			DEBUGF(JOB, ("%s ", argv[i]));
1544144467Sharti		}
1545144467Sharti		DEBUGF(JOB, ("\n"));
15461590Srgrimes	}
15478874Srgrimes
15481590Srgrimes	/*
1549144467Sharti	 * Some jobs produce no output and it's disconcerting to have
1550144467Sharti	 * no feedback of their running (since they produce no output, the
1551144467Sharti	 * banner with their name in it never appears). This is an attempt to
1552144467Sharti	 * provide that feedback, even if nothing follows it.
15531590Srgrimes	 */
1554144657Sharti	if (lastNode != job->node && (job->flags & JOB_FIRST) &&
1555144467Sharti	    !(job->flags & JOB_SILENT)) {
1556144467Sharti		MESSAGE(stdout, job->node);
1557144467Sharti		lastNode = job->node;
15581590Srgrimes	}
15591590Srgrimes
1560146129Sharti	ps.in = FILENO(job->cmdFILE);
1561146129Sharti	if (usePipes) {
1562146129Sharti		/*
1563146129Sharti		 * Set up the child's output to be routed through the
1564146129Sharti		 * pipe we've created for it.
1565146129Sharti		 */
1566146129Sharti		ps.out = job->outPipe;
1567146129Sharti	} else {
1568146129Sharti		/*
1569146129Sharti		 * We're capturing output in a file, so we duplicate
1570146129Sharti		 * the descriptor to the temporary file into the
1571146129Sharti		 * standard output.
1572146129Sharti		 */
1573146129Sharti		ps.out = job->outFd;
1574146129Sharti	}
1575146129Sharti	ps.err = STDERR_FILENO;
1576146129Sharti
1577146129Sharti	ps.merge_errors = 1;
1578146129Sharti	ps.pgroup = 1;
1579146129Sharti	ps.searchpath = 0;
1580146129Sharti
1581146129Sharti	ps.argv = argv;
1582146129Sharti
1583146129Sharti	/*
1584146129Sharti	 * Fork.  Warning since we are doing vfork() instead of fork(),
1585146129Sharti	 * do not allocate memory in the child process!
1586146129Sharti	 */
1587146130Sharti	if ((ps.child_pid = vfork()) == -1) {
1588144467Sharti		Punt("Cannot fork");
1589144467Sharti
1590146130Sharti
1591146130Sharti	} else if (ps.child_pid == 0) {
1592144665Sharti		/*
1593144665Sharti		 * Child
1594144665Sharti		 */
1595144467Sharti		if (fifoFd >= 0)
1596144467Sharti			close(fifoFd);
1597144467Sharti
1598146129Sharti		ProcExec(&ps);
1599146129Sharti		/* NOTREACHED */
1600144665Sharti	}
1601146130Sharti
1602144665Sharti	/*
1603144665Sharti	 * Parent
1604144665Sharti	 */
1605146130Sharti	job->pid = ps.child_pid;
1606144467Sharti
1607144665Sharti	if (usePipes && (job->flags & JOB_FIRST)) {
1608144665Sharti		/*
1609144665Sharti		 * The first time a job is run for a node, we set the
1610144665Sharti		 * current position in the buffer to the beginning and
1611144665Sharti		 * mark another stream to watch in the outputs mask.
1612144665Sharti		 */
1613104475Sphk#ifdef USE_KQUEUE
1614144665Sharti		struct kevent	kev[2];
1615104475Sphk#endif
1616144665Sharti		job->curPos = 0;
16178874Srgrimes
1618137202Sharti#if defined(USE_KQUEUE)
1619144665Sharti		EV_SET(&kev[0], job->inPipe, EVFILT_READ, EV_ADD, 0, 0, job);
1620144665Sharti		EV_SET(&kev[1], job->pid, EVFILT_PROC,
1621144665Sharti		    EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
1622144665Sharti		if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1623144665Sharti			/*
1624144665Sharti			 * kevent() will fail if the job is already
1625144665Sharti			 * finished
1626144665Sharti			 */
1627144665Sharti			if (errno != EINTR && errno != EBADF && errno != ESRCH)
1628144665Sharti				Punt("kevent: %s", strerror(errno));
1629144665Sharti		}
16301590Srgrimes#else
1631144665Sharti		FD_SET(job->inPipe, &outputs);
1632137202Sharti#endif /* USE_KQUEUE */
1633144665Sharti	}
1634144467Sharti
1635144665Sharti	if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1636144665Sharti		fclose(job->cmdFILE);
1637144665Sharti		job->cmdFILE = NULL;
16381590Srgrimes	}
16391590Srgrimes
1640144467Sharti	/*
1641144467Sharti	 * Now the job is actually running, add it to the table.
1642144467Sharti	 */
1643144467Sharti	nJobs += 1;
1644144494Sharti	TAILQ_INSERT_TAIL(&jobs, job, link);
1645144467Sharti	if (nJobs == maxJobs) {
1646144467Sharti		jobFull = TRUE;
16471590Srgrimes	}
16481590Srgrimes}
16491590Srgrimes
1650144467Sharti/**
1651144467Sharti * JobMakeArgv
16521590Srgrimes *	Create the argv needed to execute the shell for a given job.
16531590Srgrimes */
16541590Srgrimesstatic void
1655104696SjmallettJobMakeArgv(Job *job, char **argv)
16561590Srgrimes{
1657144467Sharti	int		argc;
1658144467Sharti	static char	args[10];	/* For merged arguments */
16598874Srgrimes
1660144467Sharti	argv[0] = shellName;
1661144467Sharti	argc = 1;
16621590Srgrimes
1663144657Sharti	if ((commandShell->exit && *commandShell->exit != '-') ||
1664144657Sharti	    (commandShell->echo && *commandShell->echo != '-')) {
1665144467Sharti		/*
1666144467Sharti		 * At least one of the flags doesn't have a minus before it, so
1667144467Sharti		 * merge them together. Have to do this because the *(&(@*#*&#$#
1668144467Sharti		 * Bourne shell thinks its second argument is a file to source.
1669144467Sharti		 * Grrrr. Note the ten-character limitation on the combined
1670144467Sharti		 * arguments.
1671144467Sharti		 */
1672144657Sharti		sprintf(args, "-%s%s", (job->flags & JOB_IGNERR) ? "" :
1673144657Sharti		    commandShell->exit ? commandShell->exit : "",
1674144657Sharti		    (job->flags & JOB_SILENT) ? "" :
1675144657Sharti		    commandShell->echo ? commandShell->echo : "");
16761590Srgrimes
1677144467Sharti		if (args[1]) {
1678144467Sharti			argv[argc] = args;
1679144467Sharti			argc++;
1680144467Sharti		}
1681144467Sharti	} else {
1682144467Sharti		if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1683144467Sharti			argv[argc] = commandShell->exit;
1684144467Sharti			argc++;
1685144467Sharti		}
1686144467Sharti		if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1687144467Sharti			argv[argc] = commandShell->echo;
1688144467Sharti			argc++;
1689144467Sharti		}
16901590Srgrimes	}
1691144467Sharti	argv[argc] = NULL;
16921590Srgrimes}
16931590Srgrimes
1694144467Sharti/**
1695144467Sharti * JobRestart
1696144494Sharti *	Restart a job that stopped for some reason. The job must be neither
1697144494Sharti *	on the jobs nor on the stoppedJobs list.
16981590Srgrimes *
16991590Srgrimes * Side Effects:
17001590Srgrimes *	jobFull will be set if the job couldn't be run.
17011590Srgrimes */
17021590Srgrimesstatic void
1703104696SjmallettJobRestart(Job *job)
17041590Srgrimes{
170518730Ssteve
1706144467Sharti	if (job->flags & JOB_RESTART) {
1707144467Sharti		/*
1708144467Sharti		 * Set up the control arguments to the shell. This is based on
1709144467Sharti		 * the flags set earlier for this job. If the JOB_IGNERR flag
1710144467Sharti		 * is clear, the 'exit' flag of the commandShell is used to
1711144467Sharti		 * cause it to exit upon receiving an error. If the JOB_SILENT
1712144467Sharti		 * flag is clear, the 'echo' flag of the commandShell is used
1713144467Sharti		 * to get it to start echoing as soon as it starts
1714144467Sharti		 * processing commands.
1715144467Sharti		 */
1716144467Sharti		char	*argv[4];
17178874Srgrimes
1718144467Sharti		JobMakeArgv(job, argv);
17198874Srgrimes
1720144467Sharti		DEBUGF(JOB, ("Restarting %s...", job->node->name));
1721144657Sharti		if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL)) {
1722144467Sharti			/*
1723144657Sharti			 * Not allowed to run -- put it back on the hold
1724144657Sharti			 * queue and mark the table full
1725144467Sharti			 */
1726144467Sharti			DEBUGF(JOB, ("holding\n"));
1727144494Sharti			TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1728144467Sharti			jobFull = TRUE;
1729144467Sharti			DEBUGF(JOB, ("Job queue is full.\n"));
1730144467Sharti			return;
1731144467Sharti		} else {
1732144467Sharti			/*
1733144467Sharti			 * Job may be run locally.
1734144467Sharti			 */
1735144467Sharti			DEBUGF(JOB, ("running locally\n"));
1736144467Sharti		}
1737144467Sharti		JobExec(job, argv);
1738144467Sharti
1739137202Sharti	} else {
17401590Srgrimes		/*
1741144467Sharti		 * The job has stopped and needs to be restarted.
1742144467Sharti		 * Why it stopped, we don't know...
17431590Srgrimes		 */
1744144467Sharti		DEBUGF(JOB, ("Resuming %s...", job->node->name));
1745144657Sharti		if ((nJobs < maxJobs || ((job->flags & JOB_SPECIAL) &&
1746144657Sharti		    maxJobs == 0)) && nJobs != maxJobs) {
1747144467Sharti			/*
1748144467Sharti			 * If we haven't reached the concurrency limit already
1749144467Sharti			 * (or the job must be run and maxJobs is 0), it's ok
1750144467Sharti			 * to resume it.
1751144467Sharti			 */
1752144467Sharti			Boolean error;
1753144467Sharti			int status;
17548874Srgrimes
1755144467Sharti			error = (KILL(job->pid, SIGCONT) != 0);
1756144467Sharti
1757144467Sharti			if (!error) {
1758144467Sharti				/*
1759144467Sharti				 * Make sure the user knows we've continued
1760144467Sharti				 * the beast and actually put the thing in the
1761144467Sharti				 * job table.
1762144467Sharti				 */
1763144467Sharti				job->flags |= JOB_CONTINUING;
1764144467Sharti				status = 0;
1765144467Sharti				W_SETTERMSIG(&status, SIGCONT);
1766144467Sharti				JobFinish(job, &status);
1767144467Sharti
1768144467Sharti				job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1769144467Sharti				DEBUGF(JOB, ("done\n"));
1770144467Sharti			} else {
1771144467Sharti				Error("couldn't resume %s: %s",
1772144467Sharti				job->node->name, strerror(errno));
1773144467Sharti				status = 0;
1774144467Sharti				W_SETEXITSTATUS(&status, 1);
1775144467Sharti				JobFinish(job, &status);
1776144467Sharti			}
1777144467Sharti		} else {
1778144467Sharti			/*
1779144467Sharti			* Job cannot be restarted. Mark the table as full and
1780144467Sharti			* place the job back on the list of stopped jobs.
1781144467Sharti			*/
1782144467Sharti			DEBUGF(JOB, ("table full\n"));
1783144494Sharti			TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1784144467Sharti			jobFull = TRUE;
1785144467Sharti			DEBUGF(JOB, ("Job queue is full.\n"));
1786144467Sharti		}
17871590Srgrimes	}
17881590Srgrimes}
17891590Srgrimes
1790144467Sharti/**
1791144467Sharti * JobStart
17921590Srgrimes *	Start a target-creation process going for the target described
17938874Srgrimes *	by the graph node gn.
17941590Srgrimes *
17951590Srgrimes * Results:
17961590Srgrimes *	JOB_ERROR if there was an error in the commands, JOB_FINISHED
17971590Srgrimes *	if there isn't actually anything left to do for the job and
17981590Srgrimes *	JOB_RUNNING if the job has been started.
17991590Srgrimes *
18001590Srgrimes * Side Effects:
18011590Srgrimes *	A new Job node is created and added to the list of running
18021590Srgrimes *	jobs. PMake is forked and a child shell created.
18031590Srgrimes */
18041590Srgrimesstatic int
1805104696SjmallettJobStart(GNode *gn, int flags, Job *previous)
18061590Srgrimes{
1807144467Sharti	Job	*job;		/* new job descriptor */
1808144467Sharti	char	*argv[4];	/* Argument vector to shell */
1809144467Sharti	Boolean	cmdsOK;		/* true if the nodes commands were all right */
1810144467Sharti	Boolean	noExec;		/* Set true if we decide not to run the job */
1811144467Sharti	int	tfd;		/* File descriptor for temp file */
1812144467Sharti	LstNode	*ln;
1813144654Sharti	char	tfile[sizeof(TMPPAT)];
18141590Srgrimes
1815144467Sharti	if (interrupted) {
1816144467Sharti		JobPassSig(interrupted);
1817144467Sharti		return (JOB_ERROR);
1818144467Sharti	}
1819144467Sharti	if (previous != NULL) {
1820144467Sharti		previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1821144467Sharti		job = previous;
1822144467Sharti	} else {
1823144467Sharti		job = emalloc(sizeof(Job));
1824144467Sharti		flags |= JOB_FIRST;
1825144467Sharti	}
18261590Srgrimes
1827144467Sharti	job->node = gn;
1828144467Sharti	job->tailCmds = NULL;
18291590Srgrimes
18301590Srgrimes	/*
1831144467Sharti	 * Set the initial value of the flags for this job based on the global
1832144467Sharti	 * ones and the node's attributes... Any flags supplied by the caller
1833144467Sharti	 * are also added to the field.
18341590Srgrimes	 */
1835144467Sharti	job->flags = 0;
1836144467Sharti	if (Targ_Ignore(gn)) {
1837144467Sharti		job->flags |= JOB_IGNERR;
18381590Srgrimes	}
1839144467Sharti	if (Targ_Silent(gn)) {
1840144467Sharti		job->flags |= JOB_SILENT;
1841144467Sharti	}
1842144467Sharti	job->flags |= flags;
18438874Srgrimes
18441590Srgrimes	/*
1845144467Sharti	 * Check the commands now so any attributes from .DEFAULT have a chance
1846144658Sharti	 * to migrate to the node.
18471590Srgrimes	 */
1848144658Sharti	if (!compatMake && (job->flags & JOB_FIRST)) {
1849144467Sharti		cmdsOK = Job_CheckCommands(gn, Error);
1850144467Sharti	} else {
1851144467Sharti		cmdsOK = TRUE;
1852144467Sharti	}
18531590Srgrimes
18541590Srgrimes	/*
1855144467Sharti	 * If the -n flag wasn't given, we open up OUR (not the child's)
1856144467Sharti	 * temporary file to stuff commands in it. The thing is rd/wr so we
1857144467Sharti	 * don't need to reopen it to feed it to the shell. If the -n flag
1858144467Sharti	 * *was* given, we just set the file to be stdout. Cute, huh?
18591590Srgrimes	 */
1860144467Sharti	if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1861144467Sharti		/*
1862144467Sharti		 * We're serious here, but if the commands were bogus, we're
1863144467Sharti		 * also dead...
1864144467Sharti		 */
1865144467Sharti		if (!cmdsOK) {
1866144467Sharti			DieHorribly();
1867144467Sharti		}
18688874Srgrimes
1869144467Sharti		strcpy(tfile, TMPPAT);
1870144467Sharti		if ((tfd = mkstemp(tfile)) == -1)
1871144467Sharti			Punt("Cannot create temp file: %s", strerror(errno));
1872144467Sharti		job->cmdFILE = fdopen(tfd, "w+");
1873144467Sharti		eunlink(tfile);
1874144467Sharti		if (job->cmdFILE == NULL) {
1875144467Sharti			close(tfd);
1876144467Sharti			Punt("Could not open %s", tfile);
1877144467Sharti		}
1878144467Sharti		fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1879144467Sharti		/*
1880144467Sharti		 * Send the commands to the command file, flush all its
1881144467Sharti		 * buffers then rewind and remove the thing.
1882144467Sharti		 */
1883144467Sharti		noExec = FALSE;
1884138564Sharti
1885138564Sharti		/*
1886144467Sharti		 * Used to be backwards; replace when start doing multiple
1887144467Sharti		 * commands per shell.
1888138564Sharti		 */
1889144467Sharti		if (compatMake) {
1890144467Sharti			/*
1891144467Sharti			 * Be compatible: If this is the first time for this
1892144467Sharti			 * node, verify its commands are ok and open the
1893144467Sharti			 * commands list for sequential access by later
1894144467Sharti			 * invocations of JobStart. Once that is done, we take
1895144467Sharti			 * the next command off the list and print it to the
1896144467Sharti			 * command file. If the command was an ellipsis, note
1897144467Sharti			 * that there's nothing more to execute.
1898144467Sharti			 */
1899144467Sharti			if (job->flags & JOB_FIRST)
1900144467Sharti				gn->compat_command = Lst_First(&gn->commands);
1901144467Sharti			else
1902144467Sharti				gn->compat_command =
1903144467Sharti				    Lst_Succ(gn->compat_command);
19048874Srgrimes
1905144467Sharti			if (gn->compat_command == NULL ||
1906144467Sharti			    JobPrintCommand(Lst_Datum(gn->compat_command), job))
1907144467Sharti				noExec = TRUE;
1908144467Sharti
1909144467Sharti			if (noExec && !(job->flags & JOB_FIRST)) {
1910144467Sharti				/*
1911144467Sharti				 * If we're not going to execute anything, the
1912144467Sharti				 * job is done and we need to close down the
1913144467Sharti				 * various file descriptors we've opened for
1914144467Sharti				 * output, then call JobDoOutput to catch the
1915144467Sharti				 * final characters or send the file to the
1916144467Sharti				 * screen... Note that the i/o streams are only
1917144467Sharti				 * open if this isn't the first job. Note also
1918144467Sharti				 * that this could not be done in
1919144467Sharti				 * Job_CatchChildren b/c it wasn't clear if
1920144467Sharti				 * there were more commands to execute or not...
1921144467Sharti				 */
1922144467Sharti				JobClose(job);
1923144467Sharti			}
1924144467Sharti		} else {
1925144467Sharti			/*
1926144467Sharti			 * We can do all the commands at once. hooray for sanity
1927144467Sharti			 */
1928144467Sharti			numCommands = 0;
1929144467Sharti			LST_FOREACH(ln, &gn->commands) {
1930144467Sharti				if (JobPrintCommand(Lst_Datum(ln), job))
1931144467Sharti					break;
1932144467Sharti			}
1933144467Sharti
1934144467Sharti			/*
1935144467Sharti			 * If we didn't print out any commands to the shell
1936144467Sharti			 * script, there's not much point in executing the
1937144467Sharti			 * shell, is there?
1938144467Sharti			 */
1939144467Sharti			if (numCommands == 0) {
1940144467Sharti				noExec = TRUE;
1941144467Sharti			}
1942144467Sharti		}
1943144467Sharti
1944144467Sharti	} else if (noExecute) {
1945144467Sharti		/*
1946144467Sharti		 * Not executing anything -- just print all the commands to
1947144467Sharti		 * stdout in one fell swoop. This will still set up
1948144467Sharti		 * job->tailCmds correctly.
1949144467Sharti		 */
1950144467Sharti		if (lastNode != gn) {
1951144467Sharti			MESSAGE(stdout, gn);
1952144467Sharti			lastNode = gn;
1953144467Sharti		}
1954144467Sharti		job->cmdFILE = stdout;
1955144467Sharti
1956144467Sharti		/*
1957144467Sharti		 * Only print the commands if they're ok, but don't die if
1958144467Sharti		 * they're not -- just let the user know they're bad and keep
1959144467Sharti		 * going. It doesn't do any harm in this case and may do
1960144467Sharti		 * some good.
1961144467Sharti		 */
1962144467Sharti		if (cmdsOK) {
1963144467Sharti			LST_FOREACH(ln, &gn->commands) {
1964144467Sharti				if (JobPrintCommand(Lst_Datum(ln), job))
1965144467Sharti					break;
1966144467Sharti			}
1967144467Sharti		}
1968144467Sharti		/*
1969144467Sharti		* Don't execute the shell, thank you.
1970144467Sharti		*/
19711590Srgrimes		noExec = TRUE;
1972144467Sharti
1973144467Sharti	} else {
1974144467Sharti		/*
1975144467Sharti		 * Just touch the target and note that no shell should be
1976144467Sharti		 * executed. Set cmdFILE to stdout to make life easier. Check
1977144467Sharti		 * the commands, too, but don't die if they're no good -- it
1978144467Sharti		 * does no harm to keep working up the graph.
1979144467Sharti		 */
1980144467Sharti		job->cmdFILE = stdout;
1981144467Sharti		Job_Touch(gn, job->flags & JOB_SILENT);
1982144467Sharti		noExec = TRUE;
19831590Srgrimes	}
1984144467Sharti
19851590Srgrimes	/*
1986144467Sharti	 * If we're not supposed to execute a shell, don't.
19871590Srgrimes	 */
1988144467Sharti	if (noExec) {
1989144467Sharti		/*
1990144467Sharti		 * Unlink and close the command file if we opened one
1991144467Sharti		 */
1992144467Sharti		if (job->cmdFILE != stdout) {
1993144467Sharti			if (job->cmdFILE != NULL)
1994144467Sharti				fclose(job->cmdFILE);
1995144467Sharti		} else {
1996144467Sharti			fflush(stdout);
1997144467Sharti		}
1998144467Sharti
1999144467Sharti		/*
2000144467Sharti		 * We only want to work our way up the graph if we aren't here
2001144467Sharti		 * because the commands for the job were no good.
2002144467Sharti		*/
2003144467Sharti		if (cmdsOK) {
2004144467Sharti			if (aborting == 0) {
2005144467Sharti				for (ln = job->tailCmds; ln != NULL;
2006144467Sharti				    ln = LST_NEXT(ln)) {
2007144467Sharti					Lst_AtEnd(&postCommands->commands,
2008146027Sharti					    Buf_Peel(Var_Subst(Lst_Datum(ln),
2009146027Sharti					    job->node, FALSE)));
2010144467Sharti				}
2011144467Sharti				job->node->made = MADE;
2012144467Sharti				Make_Update(job->node);
2013144467Sharti			}
2014144467Sharti			free(job);
2015144467Sharti			return(JOB_FINISHED);
2016144467Sharti		} else {
2017144467Sharti			free(job);
2018144467Sharti			return(JOB_ERROR);
2019144467Sharti		}
2020144467Sharti	} else {
2021144467Sharti		fflush(job->cmdFILE);
20221590Srgrimes	}
2023144467Sharti
20241590Srgrimes	/*
2025144467Sharti	 * Set up the control arguments to the shell. This is based on the flags
2026144467Sharti	 * set earlier for this job.
20271590Srgrimes	 */
2028144467Sharti	JobMakeArgv(job, argv);
20291590Srgrimes
20301590Srgrimes	/*
2031144467Sharti	 * If we're using pipes to catch output, create the pipe by which we'll
2032144467Sharti	 * get the shell's output. If we're using files, print out that we're
2033144467Sharti	 * starting a job and then set up its temporary-file name.
20341590Srgrimes	 */
2035144467Sharti	if (!compatMake || (job->flags & JOB_FIRST)) {
2036144467Sharti		if (usePipes) {
2037144467Sharti			int fd[2];
20381590Srgrimes
2039144467Sharti			if (pipe(fd) == -1)
2040144467Sharti				Punt("Cannot create pipe: %s", strerror(errno));
2041144467Sharti			job->inPipe = fd[0];
2042144467Sharti			job->outPipe = fd[1];
2043144467Sharti			fcntl(job->inPipe, F_SETFD, 1);
2044144467Sharti			fcntl(job->outPipe, F_SETFD, 1);
2045144467Sharti		} else {
2046144467Sharti			fprintf(stdout, "Remaking `%s'\n", gn->name);
2047144467Sharti			fflush(stdout);
2048144467Sharti			strcpy(job->outFile, TMPPAT);
2049144467Sharti			if ((job->outFd = mkstemp(job->outFile)) == -1)
2050144467Sharti				Punt("cannot create temp file: %s",
2051144467Sharti				    strerror(errno));
2052144467Sharti			fcntl(job->outFd, F_SETFD, 1);
20531590Srgrimes		}
20541590Srgrimes	}
20551590Srgrimes
2056144657Sharti	if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL) && maxJobs != 0) {
2057144467Sharti		/*
2058144467Sharti		 * We've hit the limit of concurrency, so put the job on hold
2059144467Sharti		 * until some other job finishes. Note that the special jobs
2060144467Sharti		 * (.BEGIN, .INTERRUPT and .END) may be run even when the
2061144467Sharti		 * limit has been reached (e.g. when maxJobs == 0).
2062144467Sharti		 */
2063144467Sharti		jobFull = TRUE;
20641590Srgrimes
2065144467Sharti		DEBUGF(JOB, ("Can only run job locally.\n"));
2066144467Sharti		job->flags |= JOB_RESTART;
2067144494Sharti		TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
20681590Srgrimes	} else {
2069144467Sharti		if (nJobs >= maxJobs) {
2070144467Sharti			/*
2071144657Sharti			 * If we're running this job as a special case
2072144467Sharti			 * (see above), at least say the table is full.
2073144467Sharti			 */
2074144467Sharti			jobFull = TRUE;
2075144467Sharti			DEBUGF(JOB, ("Local job queue is full.\n"));
2076144467Sharti		}
2077144467Sharti		JobExec(job, argv);
20781590Srgrimes	}
2079144467Sharti	return (JOB_RUNNING);
20801590Srgrimes}
20811590Srgrimes
208218730Sstevestatic char *
2083104696SjmallettJobOutput(Job *job, char *cp, char *endp, int msg)
208418730Ssteve{
2085144467Sharti	char *ecp;
208618730Ssteve
2087144467Sharti	if (commandShell->noPrint) {
2088144467Sharti		ecp = strstr(cp, commandShell->noPrint);
2089144467Sharti		while (ecp != NULL) {
2090144467Sharti			if (cp != ecp) {
2091144467Sharti				*ecp = '\0';
2092144467Sharti				if (msg && job->node != lastNode) {
2093144467Sharti					MESSAGE(stdout, job->node);
2094144467Sharti					lastNode = job->node;
2095144467Sharti				}
2096144467Sharti				/*
2097144467Sharti				 * The only way there wouldn't be a newline
2098144467Sharti				 * after this line is if it were the last in
2099144467Sharti				 * the buffer. However, since the non-printable
2100144467Sharti				 * comes after it, there must be a newline, so
2101144467Sharti				 * we don't print one.
2102144467Sharti				 */
2103144467Sharti				fprintf(stdout, "%s", cp);
2104144467Sharti				fflush(stdout);
2105144467Sharti			}
2106144741Sharti			cp = ecp + strlen(commandShell->noPrint);
2107144467Sharti			if (cp != endp) {
2108144467Sharti				/*
2109144467Sharti				 * Still more to print, look again after
2110144467Sharti				 * skipping the whitespace following the
2111144467Sharti				 * non-printable command....
2112144467Sharti				 */
2113144467Sharti				cp++;
2114144467Sharti				while (*cp == ' ' || *cp == '\t' ||
2115144467Sharti				    *cp == '\n') {
2116144467Sharti					cp++;
2117144467Sharti				}
2118144467Sharti				ecp = strstr(cp, commandShell->noPrint);
2119144467Sharti			} else {
2120144467Sharti				return (cp);
2121144467Sharti			}
212218730Ssteve		}
212318730Ssteve	}
2124144467Sharti	return (cp);
212518730Ssteve}
212618730Ssteve
2127144467Sharti/**
2128144467Sharti * JobDoOutput
21291590Srgrimes *	This function is called at different times depending on
21301590Srgrimes *	whether the user has specified that output is to be collected
21311590Srgrimes *	via pipes or temporary files. In the former case, we are called
21321590Srgrimes *	whenever there is something to read on the pipe. We collect more
21331590Srgrimes *	output from the given job and store it in the job's outBuf. If
21341590Srgrimes *	this makes up a line, we print it tagged by the job's identifier,
21351590Srgrimes *	as necessary.
21361590Srgrimes *	If output has been collected in a temporary file, we open the
21371590Srgrimes *	file and read it line by line, transfering it to our own
21381590Srgrimes *	output channel until the file is empty. At which point we
21391590Srgrimes *	remove the temporary file.
21401590Srgrimes *	In both cases, however, we keep our figurative eye out for the
21411590Srgrimes *	'noPrint' line for the shell from which the output came. If
21421590Srgrimes *	we recognize a line, we don't print it. If the command is not
21431590Srgrimes *	alone on the line (the character after it is not \0 or \n), we
21441590Srgrimes *	do print whatever follows it.
21451590Srgrimes *
21461590Srgrimes * Side Effects:
21471590Srgrimes *	curPos may be shifted as may the contents of outBuf.
21481590Srgrimes */
2149144656Shartistatic void
2150104696SjmallettJobDoOutput(Job *job, Boolean finish)
21511590Srgrimes{
2152144467Sharti	Boolean	gotNL = FALSE;	/* true if got a newline */
2153144467Sharti	Boolean	fbuf;		/* true if our buffer filled up */
2154144467Sharti	int	nr;		/* number of bytes read */
2155144467Sharti	int	i;		/* auxiliary index into outBuf */
2156144467Sharti	int	max;		/* limit for i (end of current data) */
2157144467Sharti	int	nRead;		/* (Temporary) number of bytes read */
2158144467Sharti	FILE	*oFILE;		/* Stream pointer to shell's output file */
2159144467Sharti	char	inLine[132];
21601590Srgrimes
2161144467Sharti	if (usePipes) {
21621590Srgrimes		/*
2163144467Sharti		 * Read as many bytes as will fit in the buffer.
21641590Srgrimes		 */
2165144467Sharti  end_loop:
2166144467Sharti		gotNL = FALSE;
2167144467Sharti		fbuf = FALSE;
21688874Srgrimes
2169144467Sharti		nRead = read(job->inPipe, &job->outBuf[job->curPos],
2170144467Sharti		    JOB_BUFSIZE - job->curPos);
21711590Srgrimes		/*
2172144467Sharti		 * Check for interrupt here too, because the above read may
2173144467Sharti		 * block when the child process is stopped. In this case the
2174144467Sharti		 * interrupt will unblock it (we don't use SA_RESTART).
21751590Srgrimes		 */
2176144467Sharti		if (interrupted)
2177144467Sharti			JobPassSig(interrupted);
21781590Srgrimes
2179144467Sharti		if (nRead < 0) {
2180144467Sharti			DEBUGF(JOB, ("JobDoOutput(piperead)"));
2181144467Sharti			nr = 0;
2182144467Sharti		} else {
2183144467Sharti			nr = nRead;
2184144467Sharti		}
21851590Srgrimes
21861590Srgrimes		/*
2187144467Sharti		 * If we hit the end-of-file (the job is dead), we must flush
2188144467Sharti		 * its remaining output, so pretend we read a newline if
2189144467Sharti		 * there's any output remaining in the buffer.
2190144467Sharti		 * Also clear the 'finish' flag so we stop looping.
21911590Srgrimes		 */
2192144657Sharti		if (nr == 0 && job->curPos != 0) {
2193144467Sharti			job->outBuf[job->curPos] = '\n';
2194144467Sharti			nr = 1;
2195144467Sharti			finish = FALSE;
2196144467Sharti		} else if (nr == 0) {
2197144467Sharti			finish = FALSE;
21981590Srgrimes		}
21998874Srgrimes
22001590Srgrimes		/*
2201144467Sharti		 * Look for the last newline in the bytes we just got. If there
2202144467Sharti		 * is one, break out of the loop with 'i' as its index and
2203144467Sharti		 * gotNL set TRUE.
2204144467Sharti		*/
2205144467Sharti		max = job->curPos + nr;
2206144467Sharti		for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
2207144467Sharti			if (job->outBuf[i] == '\n') {
2208144467Sharti				gotNL = TRUE;
2209144467Sharti				break;
2210144467Sharti			} else if (job->outBuf[i] == '\0') {
2211144467Sharti				/*
2212144467Sharti				 * Why?
2213144467Sharti				 */
2214144467Sharti				job->outBuf[i] = ' ';
2215144467Sharti			}
2216144467Sharti		}
22171590Srgrimes
2218144467Sharti		if (!gotNL) {
2219144467Sharti			job->curPos += nr;
2220144467Sharti			if (job->curPos == JOB_BUFSIZE) {
2221144467Sharti				/*
2222144467Sharti				 * If we've run out of buffer space, we have
2223144467Sharti				 * no choice but to print the stuff. sigh.
2224144467Sharti				 */
2225144467Sharti				fbuf = TRUE;
2226144467Sharti				i = job->curPos;
2227144467Sharti			}
22281590Srgrimes		}
2229144467Sharti		if (gotNL || fbuf) {
2230144467Sharti			/*
2231144467Sharti			 * Need to send the output to the screen. Null terminate
2232144467Sharti			 * it first, overwriting the newline character if there
2233144467Sharti			 * was one. So long as the line isn't one we should
2234144467Sharti			 * filter (according to the shell description), we print
2235144467Sharti			 * the line, preceded by a target banner if this target
2236144467Sharti			 * isn't the same as the one for which we last printed
2237144467Sharti			 * something. The rest of the data in the buffer are
2238144467Sharti			 * then shifted down to the start of the buffer and
2239144467Sharti			 * curPos is set accordingly.
2240144467Sharti			 */
2241144467Sharti			job->outBuf[i] = '\0';
2242144467Sharti			if (i >= job->curPos) {
2243144467Sharti				char *cp;
22441590Srgrimes
2245144467Sharti				cp = JobOutput(job, job->outBuf,
2246144467Sharti				    &job->outBuf[i], FALSE);
2247144467Sharti
2248144467Sharti				/*
2249144467Sharti				 * There's still more in that buffer. This time,
2250144467Sharti				 * though, we know there's no newline at the
2251144467Sharti				 * end, so we add one of our own free will.
2252144467Sharti				 */
2253144467Sharti				if (*cp != '\0') {
2254144467Sharti					if (job->node != lastNode) {
2255144467Sharti						MESSAGE(stdout, job->node);
2256144467Sharti						lastNode = job->node;
2257144467Sharti					}
2258144467Sharti					fprintf(stdout, "%s%s", cp,
2259144467Sharti					    gotNL ? "\n" : "");
2260144467Sharti					fflush(stdout);
2261144467Sharti				}
2262144467Sharti			}
2263144467Sharti			if (i < max - 1) {
2264144467Sharti				/* shift the remaining characters down */
2265144467Sharti				memcpy(job->outBuf, &job->outBuf[i + 1],
2266144467Sharti				    max - (i + 1));
2267144467Sharti				job->curPos = max - (i + 1);
2268144467Sharti
2269144467Sharti			} else {
2270144467Sharti				/*
2271144467Sharti				 * We have written everything out, so we just
2272144467Sharti				 * start over from the start of the buffer.
2273144467Sharti				 * No copying. No nothing.
2274144467Sharti				 */
2275144467Sharti				job->curPos = 0;
2276144467Sharti			}
2277144467Sharti		}
2278144467Sharti		if (finish) {
2279144467Sharti			/*
2280144467Sharti			 * If the finish flag is true, we must loop until we hit
2281144467Sharti			 * end-of-file on the pipe. This is guaranteed to happen
2282144467Sharti			 * eventually since the other end of the pipe is now
2283144467Sharti			 * closed (we closed it explicitly and the child has
2284144467Sharti			 * exited). When we do get an EOF, finish will be set
2285144467Sharti			 * FALSE and we'll fall through and out.
2286144467Sharti			 */
2287144467Sharti			goto end_loop;
2288144467Sharti		}
2289144467Sharti
2290144467Sharti	} else {
22911590Srgrimes		/*
2292144467Sharti		 * We've been called to retrieve the output of the job from the
2293144467Sharti		 * temporary file where it's been squirreled away. This consists
2294144467Sharti		 * of opening the file, reading the output line by line, being
2295144467Sharti		 * sure not to print the noPrint line for the shell we used,
2296144467Sharti		 * then close and remove the temporary file. Very simple.
2297144467Sharti		 *
2298144467Sharti		 * Change to read in blocks and do FindSubString type things
2299144467Sharti		 * as for pipes? That would allow for "@echo -n..."
23001590Srgrimes		 */
2301144467Sharti		oFILE = fopen(job->outFile, "r");
2302144467Sharti		if (oFILE != NULL) {
2303144467Sharti			fprintf(stdout, "Results of making %s:\n",
2304144467Sharti			    job->node->name);
2305144467Sharti			fflush(stdout);
2306144467Sharti
2307144467Sharti			while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2308144467Sharti				char	*cp, *endp, *oendp;
2309144467Sharti
2310144467Sharti				cp = inLine;
2311144467Sharti				oendp = endp = inLine + strlen(inLine);
2312144467Sharti				if (endp[-1] == '\n') {
2313144467Sharti					*--endp = '\0';
2314144467Sharti				}
2315144467Sharti				cp = JobOutput(job, inLine, endp, FALSE);
2316144467Sharti
2317144467Sharti				/*
2318144467Sharti				 * There's still more in that buffer. This time,
2319144467Sharti				 * though, we know there's no newline at the
2320144467Sharti				 * end, so we add one of our own free will.
2321144467Sharti				 */
2322144467Sharti				fprintf(stdout, "%s", cp);
2323144467Sharti				fflush(stdout);
2324144467Sharti				if (endp != oendp) {
2325144467Sharti					fprintf(stdout, "\n");
2326144467Sharti					fflush(stdout);
2327144467Sharti				}
2328144467Sharti			}
2329144467Sharti			fclose(oFILE);
2330144467Sharti			eunlink(job->outFile);
23311590Srgrimes		}
23321590Srgrimes	}
23331590Srgrimes}
23341590Srgrimes
2335144467Sharti/**
2336144467Sharti * Job_CatchChildren
23371590Srgrimes *	Handle the exit of a child. Called from Make_Make.
23381590Srgrimes *
23391590Srgrimes * Side Effects:
23401590Srgrimes *	The job descriptor is removed from the list of children.
23411590Srgrimes *
23421590Srgrimes * Notes:
23431590Srgrimes *	We do waits, blocking or not, according to the wisdom of our
23441590Srgrimes *	caller, until there are no more children to report. For each
23451590Srgrimes *	job, call JobFinish to finish things off. This will take care of
23461590Srgrimes *	putting jobs on the stoppedJobs queue.
23471590Srgrimes */
23481590Srgrimesvoid
2349104696SjmallettJob_CatchChildren(Boolean block)
23501590Srgrimes{
2351144665Sharti	pid_t	pid;	/* pid of dead child */
2352144467Sharti	Job	*job;	/* job descriptor for dead child */
2353144467Sharti	int	status;	/* Exit/termination status */
23541590Srgrimes
2355144467Sharti	/*
2356144467Sharti	 * Don't even bother if we know there's no one around.
2357144467Sharti	 */
2358144467Sharti	if (nJobs == 0) {
2359144467Sharti		return;
2360144467Sharti	}
23618874Srgrimes
2362144467Sharti	for (;;) {
2363144467Sharti		pid = waitpid((pid_t)-1, &status,
2364144467Sharti		    (block ? 0 : WNOHANG) | WUNTRACED);
2365144467Sharti		if (pid <= 0)
2366144467Sharti			break;
23671590Srgrimes
2368144665Sharti		DEBUGF(JOB, ("Process %jd exited or stopped.\n",
2369144665Sharti		    (intmax_t)pid));
23701590Srgrimes
2371144494Sharti		TAILQ_FOREACH(job, &jobs, link) {
2372144494Sharti			if (job->pid == pid)
2373144467Sharti				break;
2374143810Sharti		}
2375144467Sharti
2376144494Sharti		if (job == NULL) {
2377144467Sharti			if (WIFSIGNALED(status) &&
2378144467Sharti			    (WTERMSIG(status) == SIGCONT)) {
2379144494Sharti				TAILQ_FOREACH(job, &jobs, link) {
2380144494Sharti					if (job->pid == pid)
2381144467Sharti						break;
2382144467Sharti				}
2383144494Sharti				if (job == NULL) {
2384144665Sharti					Error("Resumed child (%jd) "
2385144665Sharti					    "not in table", (intmax_t)pid);
2386144467Sharti					continue;
2387144467Sharti				}
2388144494Sharti				TAILQ_REMOVE(&stoppedJobs, job, link);
2389144467Sharti			} else {
2390144665Sharti				Error("Child (%jd) not in table?",
2391144665Sharti				    (intmax_t)pid);
2392144467Sharti				continue;
2393144467Sharti			}
2394144467Sharti		} else {
2395144494Sharti			TAILQ_REMOVE(&jobs, job, link);
2396144467Sharti			nJobs -= 1;
2397144467Sharti			if (fifoFd >= 0 && maxJobs > 1) {
2398144467Sharti				write(fifoFd, "+", 1);
2399144467Sharti				maxJobs--;
2400144467Sharti				if (nJobs >= maxJobs)
2401144467Sharti					jobFull = TRUE;
2402144467Sharti				else
2403144467Sharti					jobFull = FALSE;
2404144467Sharti			} else {
2405144467Sharti				DEBUGF(JOB, ("Job queue is no longer full.\n"));
2406144467Sharti				jobFull = FALSE;
2407144467Sharti			}
24081590Srgrimes		}
2409144467Sharti
2410144467Sharti		JobFinish(job, &status);
24111590Srgrimes	}
2412144467Sharti	if (interrupted)
2413144467Sharti		JobPassSig(interrupted);
24141590Srgrimes}
24151590Srgrimes
2416144467Sharti/**
2417144467Sharti * Job_CatchOutput
24181590Srgrimes *	Catch the output from our children, if we're using
24191590Srgrimes *	pipes do so. Otherwise just block time until we get a
2420138232Sharti *	signal(most likely a SIGCHLD) since there's no point in
24211590Srgrimes *	just spinning when there's nothing to do and the reaping
24228874Srgrimes *	of a child can wait for a while.
24231590Srgrimes *
24241590Srgrimes * Side Effects:
24251590Srgrimes *	Output is read from pipes if we're piping.
24261590Srgrimes * -----------------------------------------------------------------------
24271590Srgrimes */
24281590Srgrimesvoid
2429139064Sharti#ifdef USE_KQUEUE
2430139064ShartiJob_CatchOutput(int flag __unused)
2431139064Sharti#else
2432137606SphkJob_CatchOutput(int flag)
2433139064Sharti#endif
24341590Srgrimes{
2435144467Sharti	int		nfds;
2436104475Sphk#ifdef USE_KQUEUE
2437104475Sphk#define KEV_SIZE	4
2438144467Sharti	struct kevent	kev[KEV_SIZE];
2439144467Sharti	int		i;
2440104475Sphk#else
2441144467Sharti	struct timeval	timeout;
2442144467Sharti	fd_set		readfds;
2443144467Sharti	Job		*job;
2444104475Sphk#endif
24451590Srgrimes
2446144467Sharti	fflush(stdout);
24471590Srgrimes
2448144467Sharti	if (usePipes) {
2449104475Sphk#ifdef USE_KQUEUE
2450144467Sharti		if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
2451144467Sharti			if (errno != EINTR)
2452144467Sharti				Punt("kevent: %s", strerror(errno));
2453144467Sharti			if (interrupted)
2454144467Sharti				JobPassSig(interrupted);
2455144467Sharti		} else {
2456144467Sharti			for (i = 0; i < nfds; i++) {
2457144467Sharti				if (kev[i].flags & EV_ERROR) {
2458144467Sharti					warnc(kev[i].data, "kevent");
2459144467Sharti					continue;
2460144467Sharti				}
2461144467Sharti				switch (kev[i].filter) {
2462144467Sharti				  case EVFILT_READ:
2463144467Sharti					JobDoOutput(kev[i].udata, FALSE);
2464144467Sharti					break;
2465144467Sharti				  case EVFILT_PROC:
2466144467Sharti					/*
2467144467Sharti					 * Just wake up and let
2468144467Sharti					 * Job_CatchChildren() collect the
2469144467Sharti					 * terminated job.
2470144467Sharti					 */
2471144467Sharti					break;
2472144467Sharti				}
2473144467Sharti			}
2474104475Sphk		}
2475104475Sphk#else
2476144467Sharti		readfds = outputs;
2477144467Sharti		timeout.tv_sec = SEL_SEC;
2478144467Sharti		timeout.tv_usec = SEL_USEC;
2479144467Sharti		if (flag && jobFull && fifoFd >= 0)
2480144467Sharti			FD_SET(fifoFd, &readfds);
24811590Srgrimes
2482144467Sharti		nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
2483144467Sharti		    (fd_set *)NULL, &timeout);
2484144467Sharti		if (nfds <= 0) {
2485144467Sharti			if (interrupted)
2486144467Sharti				JobPassSig(interrupted);
2487144467Sharti			return;
2488144467Sharti		}
2489144467Sharti		if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2490144467Sharti			if (--nfds <= 0)
2491144467Sharti				return;
2492144467Sharti		}
2493144494Sharti		job = TAILQ_FIRST(&jobs);
2494144494Sharti		while (nfds != 0 && job != NULL) {
2495144467Sharti			if (FD_ISSET(job->inPipe, &readfds)) {
2496144467Sharti				JobDoOutput(job, FALSE);
2497144494Sharti				nfds--;
2498144467Sharti			}
2499144494Sharti			job = TAILQ_NEXT(job, link);
2500144467Sharti		}
2501144467Sharti#endif /* !USE_KQUEUE */
2502137606Sphk	}
25031590Srgrimes}
25041590Srgrimes
2505144467Sharti/**
2506144467Sharti * Job_Make
25071590Srgrimes *	Start the creation of a target. Basically a front-end for
25081590Srgrimes *	JobStart used by the Make module.
25091590Srgrimes *
25101590Srgrimes * Side Effects:
25111590Srgrimes *	Another job is started.
25121590Srgrimes */
25131590Srgrimesvoid
2514104696SjmallettJob_Make(GNode *gn)
25151590Srgrimes{
2516138232Sharti
2517144467Sharti	JobStart(gn, 0, NULL);
25181590Srgrimes}
25191590Srgrimes
2520144467Sharti/**
2521144467Sharti * JobCopyShell
2522144467Sharti *	Make a new copy of the shell structure including a copy of the strings
2523144467Sharti *	in it. This also defaults some fields in case they are NULL.
2524138079Sharti *
2525144467Sharti * Returns:
2526144467Sharti *	The function returns a pointer to the new shell structure.
2527138079Sharti */
2528144483Shartistatic struct Shell *
2529144483ShartiJobCopyShell(const struct Shell *osh)
2530138079Sharti{
2531144483Sharti	struct Shell *nsh;
2532138079Sharti
2533138079Sharti	nsh = emalloc(sizeof(*nsh));
2534138079Sharti	nsh->name = estrdup(osh->name);
2535138079Sharti
2536138079Sharti	if (osh->echoOff != NULL)
2537138079Sharti		nsh->echoOff = estrdup(osh->echoOff);
2538138079Sharti	else
2539138079Sharti		nsh->echoOff = NULL;
2540138079Sharti	if (osh->echoOn != NULL)
2541138079Sharti		nsh->echoOn = estrdup(osh->echoOn);
2542138079Sharti	else
2543138079Sharti		nsh->echoOn = NULL;
2544138079Sharti	nsh->hasEchoCtl = osh->hasEchoCtl;
2545138079Sharti
2546138079Sharti	if (osh->noPrint != NULL)
2547138079Sharti		nsh->noPrint = estrdup(osh->noPrint);
2548138079Sharti	else
2549138079Sharti		nsh->noPrint = NULL;
2550138079Sharti
2551138079Sharti	nsh->hasErrCtl = osh->hasErrCtl;
2552138079Sharti	if (osh->errCheck == NULL)
2553138079Sharti		nsh->errCheck = estrdup("");
2554138079Sharti	else
2555138079Sharti		nsh->errCheck = estrdup(osh->errCheck);
2556138079Sharti	if (osh->ignErr == NULL)
2557138079Sharti		nsh->ignErr = estrdup("%s");
2558138079Sharti	else
2559138079Sharti		nsh->ignErr = estrdup(osh->ignErr);
2560138079Sharti
2561138079Sharti	if (osh->echo == NULL)
2562138079Sharti		nsh->echo = estrdup("");
2563138079Sharti	else
2564138079Sharti		nsh->echo = estrdup(osh->echo);
2565138079Sharti
2566138079Sharti	if (osh->exit == NULL)
2567138079Sharti		nsh->exit = estrdup("");
2568138079Sharti	else
2569138079Sharti		nsh->exit = estrdup(osh->exit);
2570138079Sharti
2571138079Sharti	return (nsh);
2572138079Sharti}
2573138079Sharti
2574144467Sharti/**
2575144467Sharti * JobFreeShell
2576144467Sharti *	Free a shell structure and all associated strings.
2577138079Sharti */
2578138079Shartistatic void
2579144483ShartiJobFreeShell(struct Shell *sh)
2580138079Sharti{
2581138079Sharti
2582138079Sharti	if (sh != NULL) {
2583138079Sharti		free(sh->name);
2584138079Sharti		free(sh->echoOff);
2585138079Sharti		free(sh->echoOn);
2586138079Sharti		free(sh->noPrint);
2587138079Sharti		free(sh->errCheck);
2588138079Sharti		free(sh->ignErr);
2589138079Sharti		free(sh->echo);
2590138079Sharti		free(sh->exit);
2591138079Sharti		free(sh);
2592138079Sharti	}
2593138079Sharti}
2594138079Sharti
2595136840Sruvoid
2596136840SruShell_Init(void)
2597136840Sru{
2598138079Sharti
2599144467Sharti	if (commandShell == NULL)
2600144467Sharti		commandShell = JobMatchShell(shells[DEFSHELL].name);
2601138079Sharti
2602144467Sharti	if (shellPath == NULL) {
2603144467Sharti		/*
2604144467Sharti		 * The user didn't specify a shell to use, so we are using the
2605144467Sharti		 * default one... Both the absolute path and the last component
2606144467Sharti		 * must be set. The last component is taken from the 'name'
2607144467Sharti		 * field of the default shell description pointed-to by
2608144467Sharti		 * commandShell. All default shells are located in
2609144467Sharti		 * PATH_DEFSHELLDIR.
2610144467Sharti		 */
2611144467Sharti		shellName = commandShell->name;
2612144467Sharti		shellPath = str_concat(PATH_DEFSHELLDIR, shellName,
2613144467Sharti		    STR_ADDSLASH);
2614144467Sharti	}
2615136840Sru}
2616136840Sru
2617144467Sharti/**
2618144467Sharti * Job_Init
2619137572Sphk *	Initialize the process module, given a maximum number of jobs.
26201590Srgrimes *
26211590Srgrimes * Side Effects:
26221590Srgrimes *	lists and counters are initialized
26231590Srgrimes */
26241590Srgrimesvoid
2625137572SphkJob_Init(int maxproc)
26261590Srgrimes{
2627144467Sharti	GNode		*begin;	/* node for commands to do at the very start */
2628144467Sharti	const char	*env;
2629144467Sharti	struct sigaction sa;
26301590Srgrimes
2631144467Sharti	fifoFd = -1;
2632144467Sharti	env = getenv("MAKE_JOBS_FIFO");
2633137606Sphk
2634144467Sharti	if (env == NULL && maxproc > 1) {
2635144467Sharti		/*
2636144467Sharti		 * We did not find the environment variable so we are the
2637144467Sharti		 * leader. Create the fifo, open it, write one char per
2638144467Sharti		 * allowed job into the pipe.
2639144467Sharti		 */
2640146155Sharti		fifoFd = mkfifotemp(fifoName);
2641146155Sharti		if (fifoFd < 0) {
2642146155Sharti			env = NULL;
2643146155Sharti		} else {
2644146155Sharti			fifoMaster = 1;
2645146155Sharti			fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2646146155Sharti			env = fifoName;
2647146155Sharti			setenv("MAKE_JOBS_FIFO", env, 1);
2648146155Sharti			while (maxproc-- > 0) {
2649146155Sharti				write(fifoFd, "+", 1);
2650144467Sharti			}
2651146155Sharti			/* The master make does not get a magic token */
2652146155Sharti			jobFull = TRUE;
2653146155Sharti			maxJobs = 0;
2654137606Sphk		}
2655144467Sharti
2656144467Sharti	} else if (env != NULL) {
2657144467Sharti		/*
2658144467Sharti		 * We had the environment variable so we are a slave.
2659144467Sharti		 * Open fifo and give ourselves a magic token which represents
2660144467Sharti		 * the token our parent make has grabbed to start his make
2661144467Sharti		 * process. Otherwise the sub-makes would gobble up tokens and
2662144467Sharti		 * the proper number of tokens to specify to -j would depend
2663144467Sharti		 * on the depth of the tree and the order of execution.
2664144467Sharti		 */
2665144467Sharti		fifoFd = open(env, O_RDWR, 0);
2666144467Sharti		if (fifoFd >= 0) {
2667144467Sharti			fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2668144467Sharti			maxJobs = 1;
2669144467Sharti			jobFull = FALSE;
2670144467Sharti		}
2671137606Sphk	}
2672144467Sharti	if (fifoFd <= 0) {
2673144467Sharti		maxJobs = maxproc;
2674144467Sharti		jobFull = FALSE;
2675144467Sharti	} else {
2676137606Sphk	}
2677144467Sharti	nJobs = 0;
26781590Srgrimes
2679144467Sharti	aborting = 0;
2680144467Sharti	errors = 0;
26811590Srgrimes
2682144467Sharti	lastNode = NULL;
26831590Srgrimes
2684144467Sharti	if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2685144467Sharti		/*
2686144467Sharti		 * If only one job can run at a time, there's no need for a
2687144467Sharti		 * banner, no is there?
2688144467Sharti		 */
2689144467Sharti		targFmt = "";
2690144467Sharti	} else {
2691144467Sharti		targFmt = TARG_FMT;
2692144467Sharti	}
2693144467Sharti
2694144467Sharti	Shell_Init();
2695144467Sharti
26961590Srgrimes	/*
2697144467Sharti	 * Catch the four signals that POSIX specifies if they aren't ignored.
2698144467Sharti	 * JobCatchSignal will just set global variables and hope someone
2699144467Sharti	 * else is going to handle the interrupt.
27001590Srgrimes	 */
2701144467Sharti	sa.sa_handler = JobCatchSig;
2702144467Sharti	sigemptyset(&sa.sa_mask);
2703144467Sharti	sa.sa_flags = 0;
27048874Srgrimes
2705144467Sharti	if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2706144467Sharti		sigaction(SIGINT, &sa, NULL);
2707144467Sharti	}
2708144467Sharti	if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2709144467Sharti		sigaction(SIGHUP, &sa, NULL);
2710144467Sharti	}
2711144467Sharti	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2712144467Sharti		sigaction(SIGQUIT, &sa, NULL);
2713144467Sharti	}
2714144467Sharti	if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2715144467Sharti		sigaction(SIGTERM, &sa, NULL);
2716144467Sharti	}
2717144467Sharti	/*
2718144467Sharti	 * There are additional signals that need to be caught and passed if
2719144467Sharti	 * either the export system wants to be told directly of signals or if
2720144467Sharti	 * we're giving each job its own process group (since then it won't get
2721144467Sharti	 * signals from the terminal driver as we own the terminal)
2722144467Sharti	 */
2723137202Sharti#if defined(USE_PGRP)
2724144467Sharti	if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2725144467Sharti		sigaction(SIGTSTP, &sa, NULL);
2726144467Sharti	}
2727144467Sharti	if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2728144467Sharti		sigaction(SIGTTOU, &sa, NULL);
2729144467Sharti	}
2730144467Sharti	if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2731144467Sharti		sigaction(SIGTTIN, &sa, NULL);
2732144467Sharti	}
2733144467Sharti	if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2734144467Sharti		sigaction(SIGWINCH, &sa, NULL);
2735144467Sharti	}
27361590Srgrimes#endif
27378874Srgrimes
2738104475Sphk#ifdef USE_KQUEUE
2739144467Sharti	if ((kqfd = kqueue()) == -1) {
2740144467Sharti		Punt("kqueue: %s", strerror(errno));
2741144467Sharti	}
2742104475Sphk#endif
2743104475Sphk
2744144467Sharti	begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
27451590Srgrimes
2746144467Sharti	if (begin != NULL) {
2747144467Sharti		JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2748144467Sharti		while (nJobs) {
2749144467Sharti			Job_CatchOutput(0);
2750144467Sharti			Job_CatchChildren(!usePipes);
2751144467Sharti		}
27521590Srgrimes	}
2753144467Sharti	postCommands = Targ_FindNode(".END", TARG_CREATE);
27541590Srgrimes}
27551590Srgrimes
2756144467Sharti/**
2757144467Sharti * Job_Full
27581590Srgrimes *	See if the job table is full. It is considered full if it is OR
27591590Srgrimes *	if we are in the process of aborting OR if we have
27601590Srgrimes *	reached/exceeded our local quota. This prevents any more jobs
27611590Srgrimes *	from starting up.
27621590Srgrimes *
27631590Srgrimes * Results:
27641590Srgrimes *	TRUE if the job table is full, FALSE otherwise
27651590Srgrimes */
27661590SrgrimesBoolean
2767104696SjmallettJob_Full(void)
27681590Srgrimes{
2769144467Sharti	char c;
2770144467Sharti	int i;
2771137606Sphk
2772144467Sharti	if (aborting)
2773144467Sharti		return (aborting);
2774144467Sharti	if (fifoFd >= 0 && jobFull) {
2775144467Sharti		i = read(fifoFd, &c, 1);
2776144467Sharti		if (i > 0) {
2777144467Sharti			maxJobs++;
2778144467Sharti			jobFull = FALSE;
2779144467Sharti		}
2780137606Sphk	}
2781144467Sharti	return (jobFull);
27821590Srgrimes}
27831590Srgrimes
2784144467Sharti/**
2785144467Sharti * Job_Empty
27861590Srgrimes *	See if the job table is empty.  Because the local concurrency may
27871590Srgrimes *	be set to 0, it is possible for the job table to become empty,
27881590Srgrimes *	while the list of stoppedJobs remains non-empty. In such a case,
27891590Srgrimes *	we want to restart as many jobs as we can.
27901590Srgrimes *
27911590Srgrimes * Results:
27921590Srgrimes *	TRUE if it is. FALSE if it ain't.
27931590Srgrimes */
27941590SrgrimesBoolean
2795104696SjmallettJob_Empty(void)
27961590Srgrimes{
2797144467Sharti	if (nJobs == 0) {
2798144494Sharti		if (!TAILQ_EMPTY(&stoppedJobs) && !aborting) {
2799144467Sharti			/*
2800144467Sharti			 * The job table is obviously not full if it has no
2801144467Sharti			 * jobs in it...Try and restart the stopped jobs.
2802144467Sharti			 */
2803144467Sharti			jobFull = FALSE;
2804144467Sharti			JobRestartJobs();
2805144467Sharti			return (FALSE);
2806144467Sharti		} else {
2807144467Sharti			return (TRUE);
2808144467Sharti		}
28091590Srgrimes	} else {
2810144467Sharti		return (FALSE);
28111590Srgrimes	}
28121590Srgrimes}
28131590Srgrimes
2814144467Sharti/**
2815144467Sharti * JobMatchShell
28161590Srgrimes *	Find a matching shell in 'shells' given its final component.
28171590Srgrimes *
28181590Srgrimes * Results:
2819138334Sharti *	A pointer to a freshly allocated Shell structure with a copy
2820138228Sharti *	of the static structure or NULL if no shell with the given name
2821138228Sharti *	is found.
28221590Srgrimes */
2823144483Shartistatic struct Shell *
2824138228ShartiJobMatchShell(const char *name)
28251590Srgrimes{
2826144467Sharti	const struct CShell	*sh;	      /* Pointer into shells table */
2827144483Sharti	struct Shell		*nsh;
28281590Srgrimes
2829144467Sharti	for (sh = shells; sh < shells + sizeof(shells)/sizeof(shells[0]); sh++)
2830144467Sharti		if (strcmp(sh->name, name) == 0)
2831144467Sharti			break;
28321590Srgrimes
2833144467Sharti	if (sh == shells + sizeof(shells)/sizeof(shells[0]))
2834144467Sharti		return (NULL);
2835138228Sharti
2836144467Sharti	/* make a copy */
2837144467Sharti	nsh = emalloc(sizeof(*nsh));
2838138228Sharti
2839144467Sharti	nsh->name = estrdup(sh->name);
2840144467Sharti	nsh->echoOff = estrdup(sh->echoOff);
2841144467Sharti	nsh->echoOn = estrdup(sh->echoOn);
2842144467Sharti	nsh->hasEchoCtl = sh->hasEchoCtl;
2843144467Sharti	nsh->noPrint = estrdup(sh->noPrint);
2844144467Sharti	nsh->hasErrCtl = sh->hasErrCtl;
2845144467Sharti	nsh->errCheck = estrdup(sh->errCheck);
2846144467Sharti	nsh->ignErr = estrdup(sh->ignErr);
2847144467Sharti	nsh->echo = estrdup(sh->echo);
2848144467Sharti	nsh->exit = estrdup(sh->exit);
2849138228Sharti
2850144467Sharti	return (nsh);
28511590Srgrimes}
28521590Srgrimes
2853144467Sharti/**
2854144467Sharti * Job_ParseShell
28551590Srgrimes *	Parse a shell specification and set up commandShell, shellPath
28561590Srgrimes *	and shellName appropriately.
28571590Srgrimes *
28581590Srgrimes * Results:
28591590Srgrimes *	FAILURE if the specification was incorrect.
28601590Srgrimes *
28611590Srgrimes * Side Effects:
28621590Srgrimes *	commandShell points to a Shell structure (either predefined or
28631590Srgrimes *	created from the shell spec), shellPath is the full path of the
28641590Srgrimes *	shell described by commandShell, while shellName is just the
28651590Srgrimes *	final component of shellPath.
28661590Srgrimes *
28671590Srgrimes * Notes:
28681590Srgrimes *	A shell specification consists of a .SHELL target, with dependency
28691590Srgrimes *	operator, followed by a series of blank-separated words. Double
28701590Srgrimes *	quotes can be used to use blanks in words. A backslash escapes
28711590Srgrimes *	anything (most notably a double-quote and a space) and
28721590Srgrimes *	provides the functionality it does in C. Each word consists of
28731590Srgrimes *	keyword and value separated by an equal sign. There should be no
28741590Srgrimes *	unnecessary spaces in the word. The keywords are as follows:
2875146061Sharti *	    name	    Name of shell.
2876146061Sharti *	    path	    Location of shell. Overrides "name" if given
2877146061Sharti *	    quiet	    Command to turn off echoing.
2878146061Sharti *	    echo	    Command to turn echoing on
28791590Srgrimes *	    filter	    Result of turning off echoing that shouldn't be
2880146061Sharti *			    printed.
28811590Srgrimes *	    echoFlag	    Flag to turn echoing on at the start
28821590Srgrimes *	    errFlag	    Flag to turn error checking on at the start
28831590Srgrimes *	    hasErrCtl	    True if shell has error checking control
2884146061Sharti *	    check	    Command to turn on error checking if hasErrCtl
2885146061Sharti *			    is TRUE or template of command to echo a command
2886146061Sharti *			    for which error checking is off if hasErrCtl is
2887146061Sharti *			    FALSE.
28881590Srgrimes *	    ignore	    Command to turn off error checking if hasErrCtl
2889146061Sharti *			    is TRUE or template of command to execute a
2890146061Sharti *			    command so as to ignore any errors it returns if
2891146061Sharti *			    hasErrCtl is FALSE.
28921590Srgrimes */
28931590SrgrimesReturnStatus
2894104696SjmallettJob_ParseShell(char *line)
28951590Srgrimes{
2896144467Sharti	char	**words;
2897144467Sharti	int	wordCount;
2898144467Sharti	char	**argv;
2899144467Sharti	int	argc;
2900144467Sharti	char	*path;
2901144741Sharti	char	*eq;
2902144467Sharti	Boolean	fullSpec = FALSE;
2903144483Sharti	struct Shell	newShell;
2904144483Sharti	struct Shell	*sh;
29051590Srgrimes
2906144467Sharti	while (isspace((unsigned char)*line)) {
2907144467Sharti		line++;
2908144467Sharti	}
29091590Srgrimes
2910144467Sharti	memset(&newShell, 0, sizeof(newShell));
2911144741Sharti	path = NULL;
29128874Srgrimes
29131590Srgrimes	/*
2914144741Sharti	 * Parse the specification by keyword but skip the first word - it
2915144741Sharti	 * is not set by brk_string.
29161590Srgrimes	 */
2917146147Sharti	words = brk_string(line, &wordCount, TRUE);
2918146147Sharti	words++;
2919144741Sharti	wordCount--;
2920144741Sharti
2921144741Sharti	for (argc = wordCount, argv = words; argc != 0; argc--, argv++) {
2922144741Sharti		/*
2923144741Sharti		 * Split keyword and value
2924144741Sharti		 */
2925144741Sharti		if ((eq = strchr(*argv, '=')) == NULL) {
2926144741Sharti			Parse_Error(PARSE_FATAL, "missing '=' in shell "
2927144741Sharti			    "specification keyword '%s'", *argv);
2928144741Sharti			return (FAILURE);
2929144741Sharti		}
2930144741Sharti		*eq++ = '\0';
2931144741Sharti
2932144741Sharti		if (strcmp(*argv, "path") == 0) {
2933144741Sharti			path = eq;
2934144741Sharti		} else if (strcmp(*argv, "name") == 0) {
2935144741Sharti			newShell.name = eq;
2936144741Sharti		} else if (strcmp(*argv, "quiet") == 0) {
2937144741Sharti			newShell.echoOff = eq;
2938144741Sharti			fullSpec = TRUE;
2939144741Sharti		} else if (strcmp(*argv, "echo") == 0) {
2940144741Sharti			newShell.echoOn = eq;
2941144741Sharti			fullSpec = TRUE;
2942144741Sharti		} else if (strcmp(*argv, "filter") == 0) {
2943144741Sharti			newShell.noPrint = eq;
2944144741Sharti			fullSpec = TRUE;
2945144741Sharti		} else if (strcmp(*argv, "echoFlag") == 0) {
2946144741Sharti			newShell.echo = eq;
2947144741Sharti			fullSpec = TRUE;
2948144741Sharti		} else if (strcmp(*argv, "errFlag") == 0) {
2949144741Sharti			newShell.exit = eq;
2950144741Sharti			fullSpec = TRUE;
2951144741Sharti		} else if (strcmp(*argv, "hasErrCtl") == 0) {
2952144741Sharti			newShell.hasErrCtl = (*eq == 'Y' || *eq == 'y' ||
2953144741Sharti			    *eq == 'T' || *eq == 't');
2954144741Sharti			fullSpec = TRUE;
2955144741Sharti		} else if (strcmp(*argv, "check") == 0) {
2956144741Sharti			newShell.errCheck = eq;
2957144741Sharti			fullSpec = TRUE;
2958144741Sharti		} else if (strcmp(*argv, "ignore") == 0) {
2959144741Sharti			newShell.ignErr = eq;
2960144741Sharti			fullSpec = TRUE;
2961144467Sharti		} else {
2962144741Sharti			Parse_Error(PARSE_FATAL, "unknown keyword in shell "
2963144741Sharti			    "specification '%s'", *argv);
2964144741Sharti			return (FAILURE);
2965144467Sharti		}
29661590Srgrimes	}
2967138079Sharti
29681590Srgrimes	/*
2969144467Sharti	 * Some checks (could be more)
29701590Srgrimes	 */
2971144467Sharti	if (fullSpec) {
2972144467Sharti		if ((newShell.echoOn != NULL) ^ (newShell.echoOff != NULL))
2973144467Sharti			Parse_Error(PARSE_FATAL, "Shell must have either both "
2974144467Sharti			    "echoOff and echoOn or none of them");
2975144467Sharti
2976144467Sharti		if (newShell.echoOn != NULL && newShell.echoOff)
2977144467Sharti			newShell.hasEchoCtl = TRUE;
29781590Srgrimes	}
2979138079Sharti
2980144467Sharti	if (path == NULL) {
2981144467Sharti		/*
2982144467Sharti		 * If no path was given, the user wants one of the pre-defined
2983144467Sharti		 * shells, yes? So we find the one s/he wants with the help of
2984144467Sharti		 * JobMatchShell and set things up the right way. shellPath
2985144467Sharti		 * will be set up by Job_Init.
2986144467Sharti		 */
2987144467Sharti		if (newShell.name == NULL) {
2988144467Sharti			Parse_Error(PARSE_FATAL,
2989144467Sharti			    "Neither path nor name specified");
2990144467Sharti			return (FAILURE);
2991144467Sharti		}
2992144467Sharti		if ((sh = JobMatchShell(newShell.name)) == NULL) {
2993144467Sharti			Parse_Error(PARSE_FATAL, "%s: no matching shell",
2994144467Sharti			    newShell.name);
2995144467Sharti			return (FAILURE);
2996144467Sharti		}
2997144467Sharti
29981590Srgrimes	} else {
2999144467Sharti		/*
3000144467Sharti		 * The user provided a path. If s/he gave nothing else
3001144467Sharti		 * (fullSpec is FALSE), try and find a matching shell in the
3002144467Sharti		 * ones we know of. Else we just take the specification at its
3003144467Sharti		 * word and copy it to a new location. In either case, we need
3004144467Sharti		 * to record the path the user gave for the shell.
3005144467Sharti		 */
3006144467Sharti		free(shellPath);
3007144467Sharti		shellPath = estrdup(path);
3008144467Sharti		if (newShell.name == NULL) {
3009144467Sharti			/* get the base name as the name */
3010144467Sharti			path = strrchr(path, '/');
3011144467Sharti			if (path == NULL) {
3012144467Sharti				path = shellPath;
3013144467Sharti			} else {
3014144467Sharti				path += 1;
3015144467Sharti			}
3016144467Sharti			newShell.name = path;
3017144467Sharti		}
3018144467Sharti
3019144467Sharti		if (!fullSpec) {
3020144467Sharti			if ((sh = JobMatchShell(newShell.name)) == NULL) {
3021144467Sharti				Parse_Error(PARSE_FATAL,
3022144467Sharti				    "%s: no matching shell", newShell.name);
3023144467Sharti				return (FAILURE);
3024144467Sharti			}
3025144467Sharti		} else {
3026144467Sharti			sh = JobCopyShell(&newShell);
3027144467Sharti		}
30281590Srgrimes	}
30291590Srgrimes
3030144467Sharti	/* set the new shell */
3031144467Sharti	JobFreeShell(commandShell);
3032144467Sharti	commandShell = sh;
30338874Srgrimes
3034144467Sharti	shellName = commandShell->name;
30358874Srgrimes
3036144467Sharti	return (SUCCESS);
30371590Srgrimes}
30381590Srgrimes
3039144467Sharti/**
3040144467Sharti * JobInterrupt
30411590Srgrimes *	Handle the receipt of an interrupt.
30421590Srgrimes *
30431590Srgrimes * Side Effects:
30441590Srgrimes *	All children are killed. Another job will be started if the
30451590Srgrimes *	.INTERRUPT target was given.
30461590Srgrimes */
30471590Srgrimesstatic void
3048104696SjmallettJobInterrupt(int runINTERRUPT, int signo)
30491590Srgrimes{
3050144467Sharti	Job	*job;		/* job descriptor in that element */
3051144467Sharti	GNode	*interrupt;	/* the node describing the .INTERRUPT target */
30528874Srgrimes
3053144467Sharti	aborting = ABORT_INTERRUPT;
30541590Srgrimes
3055144494Sharti	TAILQ_FOREACH(job, &jobs, link) {
3056144467Sharti		if (!Targ_Precious(job->node)) {
3057144467Sharti			char *file = (job->node->path == NULL ?
3058144467Sharti			    job->node->name : job->node->path);
3059144467Sharti
3060144467Sharti			if (!noExecute && eunlink(file) != -1) {
3061144467Sharti				Error("*** %s removed", file);
3062144467Sharti			}
3063144467Sharti		}
3064144467Sharti		if (job->pid) {
3065144467Sharti			DEBUGF(JOB, ("JobInterrupt passing signal to child "
3066144665Sharti			    "%jd.\n", (intmax_t)job->pid));
3067144467Sharti			KILL(job->pid, signo);
3068144467Sharti		}
30691590Srgrimes	}
307018730Ssteve
3071144467Sharti	if (runINTERRUPT && !touchFlag) {
3072144467Sharti		/*
3073144467Sharti		 * clear the interrupted flag because we would get an
3074144467Sharti		 * infinite loop otherwise.
3075144467Sharti		 */
3076144467Sharti		interrupted = 0;
3077137605Sharti
3078144467Sharti		interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
3079144467Sharti		if (interrupt != NULL) {
3080144467Sharti			ignoreErrors = FALSE;
30811590Srgrimes
3082144467Sharti			JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
3083144467Sharti			while (nJobs) {
3084144467Sharti				Job_CatchOutput(0);
3085144467Sharti				Job_CatchChildren(!usePipes);
3086144467Sharti			}
3087144467Sharti		}
30881590Srgrimes	}
30891590Srgrimes}
30901590Srgrimes
3091144467Sharti/**
3092144467Sharti * Job_Finish
30931590Srgrimes *	Do final processing such as the running of the commands
30948874Srgrimes *	attached to the .END target.
30951590Srgrimes *
30961590Srgrimes * Results:
30971590Srgrimes *	Number of errors reported.
30981590Srgrimes */
30991590Srgrimesint
3100104696SjmallettJob_Finish(void)
31011590Srgrimes{
3102138232Sharti
3103144467Sharti	if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
3104144467Sharti		if (errors) {
3105144467Sharti			Error("Errors reported so .END ignored");
3106144467Sharti		} else {
3107144467Sharti			JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
31081590Srgrimes
3109144467Sharti			while (nJobs) {
3110144467Sharti				Job_CatchOutput(0);
3111144467Sharti				Job_CatchChildren(!usePipes);
3112144467Sharti			}
3113144467Sharti		}
31141590Srgrimes	}
3115144467Sharti	if (fifoFd >= 0) {
3116144467Sharti		close(fifoFd);
3117144467Sharti		fifoFd = -1;
3118144467Sharti		if (fifoMaster)
3119144467Sharti			unlink(fifoName);
3120144467Sharti	}
3121144467Sharti	return (errors);
31221590Srgrimes}
31231590Srgrimes
3124144467Sharti/**
3125144467Sharti * Job_Wait
31261590Srgrimes *	Waits for all running jobs to finish and returns. Sets 'aborting'
31271590Srgrimes *	to ABORT_WAIT to prevent other jobs from starting.
31281590Srgrimes *
31291590Srgrimes * Side Effects:
31301590Srgrimes *	Currently running jobs finish.
31311590Srgrimes */
31321590Srgrimesvoid
3133104696SjmallettJob_Wait(void)
31341590Srgrimes{
3135138232Sharti
3136144467Sharti	aborting = ABORT_WAIT;
3137144467Sharti	while (nJobs != 0) {
3138144467Sharti		Job_CatchOutput(0);
3139144467Sharti		Job_CatchChildren(!usePipes);
3140144467Sharti	}
3141144467Sharti	aborting = 0;
31421590Srgrimes}
31431590Srgrimes
3144144467Sharti/**
3145144467Sharti * Job_AbortAll
31461590Srgrimes *	Abort all currently running jobs without handling output or anything.
31471590Srgrimes *	This function is to be called only in the event of a major
31481590Srgrimes *	error. Most definitely NOT to be called from JobInterrupt.
31491590Srgrimes *
31501590Srgrimes * Side Effects:
31511590Srgrimes *	All children are killed, not just the firstborn
31521590Srgrimes */
31531590Srgrimesvoid
3154104696SjmallettJob_AbortAll(void)
31551590Srgrimes{
3156144467Sharti	Job	*job;	/* the job descriptor in that element */
3157144467Sharti	int	foo;
31588874Srgrimes
3159144467Sharti	aborting = ABORT_ERROR;
31608874Srgrimes
3161144467Sharti	if (nJobs) {
3162144494Sharti		TAILQ_FOREACH(job, &jobs, link) {
3163144467Sharti			/*
3164144467Sharti			 * kill the child process with increasingly drastic
3165144467Sharti			 * signals to make darn sure it's dead.
3166144467Sharti			 */
3167144467Sharti			KILL(job->pid, SIGINT);
3168144467Sharti			KILL(job->pid, SIGKILL);
3169144467Sharti		}
31701590Srgrimes	}
31718874Srgrimes
3172144467Sharti	/*
3173144467Sharti	 * Catch as many children as want to report in at first, then give up
3174144467Sharti	 */
3175144467Sharti	while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
3176144665Sharti		;
31771590Srgrimes}
317818730Ssteve
3179144467Sharti/**
3180144467Sharti * JobRestartJobs
318118730Ssteve *	Tries to restart stopped jobs if there are slots available.
318218730Ssteve *	Note that this tries to restart them regardless of pending errors.
318318730Ssteve *	It's not good to leave stopped jobs lying around!
318418730Ssteve *
318518730Ssteve * Side Effects:
318618730Ssteve *	Resumes(and possibly migrates) jobs.
318718730Ssteve */
318818730Sstevestatic void
3189104696SjmallettJobRestartJobs(void)
319018730Ssteve{
3191144494Sharti	Job *job;
3192144494Sharti
3193144494Sharti	while (!jobFull && (job = TAILQ_FIRST(&stoppedJobs)) != NULL) {
3194144467Sharti		DEBUGF(JOB, ("Job queue is not full. "
3195144467Sharti		    "Restarting a stopped job.\n"));
3196144494Sharti		TAILQ_REMOVE(&stoppedJobs, job, link);
3197144494Sharti		JobRestart(job);
3198144467Sharti	}
319918730Ssteve}
3200146054Sharti
3201146054Sharti/**
3202146054Sharti * Cmd_Exec
3203146054Sharti *	Execute the command in cmd, and return the output of that command
3204146054Sharti *	in a string.
3205146054Sharti *
3206146054Sharti * Results:
3207146054Sharti *	A string containing the output of the command, or the empty string
3208146054Sharti *	If error is not NULL, it contains the reason for the command failure
3209146129Sharti *	Any output sent to stderr in the child process is passed to stderr,
3210146129Sharti *	and not captured in the string.
3211146054Sharti *
3212146054Sharti * Side Effects:
3213146054Sharti *	The string must be freed by the caller.
3214146054Sharti */
3215146054ShartiBuffer *
3216146054ShartiCmd_Exec(const char *cmd, const char **error)
3217146054Sharti{
3218146054Sharti	int	fds[2];	/* Pipe streams */
3219146054Sharti	int	status;	/* command exit status */
3220146054Sharti	Buffer	*buf;	/* buffer to store the result */
3221146054Sharti	ssize_t	rcnt;
3222146129Sharti	ProcStuff	ps;
3223146054Sharti
3224146054Sharti	*error = NULL;
3225146054Sharti	buf = Buf_Init(0);
3226146054Sharti
3227146054Sharti	if (shellPath == NULL)
3228146054Sharti		Shell_Init();
3229146054Sharti	/*
3230146054Sharti	 * Open a pipe for fetching its output
3231146054Sharti	 */
3232146054Sharti	if (pipe(fds) == -1) {
3233146054Sharti		*error = "Couldn't create pipe for \"%s\"";
3234146054Sharti		return (buf);
3235146054Sharti	}
3236146054Sharti
3237146129Sharti	/* Set close-on-exec on read side of pipe. */
3238146129Sharti	fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC);
3239146129Sharti
3240146129Sharti	ps.in = STDIN_FILENO;
3241146129Sharti	ps.out = fds[1];
3242146129Sharti	ps.err = STDERR_FILENO;
3243146129Sharti
3244146129Sharti	ps.merge_errors = 0;
3245146129Sharti	ps.pgroup = 0;
3246146129Sharti	ps.searchpath = 0;
3247146129Sharti
3248146129Sharti	/* Set up arguments for shell */
3249146129Sharti	ps.argv = emalloc(4 * sizeof(char *));
3250146129Sharti	ps.argv[0] = strdup(shellName);
3251146129Sharti	ps.argv[1] = strdup("-c");
3252146129Sharti	ps.argv[2] = strdup(cmd);
3253146129Sharti	ps.argv[3] = NULL;
3254146129Sharti
3255146054Sharti	/*
3256146129Sharti	 * Fork.  Warning since we are doing vfork() instead of fork(),
3257146129Sharti	 * do not allocate memory in the child process!
3258146054Sharti	 */
3259146130Sharti	if ((ps.child_pid = vfork()) == -1) {
3260146058Sharti		*error = "Couldn't exec \"%s\"";
3261146058Sharti		return (buf);
3262146058Sharti
3263146130Sharti	} else if (ps.child_pid == 0) {
3264146129Sharti  		/*
3265146129Sharti		 * Child
3266146129Sharti  		 */
3267146129Sharti		ProcExec(&ps);
3268146129Sharti		/* NOTREACHED */
3269146129Sharti	}
3270146054Sharti
3271146129Sharti	free(ps.argv[2]);
3272146129Sharti	free(ps.argv[1]);
3273146129Sharti	free(ps.argv[0]);
3274146129Sharti	free(ps.argv);
3275146054Sharti
3276146129Sharti	close(fds[1]); /* No need for the writing half of the pipe. */
3277146054Sharti
3278146058Sharti	do {
3279146058Sharti		char	result[BUFSIZ];
3280146054Sharti
3281146058Sharti		rcnt = read(fds[0], result, sizeof(result));
3282146058Sharti		if (rcnt != -1)
3283146058Sharti			Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
3284146058Sharti	} while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
3285146054Sharti
3286146058Sharti	if (rcnt == -1)
3287146058Sharti		*error = "Error reading shell's output for \"%s\"";
3288146054Sharti
3289146058Sharti	/*
3290146058Sharti	 * Close the input side of the pipe.
3291146058Sharti	 */
3292146058Sharti	close(fds[0]);
3293146054Sharti
3294146130Sharti	status = ProcWait(&ps);
3295146054Sharti
3296146058Sharti	if (status)
3297146058Sharti		*error = "\"%s\" returned non-zero status";
3298146054Sharti
3299146058Sharti	Buf_StripNewlines(buf);
3300146054Sharti
3301146054Sharti	return (buf);
3302146054Sharti}
3303146054Sharti
3304146056Sharti
3305146056Sharti/*
3306146056Sharti * Interrupt handler - set flag and defer handling to the main code
3307146056Sharti */
3308146056Shartistatic void
3309146056ShartiCompatCatchSig(int signo)
3310146056Sharti{
3311146056Sharti
3312146056Sharti	interrupted = signo;
3313146056Sharti}
3314146056Sharti
3315146056Sharti/*-
3316146056Sharti *-----------------------------------------------------------------------
3317146056Sharti * CompatInterrupt --
3318146056Sharti *	Interrupt the creation of the current target and remove it if
3319146056Sharti *	it ain't precious.
3320146056Sharti *
3321146056Sharti * Results:
3322146056Sharti *	None.
3323146056Sharti *
3324146056Sharti * Side Effects:
3325146056Sharti *	The target is removed and the process exits. If .INTERRUPT exists,
3326146056Sharti *	its commands are run first WITH INTERRUPTS IGNORED..
3327146056Sharti *
3328146056Sharti *-----------------------------------------------------------------------
3329146056Sharti */
3330146056Shartistatic void
3331146056ShartiCompatInterrupt(int signo)
3332146056Sharti{
3333146056Sharti	GNode		*gn;
3334146056Sharti	sigset_t	nmask, omask;
3335146056Sharti	LstNode		*ln;
3336146056Sharti
3337146056Sharti	sigemptyset(&nmask);
3338146056Sharti	sigaddset(&nmask, SIGINT);
3339146056Sharti	sigaddset(&nmask, SIGTERM);
3340146056Sharti	sigaddset(&nmask, SIGHUP);
3341146056Sharti	sigaddset(&nmask, SIGQUIT);
3342146056Sharti	sigprocmask(SIG_SETMASK, &nmask, &omask);
3343146056Sharti
3344146056Sharti	/* prevent recursion in evaluation of .INTERRUPT */
3345146056Sharti	interrupted = 0;
3346146056Sharti
3347146056Sharti	if (curTarg != NULL && !Targ_Precious(curTarg)) {
3348146056Sharti		char	  *p1;
3349146061Sharti		char	  *file = Var_Value(TARGET, curTarg, &p1);
3350146056Sharti
3351146056Sharti		if (!noExecute && eunlink(file) != -1) {
3352146056Sharti			printf("*** %s removed\n", file);
3353146056Sharti		}
3354146056Sharti		free(p1);
3355146056Sharti	}
3356146056Sharti
3357146056Sharti	/*
3358146056Sharti	 * Run .INTERRUPT only if hit with interrupt signal
3359146056Sharti	 */
3360146056Sharti	if (signo == SIGINT) {
3361146056Sharti		gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
3362146056Sharti		if (gn != NULL) {
3363146056Sharti			LST_FOREACH(ln, &gn->commands) {
3364146056Sharti				if (Compat_RunCommand(Lst_Datum(ln), gn))
3365146056Sharti					break;
3366146056Sharti			}
3367146056Sharti		}
3368146056Sharti	}
3369146056Sharti
3370146056Sharti	sigprocmask(SIG_SETMASK, &omask, NULL);
3371146056Sharti
3372146056Sharti	if (signo == SIGQUIT)
3373146056Sharti		exit(signo);
3374146056Sharti	signal(signo, SIG_DFL);
3375146056Sharti	kill(getpid(), signo);
3376146056Sharti}
3377146056Sharti
3378146129Sharti/**
3379146129Sharti * shellneed
3380146056Sharti *
3381146056Sharti * Results:
3382146129Sharti *	Returns NULL if a specified line must be executed by the shell,
3383146129Sharti *	and an argument vector if it can be run via execvp().
3384146056Sharti *
3385146056Sharti * Side Effects:
3386146056Sharti *	Uses brk_string so destroys the contents of argv.
3387146056Sharti */
3388146129Shartistatic char **
3389146056Shartishellneed(char *cmd)
3390146056Sharti{
3391146056Sharti	char		**av;
3392146056Sharti	const char	**p;
3393146056Sharti
3394146129Sharti	if (strpbrk(cmd, sh_meta) != NULL)
3395146129Sharti		return (NULL);
3396146129Sharti
3397146147Sharti	/*
3398146147Sharti	 * Break the command into words to form an argument
3399146147Sharti	 * vector we can execute. brk_string sticks NULL
3400146147Sharti	 * in av[0], so we have to skip over it...
3401146147Sharti	 */
3402146056Sharti	av = brk_string(cmd, NULL, TRUE);
3403146056Sharti	for (p = sh_builtin; *p != 0; p++)
3404146056Sharti		if (strcmp(av[1], *p) == 0)
3405146129Sharti			return (NULL);
3406146129Sharti	return (av + 1);
3407146056Sharti}
3408146056Sharti
3409146056Sharti/*-
3410146056Sharti *-----------------------------------------------------------------------
3411146056Sharti * Compat_RunCommand --
3412146056Sharti *	Execute the next command for a target. If the command returns an
3413146056Sharti *	error, the node's made field is set to ERROR and creation stops.
3414146056Sharti *	The node from which the command came is also given.
3415146056Sharti *
3416146056Sharti * Results:
3417146056Sharti *	0 if the command succeeded, 1 if an error occurred.
3418146056Sharti *
3419146056Sharti * Side Effects:
3420146056Sharti *	The node's 'made' field may be set to ERROR.
3421146056Sharti *
3422146056Sharti *-----------------------------------------------------------------------
3423146056Sharti */
3424146142Shartistatic int
3425146056ShartiCompat_RunCommand(char *cmd, GNode *gn)
3426146056Sharti{
3427146056Sharti	char	*cmdStart;	/* Start of expanded command */
3428146056Sharti	Boolean	silent;		/* Don't print command */
3429146056Sharti	Boolean	doit;		/* Execute even in -n */
3430146056Sharti	Boolean	errCheck;	/* Check errors */
3431146056Sharti	int	reason;		/* Reason for child's death */
3432146056Sharti	int	status;		/* Description of child's death */
3433146056Sharti	LstNode	*cmdNode;	/* Node where current command is located */
3434146056Sharti	char	**av;		/* Argument vector for thing to exec */
3435146056Sharti	char	*cmd_save;	/* saved cmd */
3436146129Sharti	ProcStuff	ps;
3437146056Sharti
3438146056Sharti	silent = gn->type & OP_SILENT;
3439146056Sharti	errCheck = !(gn->type & OP_IGNORE);
3440146056Sharti	doit = FALSE;
3441146056Sharti
3442146056Sharti	cmdNode = Lst_Member(&gn->commands, cmd);
3443146056Sharti	cmdStart = Buf_Peel(Var_Subst(cmd, gn, FALSE));
3444146056Sharti
3445146056Sharti	/*
3446146056Sharti	 * brk_string will return an argv with a NULL in av[0], thus causing
3447146129Sharti	 * execvp() to choke and die horribly. Besides, how can we execute a
3448146129Sharti	 * null command? In any case, we warn the user that the command
3449146129Sharti	 * expanded to nothing (is this the right thing to do?).
3450146056Sharti	 */
3451146056Sharti	if (*cmdStart == '\0') {
3452146056Sharti		free(cmdStart);
3453146056Sharti		Error("%s expands to empty string", cmd);
3454146056Sharti		return (0);
3455146056Sharti	} else {
3456146056Sharti		cmd = cmdStart;
3457146056Sharti	}
3458146056Sharti	Lst_Replace(cmdNode, cmdStart);
3459146056Sharti
3460146056Sharti	if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
3461146056Sharti		Lst_AtEnd(&ENDNode->commands, cmdStart);
3462146056Sharti		return (0);
3463146056Sharti	} else if (strcmp(cmdStart, "...") == 0) {
3464146056Sharti		gn->type |= OP_SAVE_CMDS;
3465146056Sharti		return (0);
3466146056Sharti	}
3467146056Sharti
3468146056Sharti	while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
3469146056Sharti		switch (*cmd) {
3470146056Sharti
3471146056Sharti		  case '@':
3472146056Sharti			silent = DEBUG(LOUD) ? FALSE : TRUE;
3473146056Sharti			break;
3474146056Sharti
3475146056Sharti		  case '-':
3476146056Sharti			errCheck = FALSE;
3477146056Sharti			break;
3478146056Sharti
3479146129Sharti		  case '+':
3480146056Sharti			doit = TRUE;
3481146056Sharti			break;
3482146056Sharti		}
3483146056Sharti		cmd++;
3484146056Sharti	}
3485146056Sharti
3486146056Sharti	while (isspace((unsigned char)*cmd))
3487146056Sharti		cmd++;
3488146056Sharti
3489146056Sharti	/*
3490146056Sharti	 * Print the command before echoing if we're not supposed to be quiet
3491146056Sharti	 * for this one. We also print the command if -n given, but not if '+'.
3492146056Sharti	 */
3493146056Sharti	if (!silent || (noExecute && !doit)) {
3494146056Sharti		printf("%s\n", cmd);
3495146056Sharti		fflush(stdout);
3496146056Sharti	}
3497146056Sharti
3498146056Sharti	/*
3499146056Sharti	 * If we're not supposed to execute any commands, this is as far as
3500146056Sharti	 * we go...
3501146056Sharti	 */
3502146056Sharti	if (!doit && noExecute) {
3503146056Sharti		return (0);
3504146056Sharti	}
3505146056Sharti
3506146129Sharti	ps.in = STDIN_FILENO;
3507146129Sharti	ps.out = STDOUT_FILENO;
3508146129Sharti	ps.err = STDERR_FILENO;
3509146056Sharti
3510146129Sharti	ps.merge_errors = 0;
3511146129Sharti	ps.pgroup = 0;
3512146129Sharti	ps.searchpath = 1;
3513146056Sharti
3514146129Sharti	if ((av = shellneed(cmd)) == NULL) {
3515146056Sharti		/*
3516146129Sharti		 * Shell meta character or shell builtin found - pass
3517146129Sharti		 * command to shell. We give the shell the -e flag as
3518146129Sharti		 * well as -c if it is supposed to exit when it hits an error.
3519146056Sharti		 */
3520146129Sharti		ps.argv = emalloc(4 * sizeof(char *));
3521146129Sharti		ps.argv[0] = strdup(shellName);
3522146129Sharti		ps.argv[1] = strdup(errCheck ? "-ec" : "-c");
3523146129Sharti		ps.argv[2] = strdup(cmd);
3524146129Sharti		ps.argv[3] = NULL;
3525146056Sharti	} else {
3526146129Sharti		ps.argv = av;
3527146056Sharti	}
3528146056Sharti
3529146056Sharti	/*
3530146129Sharti	 * Warning since we are doing vfork() instead of fork(),
3531146129Sharti	 * do not allocate memory in the child process!
3532146056Sharti	 */
3533146130Sharti	if ((ps.child_pid = vfork()) == -1) {
3534146056Sharti		Fatal("Could not fork");
3535146058Sharti
3536146130Sharti	} else if (ps.child_pid == 0) {
3537146129Sharti		/*
3538146129Sharti		 * Child
3539146129Sharti		 */
3540146129Sharti		ProcExec(&ps);
3541146129Sharti  		/* NOTREACHED */
3542146129Sharti
3543146131Sharti	} else {
3544146131Sharti		if (av == NULL) {
3545146131Sharti			free(ps.argv[2]);
3546146131Sharti			free(ps.argv[1]);
3547146131Sharti			free(ps.argv[0]);
3548146131Sharti			free(ps.argv);
3549146131Sharti		}
3550146129Sharti
3551146131Sharti		/*
3552146131Sharti		 * we need to print out the command associated with this
3553146131Sharti		 * Gnode in Targ_PrintCmd from Targ_PrintGraph when debugging
3554146131Sharti		 * at level g2, in main(), Fatal() and DieHorribly(),
3555146131Sharti		 * therefore do not free it when debugging.
3556146131Sharti		 */
3557146131Sharti		if (!DEBUG(GRAPH2)) {
3558146131Sharti			free(cmdStart);
3559146131Sharti			Lst_Replace(cmdNode, cmd_save);
3560146131Sharti		}
3561146129Sharti
3562146131Sharti		/*
3563146131Sharti		 * The child is off and running. Now all we can do is wait...
3564146131Sharti		 */
3565146131Sharti		reason = ProcWait(&ps);
3566146132Sharti
3567146056Sharti		if (interrupted)
3568146056Sharti			CompatInterrupt(interrupted);
3569146131Sharti
3570146132Sharti		/*
3571146132Sharti		 * Decode and report the reason child exited, then
3572146132Sharti		 * indicate how we handled it.
3573146132Sharti		 */
3574146131Sharti		if (WIFEXITED(reason)) {
3575146131Sharti			status = WEXITSTATUS(reason);
3576146131Sharti			if (status == 0) {
3577146131Sharti				return (0);
3578146131Sharti  			} else {
3579146131Sharti				printf("*** Error code %d", status);
3580146131Sharti  			}
3581146131Sharti		} else if (WIFSTOPPED(reason)) {
3582146131Sharti			status = WSTOPSIG(reason);
3583146131Sharti		} else {
3584146131Sharti			status = WTERMSIG(reason);
3585146131Sharti			printf("*** Signal %d", status);
3586146131Sharti  		}
3587146131Sharti
3588146131Sharti		if (errCheck) {
3589146131Sharti			gn->made = ERROR;
3590146131Sharti			if (keepgoing) {
3591146131Sharti				/*
3592146131Sharti				 * Abort the current
3593146131Sharti				 * target, but let
3594146131Sharti				 * others continue.
3595146131Sharti				 */
3596146131Sharti				printf(" (continuing)\n");
3597146056Sharti			}
3598146131Sharti			return (status);
3599146056Sharti		} else {
3600146131Sharti			/*
3601146131Sharti			 * Continue executing
3602146131Sharti			 * commands for this target.
3603146131Sharti			 * If we return 0, this will
3604146131Sharti			 * happen...
3605146131Sharti			 */
3606146131Sharti			printf(" (ignored)\n");
3607146131Sharti			return (0);
3608146056Sharti		}
3609146056Sharti	}
3610146056Sharti}
3611146056Sharti
3612146056Sharti/*-
3613146056Sharti *-----------------------------------------------------------------------
3614146056Sharti * CompatMake --
3615146056Sharti *	Make a target, given the parent, to abort if necessary.
3616146056Sharti *
3617146056Sharti * Side Effects:
3618146056Sharti *	If an error is detected and not being ignored, the process exits.
3619146056Sharti *
3620146056Sharti *-----------------------------------------------------------------------
3621146056Sharti */
3622146056Shartistatic int
3623146056ShartiCompatMake(GNode *gn, GNode *pgn)
3624146056Sharti{
3625146056Sharti	LstNode	*ln;
3626146056Sharti
3627146056Sharti	if (gn->type & OP_USE) {
3628146056Sharti		Make_HandleUse(gn, pgn);
3629146056Sharti
3630146056Sharti	} else if (gn->made == UNMADE) {
3631146056Sharti		/*
3632146056Sharti		 * First mark ourselves to be made, then apply whatever
3633146056Sharti		 * transformations the suffix module thinks are necessary.
3634146056Sharti		 * Once that's done, we can descend and make all our children.
3635146056Sharti		 * If any of them has an error but the -k flag was given, our
3636146056Sharti		 * 'make' field will be set FALSE again. This is our signal to
3637146056Sharti		 * not attempt to do anything but abort our parent as well.
3638146056Sharti		 */
3639146056Sharti		gn->make = TRUE;
3640146056Sharti		gn->made = BEINGMADE;
3641146056Sharti		Suff_FindDeps(gn);
3642146056Sharti		LST_FOREACH(ln, &gn->children)
3643146056Sharti			CompatMake(Lst_Datum(ln), gn);
3644146056Sharti		if (!gn->make) {
3645146056Sharti			gn->made = ABORTED;
3646146056Sharti			pgn->make = FALSE;
3647146056Sharti			return (0);
3648146056Sharti		}
3649146056Sharti
3650146056Sharti		if (Lst_Member(&gn->iParents, pgn) != NULL) {
3651146056Sharti			char *p1;
3652146056Sharti			Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
3653146056Sharti			free(p1);
3654146056Sharti		}
3655146056Sharti
3656146056Sharti		/*
3657146056Sharti		 * All the children were made ok. Now cmtime contains the
3658146056Sharti		 * modification time of the newest child, we need to find out
3659146056Sharti		 * if we exist and when we were modified last. The criteria for
3660146056Sharti		 * datedness are defined by the Make_OODate function.
3661146056Sharti		 */
3662146056Sharti		DEBUGF(MAKE, ("Examining %s...", gn->name));
3663146056Sharti		if (!Make_OODate(gn)) {
3664146056Sharti			gn->made = UPTODATE;
3665146056Sharti			DEBUGF(MAKE, ("up-to-date.\n"));
3666146056Sharti			return (0);
3667146056Sharti		} else {
3668146056Sharti			DEBUGF(MAKE, ("out-of-date.\n"));
3669146056Sharti		}
3670146056Sharti
3671146056Sharti		/*
3672146056Sharti		 * If the user is just seeing if something is out-of-date,
3673146056Sharti		 * exit now to tell him/her "yes".
3674146056Sharti		 */
3675146056Sharti		if (queryFlag) {
3676146056Sharti			exit(1);
3677146056Sharti		}
3678146056Sharti
3679146056Sharti		/*
3680146056Sharti		 * We need to be re-made. We also have to make sure we've got
3681146056Sharti		 * a $? variable. To be nice, we also define the $> variable
3682146056Sharti		 * using Make_DoAllVar().
3683146056Sharti		 */
3684146056Sharti		Make_DoAllVar(gn);
3685146056Sharti
3686146056Sharti		/*
3687146056Sharti		 * Alter our type to tell if errors should be ignored or things
3688146056Sharti		 * should not be printed so Compat_RunCommand knows what to do.
3689146056Sharti		 */
3690146056Sharti		if (Targ_Ignore(gn)) {
3691146056Sharti			gn->type |= OP_IGNORE;
3692146056Sharti		}
3693146056Sharti		if (Targ_Silent(gn)) {
3694146056Sharti			gn->type |= OP_SILENT;
3695146056Sharti		}
3696146056Sharti
3697146056Sharti		if (Job_CheckCommands(gn, Fatal)) {
3698146056Sharti			/*
3699146056Sharti			 * Our commands are ok, but we still have to worry
3700146056Sharti			 * about the -t flag...
3701146056Sharti			 */
3702146056Sharti			if (!touchFlag) {
3703146056Sharti				curTarg = gn;
3704146056Sharti				LST_FOREACH(ln, &gn->commands) {
3705146056Sharti					if (Compat_RunCommand(Lst_Datum(ln),
3706146056Sharti					    gn))
3707146056Sharti						break;
3708146056Sharti				}
3709146056Sharti				curTarg = NULL;
3710146056Sharti			} else {
3711146056Sharti				Job_Touch(gn, gn->type & OP_SILENT);
3712146056Sharti			}
3713146056Sharti		} else {
3714146056Sharti			gn->made = ERROR;
3715146056Sharti		}
3716146056Sharti
3717146056Sharti		if (gn->made != ERROR) {
3718146056Sharti			/*
3719146056Sharti			 * If the node was made successfully, mark it so, update
3720146056Sharti			 * its modification time and timestamp all its parents.
3721146056Sharti			 * Note that for .ZEROTIME targets, the timestamping
3722146056Sharti			 * isn't done. This is to keep its state from affecting
3723146056Sharti			 * that of its parent.
3724146056Sharti			 */
3725146056Sharti			gn->made = MADE;
3726146056Sharti#ifndef RECHECK
3727146056Sharti			/*
3728146056Sharti			 * We can't re-stat the thing, but we can at least take
3729146056Sharti			 * care of rules where a target depends on a source that
3730146056Sharti			 * actually creates the target, but only if it has
3731146056Sharti			 * changed, e.g.
3732146056Sharti			 *
3733146056Sharti			 * parse.h : parse.o
3734146056Sharti			 *
3735146056Sharti			 * parse.o : parse.y
3736146061Sharti			 *	yacc -d parse.y
3737146061Sharti			 *	cc -c y.tab.c
3738146061Sharti			 *	mv y.tab.o parse.o
3739146061Sharti			 *	cmp -s y.tab.h parse.h || mv y.tab.h parse.h
3740146056Sharti			 *
3741146056Sharti			 * In this case, if the definitions produced by yacc
3742146056Sharti			 * haven't changed from before, parse.h won't have been
3743146056Sharti			 * updated and gn->mtime will reflect the current
3744146056Sharti			 * modification time for parse.h. This is something of a
3745146056Sharti			 * kludge, I admit, but it's a useful one..
3746146056Sharti			 *
3747146056Sharti			 * XXX: People like to use a rule like
3748146056Sharti			 *
3749146056Sharti			 * FRC:
3750146056Sharti			 *
3751146056Sharti			 * To force things that depend on FRC to be made, so we
3752146056Sharti			 * have to check for gn->children being empty as well...
3753146056Sharti			 */
3754146056Sharti			if (!Lst_IsEmpty(&gn->commands) ||
3755146056Sharti			    Lst_IsEmpty(&gn->children)) {
3756146056Sharti				gn->mtime = now;
3757146056Sharti			}
3758146056Sharti#else
3759146056Sharti			/*
3760146056Sharti			 * This is what Make does and it's actually a good
3761146056Sharti			 * thing, as it allows rules like
3762146056Sharti			 *
3763146056Sharti			 *	cmp -s y.tab.h parse.h || cp y.tab.h parse.h
3764146056Sharti			 *
3765146056Sharti			 * to function as intended. Unfortunately, thanks to
3766146056Sharti			 * the stateless nature of NFS (and the speed of this
3767146056Sharti			 * program), there are times when the modification time
3768146056Sharti			 * of a file created on a remote machine will not be
3769146056Sharti			 * modified before the stat() implied by the Dir_MTime
3770146056Sharti			 * occurs, thus leading us to believe that the file
3771146056Sharti			 * is unchanged, wreaking havoc with files that depend
3772146056Sharti			 * on this one.
3773146056Sharti			 *
3774146056Sharti			 * I have decided it is better to make too much than to
3775146056Sharti			 * make too little, so this stuff is commented out
3776146056Sharti			 * unless you're sure it's ok.
3777146056Sharti			 * -- ardeb 1/12/88
3778146056Sharti			 */
3779146056Sharti			if (noExecute || Dir_MTime(gn) == 0) {
3780146056Sharti				gn->mtime = now;
3781146056Sharti			}
3782146056Sharti			if (gn->cmtime > gn->mtime)
3783146056Sharti				gn->mtime = gn->cmtime;
3784146056Sharti			DEBUGF(MAKE, ("update time: %s\n",
3785146056Sharti			    Targ_FmtTime(gn->mtime)));
3786146056Sharti#endif
3787146056Sharti			if (!(gn->type & OP_EXEC)) {
3788146056Sharti				pgn->childMade = TRUE;
3789146056Sharti				Make_TimeStamp(pgn, gn);
3790146056Sharti			}
3791146056Sharti
3792146056Sharti		} else if (keepgoing) {
3793146056Sharti			pgn->make = FALSE;
3794146056Sharti
3795146056Sharti		} else {
3796146056Sharti			char *p1;
3797146056Sharti
3798146056Sharti			printf("\n\nStop in %s.\n",
3799146056Sharti			    Var_Value(".CURDIR", gn, &p1));
3800146056Sharti			free(p1);
3801146056Sharti			exit(1);
3802146056Sharti		}
3803146056Sharti	} else if (gn->made == ERROR) {
3804146056Sharti		/*
3805146056Sharti		 * Already had an error when making this beastie. Tell the
3806146056Sharti		 * parent to abort.
3807146056Sharti		 */
3808146056Sharti		pgn->make = FALSE;
3809146056Sharti	} else {
3810146056Sharti		if (Lst_Member(&gn->iParents, pgn) != NULL) {
3811146056Sharti			char *p1;
3812146056Sharti			Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
3813146056Sharti			free(p1);
3814146056Sharti		}
3815146056Sharti		switch(gn->made) {
3816146056Sharti		  case BEINGMADE:
3817146056Sharti			Error("Graph cycles through %s\n", gn->name);
3818146056Sharti			gn->made = ERROR;
3819146056Sharti			pgn->make = FALSE;
3820146056Sharti			break;
3821146056Sharti		  case MADE:
3822146056Sharti			if ((gn->type & OP_EXEC) == 0) {
3823146056Sharti			    pgn->childMade = TRUE;
3824146056Sharti			    Make_TimeStamp(pgn, gn);
3825146056Sharti			}
3826146056Sharti			break;
3827146056Sharti		  case UPTODATE:
3828146056Sharti			if ((gn->type & OP_EXEC) == 0) {
3829146056Sharti			    Make_TimeStamp(pgn, gn);
3830146056Sharti			}
3831146056Sharti			break;
3832146056Sharti		  default:
3833146056Sharti			break;
3834146056Sharti		}
3835146056Sharti	}
3836146056Sharti
3837146056Sharti	return (0);
3838146056Sharti}
3839146056Sharti
3840146056Sharti/*-
3841146056Sharti *-----------------------------------------------------------------------
3842146056Sharti * Compat_Run --
3843146056Sharti *	Start making again, given a list of target nodes.
3844146056Sharti *
3845146056Sharti * Results:
3846146056Sharti *	None.
3847146056Sharti *
3848146056Sharti * Side Effects:
3849146056Sharti *	Guess what?
3850146056Sharti *
3851146056Sharti *-----------------------------------------------------------------------
3852146056Sharti */
3853146056Shartivoid
3854146056ShartiCompat_Run(Lst *targs)
3855146056Sharti{
3856146056Sharti	GNode	*gn = NULL;	/* Current root target */
3857146056Sharti	int	error_cnt;		/* Number of targets not remade due to errors */
3858146056Sharti	LstNode	*ln;
3859146056Sharti
3860146056Sharti	Shell_Init();		/* Set up shell. */
3861146056Sharti
3862146056Sharti	if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
3863146056Sharti		signal(SIGINT, CompatCatchSig);
3864146056Sharti	}
3865146056Sharti	if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
3866146056Sharti		signal(SIGTERM, CompatCatchSig);
3867146056Sharti	}
3868146056Sharti	if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
3869146056Sharti		signal(SIGHUP, CompatCatchSig);
3870146056Sharti	}
3871146056Sharti	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
3872146056Sharti		signal(SIGQUIT, CompatCatchSig);
3873146056Sharti	}
3874146056Sharti
3875146056Sharti	ENDNode = Targ_FindNode(".END", TARG_CREATE);
3876146056Sharti	/*
3877146056Sharti	 * If the user has defined a .BEGIN target, execute the commands
3878146056Sharti	 * attached to it.
3879146056Sharti	*/
3880146056Sharti	if (!queryFlag) {
3881146056Sharti		gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
3882146056Sharti		if (gn != NULL) {
3883146056Sharti			LST_FOREACH(ln, &gn->commands) {
3884146056Sharti				if (Compat_RunCommand(Lst_Datum(ln), gn))
3885146056Sharti					break;
3886146056Sharti			}
3887146056Sharti			if (gn->made == ERROR) {
3888146056Sharti				printf("\n\nStop.\n");
3889146056Sharti				exit(1);
3890146056Sharti			}
3891146056Sharti		}
3892146056Sharti	}
3893146056Sharti
3894146056Sharti	/*
3895146056Sharti	 * For each entry in the list of targets to create, call CompatMake on
3896146056Sharti	 * it to create the thing. CompatMake will leave the 'made' field of gn
3897146056Sharti	 * in one of several states:
3898146056Sharti	 *	UPTODATE  gn was already up-to-date
3899146056Sharti	 *	MADE	  gn was recreated successfully
3900146056Sharti	 *	ERROR	  An error occurred while gn was being created
3901146056Sharti	 *	ABORTED	  gn was not remade because one of its inferiors
3902146056Sharti	 *		  could not be made due to errors.
3903146056Sharti	 */
3904146056Sharti	error_cnt = 0;
3905146056Sharti	while (!Lst_IsEmpty(targs)) {
3906146056Sharti		gn = Lst_DeQueue(targs);
3907146056Sharti		CompatMake(gn, gn);
3908146056Sharti
3909146056Sharti		if (gn->made == UPTODATE) {
3910146056Sharti			printf("`%s' is up to date.\n", gn->name);
3911146056Sharti		} else if (gn->made == ABORTED) {
3912146056Sharti			printf("`%s' not remade because of errors.\n",
3913146056Sharti			    gn->name);
3914146056Sharti			error_cnt += 1;
3915146056Sharti		}
3916146056Sharti	}
3917146056Sharti
3918146056Sharti	/*
3919146056Sharti	 * If the user has defined a .END target, run its commands.
3920146056Sharti	 */
3921146056Sharti	if (error_cnt == 0) {
3922146056Sharti		LST_FOREACH(ln, &ENDNode->commands) {
3923146056Sharti			if (Compat_RunCommand(Lst_Datum(ln), gn))
3924146056Sharti				break;
3925146056Sharti		}
3926146056Sharti	}
3927146056Sharti}
3928146155Sharti
3929