job.c revision 176808
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 176808 2008-03-04 22:51:37Z obrien $");
441590Srgrimes
451590Srgrimes/*-
461590Srgrimes * job.c --
471590Srgrimes *	handle the creation etc. of our child processes.
481590Srgrimes *
491590Srgrimes * Interface:
50144467Sharti *	Job_Make	Start the creation of the given target.
511590Srgrimes *
52144467Sharti *	Job_CatchChildren
53144467Sharti *			Check for and handle the termination of any children.
54144467Sharti *			This must be called reasonably frequently to keep the
55144467Sharti *			whole make going at a decent clip, since job table
56144467Sharti *			entries aren't removed until their process is caught
57144467Sharti *			this way. Its single argument is TRUE if the function
58144467Sharti *			should block waiting for a child to terminate.
591590Srgrimes *
60144467Sharti *	Job_CatchOutput	Print any output our children have produced. Should
61144467Sharti *			also be called fairly frequently to keep the user
62144467Sharti *			informed of what's going on. If no output is waiting,
63144467Sharti *			it will block for a time given by the SEL_* constants,
64144467Sharti *			below, or until output is ready.
651590Srgrimes *
66144467Sharti *	Job_Init	Called to intialize this module. in addition, any
67144467Sharti *			commands attached to the .BEGIN target are executed
68144467Sharti *			before this function returns. Hence, the makefile must
69144467Sharti *			have been parsed before this function is called.
701590Srgrimes *
71144467Sharti *	Job_Full	Return TRUE if the job table is filled.
721590Srgrimes *
73144467Sharti *	Job_Empty	Return TRUE if the job table is completely empty.
741590Srgrimes *
75144467Sharti *	Job_Finish	Perform any final processing which needs doing. This
76144467Sharti *			includes the execution of any commands which have
77144467Sharti *			been/were attached to the .END target. It should only
78144467Sharti *			be called when the job table is empty.
791590Srgrimes *
80144467Sharti *	Job_AbortAll	Abort all currently running jobs. It doesn't handle
81144467Sharti *			output or do anything for the jobs, just kills them.
82144467Sharti *			It should only be called in an emergency, as it were.
831590Srgrimes *
84144467Sharti *	Job_CheckCommands
85144467Sharti *			Verify that the commands for a target are ok. Provide
86144467Sharti *			them if necessary and possible.
871590Srgrimes *
88144467Sharti *	Job_Touch	Update a target without really updating it.
891590Srgrimes *
90144467Sharti *	Job_Wait	Wait for all currently-running jobs to finish.
91146132Sharti *
92146132Sharti * compat.c --
93146132Sharti *	The routines in this file implement the full-compatibility
94146132Sharti *	mode of PMake. Most of the special functionality of PMake
95146132Sharti *	is available in this mode. Things not supported:
96146132Sharti *	    - different shells.
97146132Sharti *	    - friendly variable substitution.
98146132Sharti *
99146132Sharti * Interface:
100146132Sharti *	Compat_Run	    Initialize things for this module and recreate
101146132Sharti *			    thems as need creatin'
1021590Srgrimes */
1031590Srgrimes
104144494Sharti#include <sys/queue.h>
1051590Srgrimes#include <sys/types.h>
106141104Sharti#include <sys/select.h>
1071590Srgrimes#include <sys/stat.h>
108107447Sru#ifdef USE_KQUEUE
109104475Sphk#include <sys/event.h>
110107447Sru#endif
1111590Srgrimes#include <sys/wait.h>
112141104Sharti#include <ctype.h>
113146160Sjmallett#include <err.h>
11494506Scharnier#include <errno.h>
1155814Sjkh#include <fcntl.h>
116144665Sharti#include <inttypes.h>
1171590Srgrimes#include <string.h>
1185814Sjkh#include <signal.h>
119141104Sharti#include <stdlib.h>
12080381Ssheldonh#include <unistd.h>
12194506Scharnier#include <utime.h>
122141104Sharti
123141104Sharti#include "arch.h"
124142457Sharti#include "buf.h"
125146056Sharti#include "config.h"
1261590Srgrimes#include "dir.h"
127141104Sharti#include "globals.h"
128141104Sharti#include "GNode.h"
1291590Srgrimes#include "job.h"
130141104Sharti#include "make.h"
131141104Sharti#include "parse.h"
132146574Sharti#include "proc.h"
133146572Sharti#include "shell.h"
134141104Sharti#include "str.h"
135146056Sharti#include "suff.h"
136141104Sharti#include "targ.h"
137141104Sharti#include "util.h"
138141104Sharti#include "var.h"
1391590Srgrimes
140146057Sharti#define	TMPPAT	"/tmp/makeXXXXXXXXXX"
141146057Sharti
142146057Sharti#ifndef USE_KQUEUE
1431590Srgrimes/*
144146057Sharti * The SEL_ constants determine the maximum amount of time spent in select
145146057Sharti * before coming out to see if a child has finished. SEL_SEC is the number of
146146057Sharti * seconds and SEL_USEC is the number of micro-seconds
147146057Sharti */
148146057Sharti#define	SEL_SEC		2
149146057Sharti#define	SEL_USEC	0
150146057Sharti#endif /* !USE_KQUEUE */
151146057Sharti
152146057Sharti/*
153144483Sharti * Job Table definitions.
154144483Sharti *
155144483Sharti * The job "table" is kept as a linked Lst in 'jobs', with the number of
156144483Sharti * active jobs maintained in the 'nJobs' variable. At no time will this
157144483Sharti * exceed the value of 'maxJobs', initialized by the Job_Init function.
158144483Sharti *
159144483Sharti * When a job is finished, the Make_Update function is called on each of the
160144483Sharti * parents of the node which was just remade. This takes care of the upward
161144483Sharti * traversal of the dependency graph.
162144483Sharti */
163144483Sharti#define	JOB_BUFSIZE	1024
164144483Shartitypedef struct Job {
165144665Sharti	pid_t		pid;	/* The child's process ID */
166144483Sharti
167144483Sharti	struct GNode	*node;	/* The target the child is making */
168144483Sharti
169144483Sharti	/*
170144483Sharti	 * A LstNode for the first command to be saved after the job completes.
171144483Sharti	 * This is NULL if there was no "..." in the job's commands.
172144483Sharti	 */
173144483Sharti	LstNode		*tailCmds;
174144483Sharti
175144483Sharti	/*
176144483Sharti	 * An FILE* for writing out the commands. This is only
177144483Sharti	 * used before the job is actually started.
178144483Sharti	 */
179144483Sharti	FILE		*cmdFILE;
180144483Sharti
181144483Sharti	/*
182144483Sharti	 * A word of flags which determine how the module handles errors,
183144483Sharti	 * echoing, etc. for the job
184144483Sharti	 */
185144483Sharti	short		flags;	/* Flags to control treatment of job */
186144483Sharti#define	JOB_IGNERR	0x001	/* Ignore non-zero exits */
187144483Sharti#define	JOB_SILENT	0x002	/* no output */
188144483Sharti#define	JOB_SPECIAL	0x004	/* Target is a special one. i.e. run it locally
189144483Sharti				 * if we can't export it and maxLocal is 0 */
190146061Sharti#define	JOB_IGNDOTS	0x008	/* Ignore "..." lines when processing
191144483Sharti				 * commands */
192144483Sharti#define	JOB_FIRST	0x020	/* Job is first job for the node */
193144483Sharti#define	JOB_RESTART	0x080	/* Job needs to be completely restarted */
194144483Sharti#define	JOB_RESUME	0x100	/* Job needs to be resumed b/c it stopped,
195144483Sharti				 * for some reason */
196144483Sharti#define	JOB_CONTINUING	0x200	/* We are in the process of resuming this job.
197144483Sharti				 * Used to avoid infinite recursion between
198144483Sharti				 * JobFinish and JobRestart */
199144483Sharti
200144483Sharti	/* union for handling shell's output */
201144483Sharti	union {
202144483Sharti		/*
203144483Sharti		 * This part is used when usePipes is true.
204146061Sharti		 * The output is being caught via a pipe and the descriptors
205144483Sharti		 * of our pipe, an array in which output is line buffered and
206144483Sharti		 * the current position in that buffer are all maintained for
207144483Sharti		 * each job.
208144483Sharti		 */
209144483Sharti		struct {
210144483Sharti			/*
211144483Sharti			 * Input side of pipe associated with
212144483Sharti			 * job's output channel
213144483Sharti			 */
214144483Sharti			int	op_inPipe;
215144483Sharti
216144483Sharti			/*
217144483Sharti			 * Output side of pipe associated with job's
218144483Sharti			 * output channel
219144483Sharti			 */
220144483Sharti			int	op_outPipe;
221144483Sharti
222144483Sharti			/*
223144483Sharti			 * Buffer for storing the output of the
224144483Sharti			 * job, line by line
225144483Sharti			 */
226144483Sharti			char	op_outBuf[JOB_BUFSIZE + 1];
227144483Sharti
228144483Sharti			/* Current position in op_outBuf */
229144483Sharti			int	op_curPos;
230144483Sharti		}	o_pipe;
231144483Sharti
232144483Sharti		/*
233144483Sharti		 * If usePipes is false the output is routed to a temporary
234144483Sharti		 * file and all that is kept is the name of the file and the
235144483Sharti		 * descriptor open to the file.
236144483Sharti		 */
237144483Sharti		struct {
238144483Sharti			/* Name of file to which shell output was rerouted */
239144483Sharti			char	of_outFile[sizeof(TMPPAT)];
240144483Sharti
241144483Sharti			/*
242144483Sharti			 * Stream open to the output file. Used to funnel all
243144483Sharti			 * from a single job to one file while still allowing
244144483Sharti			 * multiple shell invocations
245144483Sharti			 */
246144483Sharti			int	of_outFd;
247144483Sharti		}	o_file;
248144483Sharti
249144483Sharti	}       output;	    /* Data for tracking a shell's output */
250144494Sharti
251144494Sharti	TAILQ_ENTRY(Job) link;	/* list link */
252144483Sharti} Job;
253144483Sharti
254146061Sharti#define	outPipe		output.o_pipe.op_outPipe
255146061Sharti#define	inPipe		output.o_pipe.op_inPipe
256144483Sharti#define	outBuf		output.o_pipe.op_outBuf
257144483Sharti#define	curPos		output.o_pipe.op_curPos
258144483Sharti#define	outFile		output.o_file.of_outFile
259146061Sharti#define	outFd		output.o_file.of_outFd
260144483Sharti
261144494ShartiTAILQ_HEAD(JobList, Job);
262144494Sharti
263144483Sharti/*
2648874Srgrimes * error handling variables
2651590Srgrimes */
266144467Shartistatic int	errors = 0;	/* number of errors reported */
267144467Shartistatic int	aborting = 0;	/* why is the make aborting? */
268144467Sharti#define	ABORT_ERROR	1	/* Because of an error */
269144467Sharti#define	ABORT_INTERRUPT	2	/* Because it was interrupted */
270144467Sharti#define	ABORT_WAIT	3	/* Waiting for jobs to finish */
2711590Srgrimes
27218730Ssteve/*
27318730Ssteve * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
27418730Ssteve * is a char! So when we go above 127 we turn negative!
27518730Ssteve */
276138232Sharti#define	FILENO(a) ((unsigned)fileno(a))
2771590Srgrimes
2781590Srgrimes/*
2791590Srgrimes * post-make command processing. The node postCommands is really just the
2801590Srgrimes * .END target but we keep it around to avoid having to search for it
2811590Srgrimes * all the time.
2821590Srgrimes */
283144467Shartistatic GNode	*postCommands;
2841590Srgrimes
2851590Srgrimes/*
286144467Sharti * The number of commands actually printed for a target. Should this
287144467Sharti * number be 0, no shell will be executed.
288144467Sharti */
289144467Shartistatic int	numCommands;
290144467Sharti
291144467Sharti/*
2921590Srgrimes * Return values from JobStart.
2931590Srgrimes */
294144467Sharti#define	JOB_RUNNING	0	/* Job is running */
295146061Sharti#define	JOB_ERROR	1	/* Error in starting the job */
296144467Sharti#define	JOB_FINISHED	2	/* The job is already finished */
297144467Sharti#define	JOB_STOPPED	3	/* The job is stopped */
2981590Srgrimes
2991590Srgrimes/*
300146140Sharti * The maximum number of jobs that may run. This is initialize from the
301146140Sharti * -j argument for the leading make and from the FIFO for sub-makes.
302146140Sharti */
303146140Shartistatic int	maxJobs;
304146140Sharti
305144656Shartistatic int	nJobs;		/* The number of children currently running */
306138916Sharti
307138916Sharti/* The structures that describe them */
308144494Shartistatic struct JobList jobs = TAILQ_HEAD_INITIALIZER(jobs);
309138916Sharti
310146061Shartistatic Boolean	jobFull;	/* Flag to tell when the job table is full. It
3111590Srgrimes				 * is set TRUE when (1) the total number of
312137572Sphk				 * running jobs equals the maximum allowed */
313104475Sphk#ifdef USE_KQUEUE
314104475Sphkstatic int	kqfd;		/* File descriptor obtained by kqueue() */
315104475Sphk#else
316146061Shartistatic fd_set	outputs;	/* Set of descriptors of pipes connected to
3171590Srgrimes				 * the output channels of children */
3181590Srgrimes#endif
3191590Srgrimes
320146061Shartistatic GNode	*lastNode;	/* The node for which output was most recently
3211590Srgrimes				 * produced. */
322146061Shartistatic const char *targFmt;	/* Format string to use to head output from a
3231590Srgrimes				 * job when it's not the most-recent job heard
3241590Srgrimes				 * from */
3251590Srgrimes
326137202Sharti#define	TARG_FMT  "--- %s ---\n" /* Default format */
327137202Sharti#define	MESSAGE(fp, gn) \
328138232Sharti	 fprintf(fp, targFmt, gn->name);
32918730Ssteve
3301590Srgrimes/*
331137252Sharti * When JobStart attempts to run a job but isn't allowed to
332137252Sharti * or when Job_CatchChildren detects a job that has
333137252Sharti * been stopped somehow, the job is placed on the stoppedJobs queue to be run
3348874Srgrimes * when the next job finishes.
335138916Sharti *
336138916Sharti * Lst of Job structures describing jobs that were stopped due to
337138916Sharti * concurrency limits or externally
3381590Srgrimes */
339144494Shartistatic struct JobList stoppedJobs = TAILQ_HEAD_INITIALIZER(stoppedJobs);
3401590Srgrimes
341144656Shartistatic int	fifoFd;		/* Fd of our job fifo */
342144656Shartistatic char	fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
343144656Shartistatic int	fifoMaster;
3441590Srgrimes
345137605Shartistatic sig_atomic_t interrupted;
346137605Sharti
347137605Sharti
3481590Srgrimes#if defined(USE_PGRP) && defined(SYSV)
34918730Ssteve# define KILL(pid, sig)		killpg(-(pid), (sig))
3501590Srgrimes#else
3511590Srgrimes# if defined(USE_PGRP)
35218730Ssteve#  define KILL(pid, sig)	killpg((pid), (sig))
3531590Srgrimes# else
35418730Ssteve#  define KILL(pid, sig)	kill((pid), (sig))
3551590Srgrimes# endif
3561590Srgrimes#endif
3571590Srgrimes
35818730Ssteve/*
35918730Ssteve * Grmpf... There is no way to set bits of the wait structure
36018730Ssteve * anymore with the stupid W*() macros. I liked the union wait
36118730Ssteve * stuff much more. So, we devise our own macros... This is
36218730Ssteve * really ugly, use dramamine sparingly. You have been warned.
36318730Ssteve */
364103503Sjmallett#define	W_SETMASKED(st, val, fun)				\
36518730Ssteve	{							\
366138232Sharti		int sh = (int)~0;				\
36718730Ssteve		int mask = fun(sh);				\
36818730Ssteve								\
36918730Ssteve		for (sh = 0; ((mask >> sh) & 1) == 0; sh++)	\
37018730Ssteve			continue;				\
37118730Ssteve		*(st) = (*(st) & ~mask) | ((val) << sh);	\
37218730Ssteve	}
37318730Ssteve
374103503Sjmallett#define	W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
375103503Sjmallett#define	W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
37618730Ssteve
37792921Simpstatic void JobRestart(Job *);
37892921Simpstatic int JobStart(GNode *, int, Job *);
37992921Simpstatic void JobDoOutput(Job *, Boolean);
38092921Simpstatic void JobInterrupt(int, int);
38192921Simpstatic void JobRestartJobs(void);
382146142Shartistatic int Compat_RunCommand(char *, struct GNode *);
3831590Srgrimes
384146132Shartistatic GNode	    *curTarg = NULL;
385146132Shartistatic GNode	    *ENDNode;
386146132Sharti
387146155Sharti/**
388146155Sharti * Create a fifo file with a uniq filename, and returns a file
389146155Sharti * descriptor to that fifo.
390146155Sharti */
391146155Shartistatic int
392146155Shartimkfifotemp(char *template)
393146155Sharti{
394146155Sharti	char *start;
395146155Sharti	char *pathend;
396146155Sharti	char *ptr;
397146155Sharti	const unsigned char padchar[] =
398146155Sharti	    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
399146155Sharti
400146155Sharti	if (template[0] == '\0') {
401146155Sharti		errno = EINVAL;	/* bad input string */
402146155Sharti		return (-1);
403146155Sharti	}
404146155Sharti
405146155Sharti	/* Find end of template string. */
406146155Sharti	pathend = strchr(template, '\0');
407146155Sharti	ptr = pathend - 1;
408146155Sharti
409146155Sharti	/*
410146155Sharti	 * Starting from the end of the template replace spaces with 'X' in
411146155Sharti	 * them with random characters until there are no more 'X'.
412146155Sharti	 */
413146155Sharti	while (ptr >= template && *ptr == 'X') {
414146155Sharti		uint32_t rand_num = arc4random() % (sizeof(padchar) - 1);
415146155Sharti		*ptr-- = padchar[rand_num];
416146155Sharti	}
417146155Sharti	start = ptr + 1;
418146155Sharti
419146155Sharti	/* Check the target directory. */
420146155Sharti	for (; ptr > template; --ptr) {
421146155Sharti		if (*ptr == '/') {
422146155Sharti			struct stat sbuf;
423146155Sharti
424146155Sharti			*ptr = '\0';
425146155Sharti			if (stat(template, &sbuf) != 0)
426146155Sharti				return (-1);
427146155Sharti
428146155Sharti			if (!S_ISDIR(sbuf.st_mode)) {
429146155Sharti				errno = ENOTDIR;
430146155Sharti				return (-1);
431146155Sharti			}
432146155Sharti			*ptr = '/';
433146155Sharti			break;
434146155Sharti		}
435146155Sharti	}
436146155Sharti
437146155Sharti	for (;;) {
438146155Sharti		if (mkfifo(template, 0600) == 0) {
439146155Sharti			int fd;
440146155Sharti
441146155Sharti			if ((fd = open(template, O_RDWR, 0600)) < 0) {
442146155Sharti				unlink(template);
443146155Sharti				return (-1);
444146155Sharti			} else {
445146155Sharti				return (fd);
446146155Sharti			}
447146155Sharti		} else {
448146155Sharti			if (errno != EEXIST) {
449146155Sharti				return (-1);
450146155Sharti			}
451146155Sharti		}
452146155Sharti
453146155Sharti		/*
454146155Sharti		 * If we have a collision, cycle through the space of
455146155Sharti		 * filenames.
456146155Sharti		 */
457146155Sharti		for (ptr = start;;) {
458146155Sharti			char *pad;
459146155Sharti
460146155Sharti			if (*ptr == '\0' || ptr == pathend)
461146155Sharti				return (-1);
462146155Sharti
463146155Sharti			pad = strchr(padchar, *ptr);
464146155Sharti			if (pad == NULL || *++pad == '\0') {
465146155Sharti				*ptr++ = padchar[0];
466146155Sharti			} else {
467146155Sharti				*ptr++ = *pad;
468146155Sharti				break;
469146155Sharti			}
470146155Sharti		}
471146155Sharti	}
472146155Sharti	/*NOTREACHED*/
473146155Sharti}
474146155Sharti
475146144Shartistatic void
476146144Sharticatch_child(int sig __unused)
477146144Sharti{
478146144Sharti}
479146144Sharti
480144467Sharti/**
481146144Sharti */
482146144Shartivoid
483146144ShartiProc_Init()
484146144Sharti{
485146144Sharti	/*
486146144Sharti	 * Catch SIGCHLD so that we get kicked out of select() when we
487146144Sharti	 * need to look at a child.  This is only known to matter for the
488146144Sharti	 * -j case (perhaps without -P).
489146144Sharti	 *
490146144Sharti	 * XXX this is intentionally misplaced.
491146144Sharti	 */
492146144Sharti	struct sigaction sa;
493146144Sharti
494146144Sharti	sigemptyset(&sa.sa_mask);
495146144Sharti	sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
496146144Sharti	sa.sa_handler = catch_child;
497146144Sharti	sigaction(SIGCHLD, &sa, NULL);
498146144Sharti}
499146144Sharti
500146144Sharti/**
501146131Sharti * Wait for child process to terminate.
502146130Sharti */
503146130Shartistatic int
504146130ShartiProcWait(ProcStuff *ps)
505146130Sharti{
506146130Sharti	pid_t	pid;
507146130Sharti	int	status;
508146130Sharti
509146130Sharti	/*
510146130Sharti	 * Wait for the process to exit.
511146130Sharti	 */
512146131Sharti	for (;;) {
513146131Sharti		pid = wait(&status);
514146131Sharti		if (pid == -1 && errno != EINTR) {
515146131Sharti			Fatal("error in wait: %d", pid);
516146131Sharti			/* NOTREACHED */
517146131Sharti		}
518146131Sharti		if (pid == ps->child_pid) {
519146131Sharti			break;
520146131Sharti		}
521146131Sharti		if (interrupted) {
522146131Sharti			break;
523146131Sharti		}
524146130Sharti	}
525146130Sharti
526146130Sharti	return (status);
527146130Sharti}
528146130Sharti
529146130Sharti/**
530137605Sharti * JobCatchSignal
531144467Sharti *	Got a signal. Set global variables and hope that someone will
532144467Sharti *	handle it.
533137605Sharti */
534137605Shartistatic void
535137605ShartiJobCatchSig(int signo)
536137605Sharti{
537137605Sharti
538137605Sharti	interrupted = signo;
539137605Sharti}
540137605Sharti
541144467Sharti/**
5421590Srgrimes * JobPassSig --
543137252Sharti *	Pass a signal on to all local jobs if
5441590Srgrimes *	USE_PGRP is defined, then die ourselves.
5451590Srgrimes *
5461590Srgrimes * Side Effects:
5471590Srgrimes *	We die by the same signal.
5481590Srgrimes */
5491590Srgrimesstatic void
550104696SjmallettJobPassSig(int signo)
5511590Srgrimes{
552144741Sharti	Job	*job;
553144467Sharti	sigset_t nmask, omask;
554144467Sharti	struct sigaction act;
5558874Srgrimes
556144467Sharti	sigemptyset(&nmask);
557144467Sharti	sigaddset(&nmask, signo);
558144467Sharti	sigprocmask(SIG_SETMASK, &nmask, &omask);
559137605Sharti
560144467Sharti	DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
561144741Sharti	TAILQ_FOREACH(job, &jobs, link) {
562144741Sharti		DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
563144741Sharti		    signo, (intmax_t)job->pid));
564144741Sharti		KILL(job->pid, signo);
565144741Sharti	}
5661590Srgrimes
567144467Sharti	/*
568144467Sharti	 * Deal with proper cleanup based on the signal received. We only run
569144467Sharti	 * the .INTERRUPT target if the signal was in fact an interrupt.
570144467Sharti	 * The other three termination signals are more of a "get out *now*"
571144467Sharti	 * command.
572144467Sharti	 */
573144467Sharti	if (signo == SIGINT) {
574144467Sharti		JobInterrupt(TRUE, signo);
575144657Sharti	} else if (signo == SIGHUP || signo == SIGTERM || signo == SIGQUIT) {
576144467Sharti		JobInterrupt(FALSE, signo);
577144467Sharti	}
5788874Srgrimes
579144467Sharti	/*
580144467Sharti	 * Leave gracefully if SIGQUIT, rather than core dumping.
581144467Sharti	 */
582144467Sharti	if (signo == SIGQUIT) {
583144467Sharti		signo = SIGINT;
584144467Sharti	}
5858874Srgrimes
586144467Sharti	/*
587144467Sharti	 * Send ourselves the signal now we've given the message to everyone
588144467Sharti	 * else. Note we block everything else possible while we're getting
589144467Sharti	 * the signal. This ensures that all our jobs get continued when we
590144467Sharti	 * wake up before we take any other signal.
591144467Sharti	 * XXX this comment seems wrong.
592144467Sharti	 */
593144467Sharti	act.sa_handler = SIG_DFL;
594144467Sharti	sigemptyset(&act.sa_mask);
595144467Sharti	act.sa_flags = 0;
596144467Sharti	sigaction(signo, &act, NULL);
5971590Srgrimes
598144467Sharti	DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
599144467Sharti	    ~0 & ~(1 << (signo - 1))));
600144467Sharti	signal(signo, SIG_DFL);
6011590Srgrimes
602144467Sharti	KILL(getpid(), signo);
60318730Ssteve
604144467Sharti	signo = SIGCONT;
605144741Sharti	TAILQ_FOREACH(job, &jobs, link) {
606144741Sharti		DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
607144741Sharti		    signo, (intmax_t)job->pid));
608144741Sharti		KILL(job->pid, signo);
609144741Sharti	}
6101590Srgrimes
611144467Sharti	sigprocmask(SIG_SETMASK, &omask, NULL);
612144467Sharti	sigprocmask(SIG_SETMASK, &omask, NULL);
613144467Sharti	act.sa_handler = JobPassSig;
614144467Sharti	sigaction(signo, &act, NULL);
6151590Srgrimes}
6161590Srgrimes
617144467Sharti/**
6181590Srgrimes * JobPrintCommand  --
6191590Srgrimes *	Put out another command for the given job. If the command starts
6201590Srgrimes *	with an @ or a - we process it specially. In the former case,
6211590Srgrimes *	so long as the -s and -n flags weren't given to make, we stick
6221590Srgrimes *	a shell-specific echoOff command in the script. In the latter,
6231590Srgrimes *	we ignore errors for the entire job, unless the shell has error
6241590Srgrimes *	control.
6251590Srgrimes *	If the command is just "..." we take all future commands for this
6261590Srgrimes *	job to be commands to be executed once the entire graph has been
6271590Srgrimes *	made and return non-zero to signal that the end of the commands
6281590Srgrimes *	was reached. These commands are later attached to the postCommands
62994594Sobrien *	node and executed by Job_Finish when all things are done.
630142993Sharti *	This function is called from JobStart via LST_FOREACH.
6311590Srgrimes *
6321590Srgrimes * Results:
6331590Srgrimes *	Always 0, unless the command was "..."
6341590Srgrimes *
6351590Srgrimes * Side Effects:
6361590Srgrimes *	If the command begins with a '-' and the shell has no error control,
6371590Srgrimes *	the JOB_IGNERR flag is set in the job descriptor.
6381590Srgrimes *	If the command is "..." and we're not ignoring such things,
6391590Srgrimes *	tailCmds is set to the successor node of the cmd.
6401590Srgrimes *	numCommands is incremented if the command is actually printed.
6411590Srgrimes */
6421590Srgrimesstatic int
643144741ShartiJobPrintCommand(char *cmd, Job *job)
6441590Srgrimes{
645144467Sharti	Boolean	noSpecials;	/* true if we shouldn't worry about
646141258Sharti				 * inserting special commands into
647141258Sharti				 * the input stream. */
648144467Sharti	Boolean	shutUp = FALSE;	/* true if we put a no echo command
649141258Sharti				 * into the command file */
650144467Sharti	Boolean	errOff = FALSE;	/* true if we turned error checking
651141258Sharti				 * off before printing the command
652141258Sharti				 * and need to turn it back on */
653144467Sharti	const char *cmdTemplate;/* Template to use when printing the command */
654144467Sharti	char	*cmdStart;	/* Start of expanded command */
655144467Sharti	LstNode	*cmdNode;	/* Node for replacing the command */
6561590Srgrimes
657144467Sharti	noSpecials = (noExecute && !(job->node->type & OP_MAKE));
6581590Srgrimes
659144467Sharti	if (strcmp(cmd, "...") == 0) {
660144467Sharti		job->node->type |= OP_SAVE_CMDS;
661144467Sharti		if ((job->flags & JOB_IGNDOTS) == 0) {
662144467Sharti			job->tailCmds =
663144467Sharti			    Lst_Succ(Lst_Member(&job->node->commands, cmd));
664144467Sharti			return (1);
665144467Sharti		}
666144467Sharti		return (0);
6671590Srgrimes	}
6681590Srgrimes
669144467Sharti#define	DBPRINTF(fmt, arg)			\
670144467Sharti	DEBUGF(JOB, (fmt, arg));		\
671144467Sharti	fprintf(job->cmdFILE, fmt, arg);	\
672144467Sharti	fflush(job->cmdFILE);
6731590Srgrimes
674144467Sharti	numCommands += 1;
6751590Srgrimes
676144467Sharti	/*
677144467Sharti	 * For debugging, we replace each command with the result of expanding
678144467Sharti	 * the variables in the command.
679144467Sharti	 */
680144467Sharti	cmdNode = Lst_Member(&job->node->commands, cmd);
681142457Sharti
682146027Sharti	cmd = Buf_Peel(Var_Subst(cmd, job->node, FALSE));
683144467Sharti	cmdStart = cmd;
684142457Sharti
685144467Sharti	Lst_Replace(cmdNode, cmdStart);
6861590Srgrimes
687144467Sharti	cmdTemplate = "%s\n";
6881590Srgrimes
689144467Sharti	/*
690144467Sharti	 * Check for leading @', -' or +'s to control echoing, error checking,
691144467Sharti	 * and execution on -n.
692144467Sharti	 */
693144467Sharti	while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
694144467Sharti		switch (*cmd) {
695132839Sharti
696144467Sharti		  case '@':
697144467Sharti			shutUp = DEBUG(LOUD) ? FALSE : TRUE;
698144467Sharti			break;
699132839Sharti
700144467Sharti		  case '-':
701144467Sharti			errOff = TRUE;
702144467Sharti			break;
703132839Sharti
704144467Sharti		  case '+':
705144467Sharti			if (noSpecials) {
706144467Sharti				/*
707144467Sharti				 * We're not actually exececuting anything...
708144467Sharti				 * but this one needs to be - use compat mode
709144467Sharti				 * just for it.
710144467Sharti				 */
711144741Sharti				Compat_RunCommand(cmd, job->node);
712144467Sharti				return (0);
713144467Sharti			}
714144467Sharti			break;
715144467Sharti		}
716144467Sharti		cmd++;
7171590Srgrimes	}
7181590Srgrimes
719144467Sharti	while (isspace((unsigned char)*cmd))
720144467Sharti		cmd++;
7211590Srgrimes
722144467Sharti	if (shutUp) {
723144467Sharti		if (!(job->flags & JOB_SILENT) && !noSpecials &&
7241590Srgrimes		    commandShell->hasEchoCtl) {
72518730Ssteve			DBPRINTF("%s\n", commandShell->echoOff);
7261590Srgrimes		} else {
727144467Sharti			shutUp = FALSE;
7281590Srgrimes		}
729144467Sharti	}
730144467Sharti
731144467Sharti	if (errOff) {
732144467Sharti		if (!(job->flags & JOB_IGNERR) && !noSpecials) {
733144467Sharti			if (commandShell->hasErrCtl) {
734144467Sharti				/*
735144467Sharti				 * We don't want the error-control commands
736144467Sharti				 * showing up either, so we turn off echoing
737144467Sharti				 * while executing them. We could put another
738144467Sharti				 * field in the shell structure to tell
739144467Sharti				 * JobDoOutput to look for this string too,
740144467Sharti				 * but why make it any more complex than
741144467Sharti				 * it already is?
742144467Sharti				 */
743144467Sharti				if (!(job->flags & JOB_SILENT) && !shutUp &&
744144467Sharti				    commandShell->hasEchoCtl) {
745144467Sharti					DBPRINTF("%s\n", commandShell->echoOff);
746144467Sharti					DBPRINTF("%s\n", commandShell->ignErr);
747144467Sharti					DBPRINTF("%s\n", commandShell->echoOn);
748144467Sharti				} else {
749144467Sharti					DBPRINTF("%s\n", commandShell->ignErr);
750144467Sharti				}
751144467Sharti			} else if (commandShell->ignErr &&
752144657Sharti			    *commandShell->ignErr != '\0') {
753144467Sharti				/*
754144467Sharti				 * The shell has no error control, so we need to
755144467Sharti				 * be weird to get it to ignore any errors from
756144467Sharti				 * the command. If echoing is turned on, we turn
757144467Sharti				 * it off and use the errCheck template to echo
758144467Sharti				 * the command. Leave echoing off so the user
759144467Sharti				 * doesn't see the weirdness we go through to
760144467Sharti				 * ignore errors. Set cmdTemplate to use the
761144467Sharti				 * weirdness instead of the simple "%s\n"
762144467Sharti				 * template.
763144467Sharti				 */
764144467Sharti				if (!(job->flags & JOB_SILENT) && !shutUp &&
765144467Sharti				    commandShell->hasEchoCtl) {
766144467Sharti					DBPRINTF("%s\n", commandShell->echoOff);
767144467Sharti					DBPRINTF(commandShell->errCheck, cmd);
768144467Sharti					shutUp = TRUE;
769144467Sharti				}
770144467Sharti				cmdTemplate = commandShell->ignErr;
771144467Sharti				/*
772144467Sharti				 * The error ignoration (hee hee) is already
773144467Sharti				 * taken care of by the ignErr template, so
774144467Sharti				 * pretend error checking is still on.
775144467Sharti				*/
776144467Sharti				errOff = FALSE;
777144467Sharti			} else {
778144467Sharti				errOff = FALSE;
779144467Sharti			}
780144467Sharti		} else {
781144467Sharti			errOff = FALSE;
782144467Sharti		}
783144467Sharti	}
784144467Sharti
785144467Sharti	DBPRINTF(cmdTemplate, cmd);
786144467Sharti
787144467Sharti	if (errOff) {
7881590Srgrimes		/*
789144467Sharti		 * If echoing is already off, there's no point in issuing the
790144467Sharti		 * echoOff command. Otherwise we issue it and pretend it was on
791144467Sharti		 * for the whole command...
7921590Srgrimes		 */
793144467Sharti		if (!shutUp && !(job->flags & JOB_SILENT) &&
7941590Srgrimes		    commandShell->hasEchoCtl) {
79518730Ssteve			DBPRINTF("%s\n", commandShell->echoOff);
7961590Srgrimes			shutUp = TRUE;
7971590Srgrimes		}
798144467Sharti		DBPRINTF("%s\n", commandShell->errCheck);
7991590Srgrimes	}
800144467Sharti	if (shutUp) {
801144467Sharti		DBPRINTF("%s\n", commandShell->echoOn);
8021590Srgrimes	}
803144467Sharti	return (0);
8041590Srgrimes}
8051590Srgrimes
806144467Sharti/**
80718730Ssteve * JobClose --
80818730Ssteve *	Called to close both input and output pipes when a job is finished.
80918730Ssteve *
81018730Ssteve * Side Effects:
81118730Ssteve *	The file descriptors associated with the job are closed.
81218730Ssteve */
81318730Sstevestatic void
814104696SjmallettJobClose(Job *job)
81518730Ssteve{
816138232Sharti
817144467Sharti	if (usePipes) {
818137202Sharti#if !defined(USE_KQUEUE)
819144467Sharti		FD_CLR(job->inPipe, &outputs);
82018730Ssteve#endif
821144467Sharti		if (job->outPipe != job->inPipe) {
822144467Sharti			close(job->outPipe);
823144467Sharti		}
824144467Sharti		JobDoOutput(job, TRUE);
825144467Sharti		close(job->inPipe);
826144467Sharti	} else {
827144467Sharti		close(job->outFd);
828144467Sharti		JobDoOutput(job, TRUE);
82918730Ssteve	}
83018730Ssteve}
83118730Ssteve
832144467Sharti/**
8331590Srgrimes * JobFinish  --
8341590Srgrimes *	Do final processing for the given job including updating
8351590Srgrimes *	parents and starting new jobs as available/necessary. Note
8361590Srgrimes *	that we pay no attention to the JOB_IGNERR flag here.
8371590Srgrimes *	This is because when we're called because of a noexecute flag
8381590Srgrimes *	or something, jstat.w_status is 0 and when called from
8391590Srgrimes *	Job_CatchChildren, the status is zeroed if it s/b ignored.
8401590Srgrimes *
8411590Srgrimes * Side Effects:
8421590Srgrimes *	Some nodes may be put on the toBeMade queue.
8431590Srgrimes *	Final commands for the job are placed on postCommands.
8441590Srgrimes *
8451590Srgrimes *	If we got an error and are aborting (aborting == ABORT_ERROR) and
8461590Srgrimes *	the job list is now empty, we are done for the day.
8471590Srgrimes *	If we recognized an error (errors !=0), we set the aborting flag
8481590Srgrimes *	to ABORT_ERROR so no more jobs will be started.
8491590Srgrimes */
8501590Srgrimesstatic void
851104696SjmallettJobFinish(Job *job, int *status)
8521590Srgrimes{
853144467Sharti	Boolean	done;
854144467Sharti	LstNode	*ln;
8551590Srgrimes
856146133Sharti	if (WIFEXITED(*status)) {
857146133Sharti		int	job_status = WEXITSTATUS(*status);
858146133Sharti
859144467Sharti		JobClose(job);
860144467Sharti		/*
861146133Sharti		 * Deal with ignored errors in -B mode. We need to
862146133Sharti		 * print a message telling of the ignored error as
863146133Sharti		 * well as setting status.w_status to 0 so the next
864146133Sharti		 * command gets run. To do this, we set done to be
865146133Sharti		 * TRUE if in -B mode and the job exited non-zero.
866144467Sharti		 */
867146133Sharti		if (job_status == 0) {
868146133Sharti			done = FALSE;
869146133Sharti		} else {
870146133Sharti			if (job->flags & JOB_IGNERR) {
871146133Sharti				done = TRUE;
872146133Sharti			} else {
873146133Sharti				/*
874146133Sharti				 * If it exited non-zero and either we're
875146133Sharti				 * doing things our way or we're not ignoring
876146133Sharti				 * errors, the job is finished. Similarly, if
877146133Sharti				 * the shell died because of a signal the job
878146133Sharti				 * is also finished. In these cases, finish
879146133Sharti				 * out the job's output before printing the
880146133Sharti				 * exit status...
881146133Sharti				 */
882146133Sharti				done = TRUE;
883146133Sharti				if (job->cmdFILE != NULL &&
884146133Sharti				    job->cmdFILE != stdout) {
885146133Sharti					fclose(job->cmdFILE);
886146133Sharti				}
8878874Srgrimes
888146133Sharti			}
889146133Sharti		}
890146133Sharti	} else if (WIFSIGNALED(*status)) {
891146133Sharti		if (WTERMSIG(*status) == SIGCONT) {
892146133Sharti			/*
893146133Sharti			 * No need to close things down or anything.
894146133Sharti			 */
895146133Sharti			done = FALSE;
896146133Sharti		} else {
897146133Sharti			/*
898146133Sharti			 * If it exited non-zero and either we're
899146133Sharti			 * doing things our way or we're not ignoring
900146133Sharti			 * errors, the job is finished. Similarly, if
901146133Sharti			 * the shell died because of a signal the job
902146133Sharti			 * is also finished. In these cases, finish
903146133Sharti			 * out the job's output before printing the
904146133Sharti			 * exit status...
905146133Sharti			 */
906146133Sharti			JobClose(job);
907146133Sharti			if (job->cmdFILE != NULL &&
908146133Sharti			    job->cmdFILE != stdout) {
909146133Sharti				fclose(job->cmdFILE);
910146133Sharti			}
911146133Sharti			done = TRUE;
912146133Sharti		}
9131590Srgrimes	} else {
914144467Sharti		/*
915144467Sharti		 * No need to close things down or anything.
916144467Sharti		 */
917144467Sharti		done = FALSE;
9181590Srgrimes	}
9191590Srgrimes
920146133Sharti	if (WIFEXITED(*status)) {
921146133Sharti		if (done || DEBUG(JOB)) {
922146133Sharti			FILE   *out;
923144467Sharti
924146133Sharti			if (compatMake &&
925146133Sharti			    !usePipes &&
926146133Sharti			    (job->flags & JOB_IGNERR)) {
927146133Sharti				/*
928146133Sharti				 * If output is going to a file and this job
929146133Sharti				 * is ignoring errors, arrange to have the
930146133Sharti				 * exit status sent to the output file as
931146133Sharti				 * well.
932146133Sharti				 */
933146133Sharti				out = fdopen(job->outFd, "w");
934146133Sharti				if (out == NULL)
935146133Sharti					Punt("Cannot fdopen");
936146133Sharti			} else {
937146133Sharti				out = stdout;
938146133Sharti			}
9391590Srgrimes
940144665Sharti			DEBUGF(JOB, ("Process %jd exited.\n",
941144665Sharti			    (intmax_t)job->pid));
942146133Sharti
943146133Sharti			if (WEXITSTATUS(*status) == 0) {
944146133Sharti				if (DEBUG(JOB)) {
945146133Sharti					if (usePipes && job->node != lastNode) {
946146133Sharti						MESSAGE(out, job->node);
947146133Sharti						lastNode = job->node;
948146133Sharti					}
949146133Sharti					fprintf(out,
950146133Sharti					    "*** Completed successfully\n");
951146133Sharti				}
952146133Sharti			} else {
953144467Sharti				if (usePipes && job->node != lastNode) {
954144467Sharti					MESSAGE(out, job->node);
955144467Sharti					lastNode = job->node;
956144467Sharti				}
957144467Sharti				fprintf(out, "*** Error code %d%s\n",
958146133Sharti					WEXITSTATUS(*status),
959146133Sharti					(job->flags & JOB_IGNERR) ?
960146133Sharti					"(ignored)" : "");
961144467Sharti
962144467Sharti				if (job->flags & JOB_IGNERR) {
963144467Sharti					*status = 0;
964144467Sharti				}
965144467Sharti			}
966144467Sharti
967144467Sharti			fflush(out);
968146133Sharti		}
969146133Sharti	} else if (WIFSIGNALED(*status)) {
970146133Sharti		if (done || DEBUG(JOB) || (WTERMSIG(*status) == SIGCONT)) {
971146133Sharti			FILE   *out;
972144467Sharti
973146133Sharti			if (compatMake &&
974146133Sharti			    !usePipes &&
975146133Sharti			    (job->flags & JOB_IGNERR)) {
976146133Sharti				/*
977146133Sharti				 * If output is going to a file and this job
978146133Sharti				 * is ignoring errors, arrange to have the
979146133Sharti				 * exit status sent to the output file as
980146133Sharti				 * well.
981146133Sharti				 */
982146133Sharti				out = fdopen(job->outFd, "w");
983146133Sharti				if (out == NULL)
984146133Sharti					Punt("Cannot fdopen");
985146133Sharti			} else {
986146133Sharti				out = stdout;
987146133Sharti			}
988146133Sharti
989146133Sharti			if (WTERMSIG(*status) == SIGCONT) {
990146133Sharti				/*
991146133Sharti				 * If the beastie has continued, shift the
992146133Sharti				 * Job from the stopped list to the running
993146133Sharti				 * one (or re-stop it if concurrency is
994146133Sharti				 * exceeded) and go and get another child.
995146133Sharti				 */
996146133Sharti				if (job->flags & (JOB_RESUME | JOB_RESTART)) {
997146133Sharti					if (usePipes && job->node != lastNode) {
998146133Sharti						MESSAGE(out, job->node);
999146133Sharti						lastNode = job->node;
1000146133Sharti					}
1001146133Sharti					fprintf(out, "*** Continued\n");
1002146133Sharti				}
1003146133Sharti				if (!(job->flags & JOB_CONTINUING)) {
1004146133Sharti					DEBUGF(JOB, ("Warning: process %jd was not "
1005146133Sharti						     "continuing.\n", (intmax_t) job->pid));
1006146133Sharti#ifdef notdef
1007146133Sharti					/*
1008146133Sharti					 * We don't really want to restart a
1009146133Sharti					 * job from scratch just because it
1010146133Sharti					 * continued, especially not without
1011146133Sharti					 * killing the continuing process!
1012146133Sharti					 * That's why this is ifdef'ed out.
1013146133Sharti					 * FD - 9/17/90
1014146133Sharti					 */
1015146133Sharti					JobRestart(job);
1016146133Sharti#endif
1017146133Sharti				}
1018146133Sharti				job->flags &= ~JOB_CONTINUING;
1019146133Sharti				TAILQ_INSERT_TAIL(&jobs, job, link);
1020146133Sharti				nJobs += 1;
1021146133Sharti				DEBUGF(JOB, ("Process %jd is continuing locally.\n",
1022146133Sharti					     (intmax_t) job->pid));
1023146133Sharti				if (nJobs == maxJobs) {
1024146133Sharti					jobFull = TRUE;
1025146133Sharti					DEBUGF(JOB, ("Job queue is full.\n"));
1026146133Sharti				}
1027146133Sharti				fflush(out);
1028146133Sharti				return;
1029146133Sharti
1030146133Sharti			} else {
1031144467Sharti				if (usePipes && job->node != lastNode) {
1032144467Sharti					MESSAGE(out, job->node);
1033144467Sharti					lastNode = job->node;
1034144467Sharti				}
1035146133Sharti				fprintf(out,
1036146133Sharti				    "*** Signal %d\n", WTERMSIG(*status));
1037146133Sharti				fflush(out);
1038144467Sharti			}
1039146133Sharti		}
1040146133Sharti	} else {
1041146133Sharti		/* STOPPED */
1042146133Sharti		FILE   *out;
10431590Srgrimes
1044146133Sharti		if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
1045146133Sharti			/*
1046146133Sharti			 * If output is going to a file and this job
1047146133Sharti			 * is ignoring errors, arrange to have the
1048146133Sharti			 * exit status sent to the output file as
1049146133Sharti			 * well.
1050146133Sharti			 */
1051146133Sharti			out = fdopen(job->outFd, "w");
1052146133Sharti			if (out == NULL)
1053146133Sharti				Punt("Cannot fdopen");
1054144467Sharti		} else {
1055146133Sharti			out = stdout;
1056144467Sharti		}
10571590Srgrimes
1058146133Sharti		DEBUGF(JOB, ("Process %jd stopped.\n", (intmax_t) job->pid));
1059146133Sharti		if (usePipes && job->node != lastNode) {
1060146133Sharti			MESSAGE(out, job->node);
1061146133Sharti			lastNode = job->node;
1062146133Sharti		}
1063146133Sharti		fprintf(out, "*** Stopped -- signal %d\n", WSTOPSIG(*status));
1064146133Sharti		job->flags |= JOB_RESUME;
1065146133Sharti		TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1066144467Sharti		fflush(out);
1067146133Sharti		return;
10681590Srgrimes	}
10691590Srgrimes
10701590Srgrimes	/*
1071144467Sharti	 * Now handle the -B-mode stuff. If the beast still isn't finished,
1072144467Sharti	 * try and restart the job on the next command. If JobStart says it's
1073144467Sharti	 * ok, it's ok. If there's an error, this puppy is done.
10741590Srgrimes	 */
1075144467Sharti	if (compatMake && WIFEXITED(*status) &&
1076144467Sharti	    Lst_Succ(job->node->compat_command) != NULL) {
1077144467Sharti		switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
1078144467Sharti		  case JOB_RUNNING:
1079144467Sharti			done = FALSE;
1080144467Sharti			break;
1081144467Sharti		  case JOB_ERROR:
1082144467Sharti			done = TRUE;
1083144467Sharti			W_SETEXITSTATUS(status, 1);
1084144467Sharti			break;
1085144467Sharti		  case JOB_FINISHED:
1086144467Sharti			/*
1087144467Sharti			 * If we got back a JOB_FINISHED code, JobStart has
1088144467Sharti			 * already called Make_Update and freed the job
1089144467Sharti			 * descriptor. We set done to false here to avoid fake
1090144467Sharti			 * cycles and double frees. JobStart needs to do the
1091144467Sharti			 * update so we can proceed up the graph when given
1092144467Sharti			 * the -n flag..
1093144467Sharti			 */
1094144467Sharti			done = FALSE;
1095144467Sharti			break;
1096144467Sharti		  default:
1097144467Sharti			break;
1098144467Sharti		}
1099144467Sharti	} else {
1100144467Sharti		done = TRUE;
11011590Srgrimes	}
1102143703Sharti
1103144657Sharti	if (done && aborting != ABORT_ERROR &&
1104144657Sharti	    aborting != ABORT_INTERRUPT && *status == 0) {
1105144467Sharti		/*
1106144467Sharti		 * As long as we aren't aborting and the job didn't return a
1107144467Sharti		 * non-zero status that we shouldn't ignore, we call
1108144467Sharti		 * Make_Update to update the parents. In addition, any saved
1109144467Sharti		 * commands for the node are placed on the .END target.
1110144467Sharti		 */
1111144467Sharti		for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
1112144467Sharti			Lst_AtEnd(&postCommands->commands,
1113146027Sharti			    Buf_Peel(
1114146027Sharti				Var_Subst(Lst_Datum(ln), job->node, FALSE)));
1115144467Sharti		}
11161590Srgrimes
1117144467Sharti		job->node->made = MADE;
1118144467Sharti		Make_Update(job->node);
1119144467Sharti		free(job);
11201590Srgrimes
1121144467Sharti	} else if (*status != 0) {
1122144467Sharti		errors += 1;
1123144467Sharti		free(job);
1124144467Sharti	}
1125144467Sharti
1126144467Sharti	JobRestartJobs();
1127144467Sharti
11281590Srgrimes	/*
1129144467Sharti	 * Set aborting if any error.
11301590Srgrimes	 */
1131144657Sharti	if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
1132144467Sharti		/*
1133144467Sharti		 * If we found any errors in this batch of children and the -k
1134144467Sharti		 * flag wasn't given, we set the aborting flag so no more jobs
1135144467Sharti		 * get started.
1136144467Sharti		 */
1137144467Sharti		aborting = ABORT_ERROR;
1138144467Sharti	}
11398874Srgrimes
1140144657Sharti	if (aborting == ABORT_ERROR && Job_Empty()) {
1141144467Sharti		/*
1142144467Sharti		 * If we are aborting and the job table is now empty, we finish.
1143144467Sharti		 */
1144144467Sharti		Finish(errors);
1145144467Sharti	}
11461590Srgrimes}
11471590Srgrimes
1148144467Sharti/**
1149144467Sharti * Job_Touch
11501590Srgrimes *	Touch the given target. Called by JobStart when the -t flag was
1151104696Sjmallett *	given.  Prints messages unless told to be silent.
11521590Srgrimes *
11531590Srgrimes * Side Effects:
11541590Srgrimes *	The data modification of the file is changed. In addition, if the
11551590Srgrimes *	file did not exist, it is created.
11561590Srgrimes */
11571590Srgrimesvoid
1158104696SjmallettJob_Touch(GNode *gn, Boolean silent)
11591590Srgrimes{
1160144467Sharti	int	streamID;	/* ID of stream opened to do the touch */
1161144467Sharti	struct utimbuf times;	/* Times for utime() call */
11621590Srgrimes
1163144467Sharti	if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
1164144467Sharti		/*
1165144467Sharti		 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
1166144467Sharti		 * targets and, as such, shouldn't really be created.
1167144467Sharti		 */
1168144467Sharti		return;
1169144467Sharti	}
11708874Srgrimes
1171144467Sharti	if (!silent) {
1172144467Sharti		fprintf(stdout, "touch %s\n", gn->name);
1173144467Sharti		fflush(stdout);
1174144467Sharti	}
11751590Srgrimes
1176144467Sharti	if (noExecute) {
1177144467Sharti		return;
1178144467Sharti	}
11791590Srgrimes
1180144467Sharti	if (gn->type & OP_ARCHV) {
1181144467Sharti		Arch_Touch(gn);
1182144467Sharti	} else if (gn->type & OP_LIB) {
1183144467Sharti		Arch_TouchLib(gn);
1184144467Sharti	} else {
1185144467Sharti		char	*file = gn->path ? gn->path : gn->name;
11861590Srgrimes
1187144467Sharti		times.actime = times.modtime = now;
1188144467Sharti		if (utime(file, &times) < 0) {
1189144467Sharti			streamID = open(file, O_RDWR | O_CREAT, 0666);
11901590Srgrimes
1191144467Sharti			if (streamID >= 0) {
1192144467Sharti				char	c;
11931590Srgrimes
1194144467Sharti				/*
1195144467Sharti				 * Read and write a byte to the file to change
1196144467Sharti				 * the modification time, then close the file.
1197144467Sharti				 */
1198144467Sharti				if (read(streamID, &c, 1) == 1) {
1199144467Sharti					lseek(streamID, (off_t)0, SEEK_SET);
1200144467Sharti					write(streamID, &c, 1);
1201144467Sharti				}
1202144467Sharti
1203144467Sharti				close(streamID);
1204144467Sharti			} else {
1205144467Sharti				fprintf(stdout, "*** couldn't touch %s: %s",
1206144467Sharti				    file, strerror(errno));
1207144467Sharti				fflush(stdout);
1208144467Sharti			}
12091590Srgrimes		}
12101590Srgrimes	}
12111590Srgrimes}
12121590Srgrimes
1213144467Sharti/**
1214144467Sharti * Job_CheckCommands
12158874Srgrimes *	Make sure the given node has all the commands it needs.
12161590Srgrimes *
12171590Srgrimes * Results:
12181590Srgrimes *	TRUE if the commands list is/was ok.
12191590Srgrimes *
12201590Srgrimes * Side Effects:
12211590Srgrimes *	The node will have commands from the .DEFAULT rule added to it
12221590Srgrimes *	if it needs them.
12231590Srgrimes */
12241590SrgrimesBoolean
1225104696SjmallettJob_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
12261590Srgrimes{
1227138232Sharti
1228144467Sharti	if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
1229144467Sharti	    (gn->type & OP_LIB) == 0) {
1230144467Sharti		/*
1231144467Sharti		 * No commands. Look for .DEFAULT rule from which we might infer
1232144467Sharti		 * commands.
1233144467Sharti		 */
1234144657Sharti		if (DEFAULT != NULL && !Lst_IsEmpty(&DEFAULT->commands)) {
1235144467Sharti			/*
1236144467Sharti			 * Make only looks for a .DEFAULT if the node was
1237144467Sharti			 * never the target of an operator, so that's what we
1238144467Sharti			 * do too. If a .DEFAULT was given, we substitute its
1239144467Sharti			 * commands for gn's commands and set the IMPSRC
1240144467Sharti			 * variable to be the target's name The DEFAULT node
1241144467Sharti			 * acts like a transformation rule, in that gn also
1242144467Sharti			 * inherits any attributes or sources attached to
1243144467Sharti			 * .DEFAULT itself.
1244144467Sharti			 */
1245144467Sharti			Make_HandleUse(DEFAULT, gn);
1246146580Sharti			Var_Set(IMPSRC, Var_Value(TARGET, gn), gn);
124718730Ssteve
1248144467Sharti		} else if (Dir_MTime(gn) == 0) {
1249144467Sharti			/*
1250144467Sharti			 * The node wasn't the target of an operator we have
1251144467Sharti			 * no .DEFAULT rule to go on and the target doesn't
1252144467Sharti			 * already exist. There's nothing more we can do for
1253144467Sharti			 * this branch. If the -k flag wasn't given, we stop
1254144467Sharti			 * in our tracks, otherwise we just don't update
1255144467Sharti			 * this node's parents so they never get examined.
1256144467Sharti			 */
1257144467Sharti			static const char msg[] =
1258144467Sharti			    "make: don't know how to make";
1259144467Sharti
1260144467Sharti			if (gn->type & OP_OPTIONAL) {
1261144467Sharti				fprintf(stdout, "%s %s(ignored)\n",
1262144467Sharti				    msg, gn->name);
1263144467Sharti				fflush(stdout);
1264144467Sharti			} else if (keepgoing) {
1265144467Sharti				fprintf(stdout, "%s %s(continuing)\n",
1266144467Sharti				    msg, gn->name);
1267144467Sharti				fflush(stdout);
1268144467Sharti				return (FALSE);
1269144467Sharti			} else {
1270176808Sobrien#ifndef WITHOUT_OLD_JOKE
1271144467Sharti				if (strcmp(gn->name,"love") == 0)
1272144467Sharti					(*abortProc)("Not war.");
1273144467Sharti				else
1274176808Sobrien#endif
1275144467Sharti					(*abortProc)("%s %s. Stop",
1276144467Sharti					    msg, gn->name);
1277144467Sharti				return (FALSE);
1278144467Sharti			}
1279144467Sharti		}
12801590Srgrimes	}
1281144467Sharti	return (TRUE);
12821590Srgrimes}
12831590Srgrimes
1284144467Sharti/**
1285144467Sharti * JobExec
12861590Srgrimes *	Execute the shell for the given job. Called from JobStart and
12871590Srgrimes *	JobRestart.
12881590Srgrimes *
12891590Srgrimes * Side Effects:
12901590Srgrimes *	A shell is executed, outputs is altered and the Job structure added
12911590Srgrimes *	to the job table.
12921590Srgrimes */
12931590Srgrimesstatic void
1294104696SjmallettJobExec(Job *job, char **argv)
12951590Srgrimes{
1296146129Sharti	ProcStuff	ps;
12978874Srgrimes
1298144467Sharti	if (DEBUG(JOB)) {
1299146061Sharti		int	  i;
13008874Srgrimes
1301144467Sharti		DEBUGF(JOB, ("Running %s\n", job->node->name));
1302144467Sharti		DEBUGF(JOB, ("\tCommand: "));
1303144467Sharti		for (i = 0; argv[i] != NULL; i++) {
1304144467Sharti			DEBUGF(JOB, ("%s ", argv[i]));
1305144467Sharti		}
1306144467Sharti		DEBUGF(JOB, ("\n"));
13071590Srgrimes	}
13088874Srgrimes
13091590Srgrimes	/*
1310144467Sharti	 * Some jobs produce no output and it's disconcerting to have
1311144467Sharti	 * no feedback of their running (since they produce no output, the
1312144467Sharti	 * banner with their name in it never appears). This is an attempt to
1313144467Sharti	 * provide that feedback, even if nothing follows it.
13141590Srgrimes	 */
1315144657Sharti	if (lastNode != job->node && (job->flags & JOB_FIRST) &&
1316144467Sharti	    !(job->flags & JOB_SILENT)) {
1317144467Sharti		MESSAGE(stdout, job->node);
1318144467Sharti		lastNode = job->node;
13191590Srgrimes	}
13201590Srgrimes
1321146129Sharti	ps.in = FILENO(job->cmdFILE);
1322146129Sharti	if (usePipes) {
1323146129Sharti		/*
1324146129Sharti		 * Set up the child's output to be routed through the
1325146129Sharti		 * pipe we've created for it.
1326146129Sharti		 */
1327146129Sharti		ps.out = job->outPipe;
1328146129Sharti	} else {
1329146129Sharti		/*
1330146129Sharti		 * We're capturing output in a file, so we duplicate
1331146129Sharti		 * the descriptor to the temporary file into the
1332146129Sharti		 * standard output.
1333146129Sharti		 */
1334146129Sharti		ps.out = job->outFd;
1335146129Sharti	}
1336146129Sharti	ps.err = STDERR_FILENO;
1337146129Sharti
1338146129Sharti	ps.merge_errors = 1;
1339146129Sharti	ps.pgroup = 1;
1340146129Sharti	ps.searchpath = 0;
1341146129Sharti
1342146129Sharti	ps.argv = argv;
1343146156Sharti	ps.argv_free = 0;
1344146129Sharti
1345146129Sharti	/*
1346146129Sharti	 * Fork.  Warning since we are doing vfork() instead of fork(),
1347146129Sharti	 * do not allocate memory in the child process!
1348146129Sharti	 */
1349146130Sharti	if ((ps.child_pid = vfork()) == -1) {
1350144467Sharti		Punt("Cannot fork");
1351144467Sharti
1352146130Sharti
1353146130Sharti	} else if (ps.child_pid == 0) {
1354144665Sharti		/*
1355144665Sharti		 * Child
1356144665Sharti		 */
1357144467Sharti		if (fifoFd >= 0)
1358144467Sharti			close(fifoFd);
1359144467Sharti
1360146574Sharti		Proc_Exec(&ps);
1361146129Sharti		/* NOTREACHED */
1362144665Sharti	}
1363146130Sharti
1364144665Sharti	/*
1365144665Sharti	 * Parent
1366144665Sharti	 */
1367146130Sharti	job->pid = ps.child_pid;
1368144467Sharti
1369144665Sharti	if (usePipes && (job->flags & JOB_FIRST)) {
1370144665Sharti		/*
1371144665Sharti		 * The first time a job is run for a node, we set the
1372144665Sharti		 * current position in the buffer to the beginning and
1373144665Sharti		 * mark another stream to watch in the outputs mask.
1374144665Sharti		 */
1375104475Sphk#ifdef USE_KQUEUE
1376144665Sharti		struct kevent	kev[2];
1377104475Sphk#endif
1378144665Sharti		job->curPos = 0;
13798874Srgrimes
1380137202Sharti#if defined(USE_KQUEUE)
1381144665Sharti		EV_SET(&kev[0], job->inPipe, EVFILT_READ, EV_ADD, 0, 0, job);
1382144665Sharti		EV_SET(&kev[1], job->pid, EVFILT_PROC,
1383144665Sharti		    EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
1384144665Sharti		if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1385144665Sharti			/*
1386144665Sharti			 * kevent() will fail if the job is already
1387144665Sharti			 * finished
1388144665Sharti			 */
1389144665Sharti			if (errno != EINTR && errno != EBADF && errno != ESRCH)
1390144665Sharti				Punt("kevent: %s", strerror(errno));
1391144665Sharti		}
13921590Srgrimes#else
1393144665Sharti		FD_SET(job->inPipe, &outputs);
1394137202Sharti#endif /* USE_KQUEUE */
1395144665Sharti	}
1396144467Sharti
1397144665Sharti	if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1398144665Sharti		fclose(job->cmdFILE);
1399144665Sharti		job->cmdFILE = NULL;
14001590Srgrimes	}
14011590Srgrimes
1402144467Sharti	/*
1403144467Sharti	 * Now the job is actually running, add it to the table.
1404144467Sharti	 */
1405144467Sharti	nJobs += 1;
1406144494Sharti	TAILQ_INSERT_TAIL(&jobs, job, link);
1407144467Sharti	if (nJobs == maxJobs) {
1408144467Sharti		jobFull = TRUE;
14091590Srgrimes	}
14101590Srgrimes}
14111590Srgrimes
1412144467Sharti/**
1413144467Sharti * JobMakeArgv
14141590Srgrimes *	Create the argv needed to execute the shell for a given job.
14151590Srgrimes */
14161590Srgrimesstatic void
1417104696SjmallettJobMakeArgv(Job *job, char **argv)
14181590Srgrimes{
1419144467Sharti	int		argc;
1420144467Sharti	static char	args[10];	/* For merged arguments */
14218874Srgrimes
1422146557Sharti	argv[0] = commandShell->name;
1423144467Sharti	argc = 1;
14241590Srgrimes
1425144657Sharti	if ((commandShell->exit && *commandShell->exit != '-') ||
1426144657Sharti	    (commandShell->echo && *commandShell->echo != '-')) {
1427144467Sharti		/*
1428144467Sharti		 * At least one of the flags doesn't have a minus before it, so
1429144467Sharti		 * merge them together. Have to do this because the *(&(@*#*&#$#
1430144467Sharti		 * Bourne shell thinks its second argument is a file to source.
1431144467Sharti		 * Grrrr. Note the ten-character limitation on the combined
1432144467Sharti		 * arguments.
1433144467Sharti		 */
1434144657Sharti		sprintf(args, "-%s%s", (job->flags & JOB_IGNERR) ? "" :
1435144657Sharti		    commandShell->exit ? commandShell->exit : "",
1436144657Sharti		    (job->flags & JOB_SILENT) ? "" :
1437144657Sharti		    commandShell->echo ? commandShell->echo : "");
14381590Srgrimes
1439144467Sharti		if (args[1]) {
1440144467Sharti			argv[argc] = args;
1441144467Sharti			argc++;
1442144467Sharti		}
1443144467Sharti	} else {
1444144467Sharti		if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1445144467Sharti			argv[argc] = commandShell->exit;
1446144467Sharti			argc++;
1447144467Sharti		}
1448144467Sharti		if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1449144467Sharti			argv[argc] = commandShell->echo;
1450144467Sharti			argc++;
1451144467Sharti		}
14521590Srgrimes	}
1453144467Sharti	argv[argc] = NULL;
14541590Srgrimes}
14551590Srgrimes
1456144467Sharti/**
1457144467Sharti * JobRestart
1458144494Sharti *	Restart a job that stopped for some reason. The job must be neither
1459144494Sharti *	on the jobs nor on the stoppedJobs list.
14601590Srgrimes *
14611590Srgrimes * Side Effects:
14621590Srgrimes *	jobFull will be set if the job couldn't be run.
14631590Srgrimes */
14641590Srgrimesstatic void
1465104696SjmallettJobRestart(Job *job)
14661590Srgrimes{
146718730Ssteve
1468144467Sharti	if (job->flags & JOB_RESTART) {
1469144467Sharti		/*
1470144467Sharti		 * Set up the control arguments to the shell. This is based on
1471144467Sharti		 * the flags set earlier for this job. If the JOB_IGNERR flag
1472144467Sharti		 * is clear, the 'exit' flag of the commandShell is used to
1473144467Sharti		 * cause it to exit upon receiving an error. If the JOB_SILENT
1474144467Sharti		 * flag is clear, the 'echo' flag of the commandShell is used
1475144467Sharti		 * to get it to start echoing as soon as it starts
1476144467Sharti		 * processing commands.
1477144467Sharti		 */
1478144467Sharti		char	*argv[4];
14798874Srgrimes
1480144467Sharti		JobMakeArgv(job, argv);
14818874Srgrimes
1482144467Sharti		DEBUGF(JOB, ("Restarting %s...", job->node->name));
1483144657Sharti		if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL)) {
1484144467Sharti			/*
1485144657Sharti			 * Not allowed to run -- put it back on the hold
1486144657Sharti			 * queue and mark the table full
1487144467Sharti			 */
1488144467Sharti			DEBUGF(JOB, ("holding\n"));
1489144494Sharti			TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1490144467Sharti			jobFull = TRUE;
1491144467Sharti			DEBUGF(JOB, ("Job queue is full.\n"));
1492144467Sharti			return;
1493144467Sharti		} else {
1494144467Sharti			/*
1495144467Sharti			 * Job may be run locally.
1496144467Sharti			 */
1497144467Sharti			DEBUGF(JOB, ("running locally\n"));
1498144467Sharti		}
1499144467Sharti		JobExec(job, argv);
1500144467Sharti
1501137202Sharti	} else {
15021590Srgrimes		/*
1503144467Sharti		 * The job has stopped and needs to be restarted.
1504144467Sharti		 * Why it stopped, we don't know...
15051590Srgrimes		 */
1506144467Sharti		DEBUGF(JOB, ("Resuming %s...", job->node->name));
1507144657Sharti		if ((nJobs < maxJobs || ((job->flags & JOB_SPECIAL) &&
1508144657Sharti		    maxJobs == 0)) && nJobs != maxJobs) {
1509144467Sharti			/*
1510144467Sharti			 * If we haven't reached the concurrency limit already
1511144467Sharti			 * (or the job must be run and maxJobs is 0), it's ok
1512144467Sharti			 * to resume it.
1513144467Sharti			 */
1514144467Sharti			Boolean error;
1515144467Sharti			int status;
15168874Srgrimes
1517144467Sharti			error = (KILL(job->pid, SIGCONT) != 0);
1518144467Sharti
1519144467Sharti			if (!error) {
1520144467Sharti				/*
1521144467Sharti				 * Make sure the user knows we've continued
1522144467Sharti				 * the beast and actually put the thing in the
1523144467Sharti				 * job table.
1524144467Sharti				 */
1525144467Sharti				job->flags |= JOB_CONTINUING;
1526144467Sharti				status = 0;
1527144467Sharti				W_SETTERMSIG(&status, SIGCONT);
1528144467Sharti				JobFinish(job, &status);
1529144467Sharti
1530144467Sharti				job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1531144467Sharti				DEBUGF(JOB, ("done\n"));
1532144467Sharti			} else {
1533144467Sharti				Error("couldn't resume %s: %s",
1534144467Sharti				job->node->name, strerror(errno));
1535144467Sharti				status = 0;
1536144467Sharti				W_SETEXITSTATUS(&status, 1);
1537144467Sharti				JobFinish(job, &status);
1538144467Sharti			}
1539144467Sharti		} else {
1540144467Sharti			/*
1541144467Sharti			* Job cannot be restarted. Mark the table as full and
1542144467Sharti			* place the job back on the list of stopped jobs.
1543144467Sharti			*/
1544144467Sharti			DEBUGF(JOB, ("table full\n"));
1545144494Sharti			TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1546144467Sharti			jobFull = TRUE;
1547144467Sharti			DEBUGF(JOB, ("Job queue is full.\n"));
1548144467Sharti		}
15491590Srgrimes	}
15501590Srgrimes}
15511590Srgrimes
1552144467Sharti/**
1553144467Sharti * JobStart
15541590Srgrimes *	Start a target-creation process going for the target described
15558874Srgrimes *	by the graph node gn.
15561590Srgrimes *
15571590Srgrimes * Results:
15581590Srgrimes *	JOB_ERROR if there was an error in the commands, JOB_FINISHED
15591590Srgrimes *	if there isn't actually anything left to do for the job and
15601590Srgrimes *	JOB_RUNNING if the job has been started.
15611590Srgrimes *
15621590Srgrimes * Side Effects:
15631590Srgrimes *	A new Job node is created and added to the list of running
15641590Srgrimes *	jobs. PMake is forked and a child shell created.
15651590Srgrimes */
15661590Srgrimesstatic int
1567104696SjmallettJobStart(GNode *gn, int flags, Job *previous)
15681590Srgrimes{
1569144467Sharti	Job	*job;		/* new job descriptor */
1570144467Sharti	char	*argv[4];	/* Argument vector to shell */
1571144467Sharti	Boolean	cmdsOK;		/* true if the nodes commands were all right */
1572144467Sharti	Boolean	noExec;		/* Set true if we decide not to run the job */
1573144467Sharti	int	tfd;		/* File descriptor for temp file */
1574144467Sharti	LstNode	*ln;
1575144654Sharti	char	tfile[sizeof(TMPPAT)];
15761590Srgrimes
1577144467Sharti	if (interrupted) {
1578144467Sharti		JobPassSig(interrupted);
1579144467Sharti		return (JOB_ERROR);
1580144467Sharti	}
1581144467Sharti	if (previous != NULL) {
1582144467Sharti		previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1583144467Sharti		job = previous;
1584144467Sharti	} else {
1585144467Sharti		job = emalloc(sizeof(Job));
1586144467Sharti		flags |= JOB_FIRST;
1587144467Sharti	}
15881590Srgrimes
1589144467Sharti	job->node = gn;
1590144467Sharti	job->tailCmds = NULL;
15911590Srgrimes
15921590Srgrimes	/*
1593144467Sharti	 * Set the initial value of the flags for this job based on the global
1594144467Sharti	 * ones and the node's attributes... Any flags supplied by the caller
1595144467Sharti	 * are also added to the field.
15961590Srgrimes	 */
1597144467Sharti	job->flags = 0;
1598144467Sharti	if (Targ_Ignore(gn)) {
1599144467Sharti		job->flags |= JOB_IGNERR;
16001590Srgrimes	}
1601144467Sharti	if (Targ_Silent(gn)) {
1602144467Sharti		job->flags |= JOB_SILENT;
1603144467Sharti	}
1604144467Sharti	job->flags |= flags;
16058874Srgrimes
16061590Srgrimes	/*
1607144467Sharti	 * Check the commands now so any attributes from .DEFAULT have a chance
1608144658Sharti	 * to migrate to the node.
16091590Srgrimes	 */
1610144658Sharti	if (!compatMake && (job->flags & JOB_FIRST)) {
1611144467Sharti		cmdsOK = Job_CheckCommands(gn, Error);
1612144467Sharti	} else {
1613144467Sharti		cmdsOK = TRUE;
1614144467Sharti	}
16151590Srgrimes
16161590Srgrimes	/*
1617144467Sharti	 * If the -n flag wasn't given, we open up OUR (not the child's)
1618144467Sharti	 * temporary file to stuff commands in it. The thing is rd/wr so we
1619144467Sharti	 * don't need to reopen it to feed it to the shell. If the -n flag
1620144467Sharti	 * *was* given, we just set the file to be stdout. Cute, huh?
16211590Srgrimes	 */
1622144467Sharti	if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1623144467Sharti		/*
1624144467Sharti		 * We're serious here, but if the commands were bogus, we're
1625144467Sharti		 * also dead...
1626144467Sharti		 */
1627144467Sharti		if (!cmdsOK) {
1628144467Sharti			DieHorribly();
1629144467Sharti		}
16308874Srgrimes
1631144467Sharti		strcpy(tfile, TMPPAT);
1632144467Sharti		if ((tfd = mkstemp(tfile)) == -1)
1633144467Sharti			Punt("Cannot create temp file: %s", strerror(errno));
1634144467Sharti		job->cmdFILE = fdopen(tfd, "w+");
1635144467Sharti		eunlink(tfile);
1636144467Sharti		if (job->cmdFILE == NULL) {
1637144467Sharti			close(tfd);
1638144467Sharti			Punt("Could not open %s", tfile);
1639144467Sharti		}
1640144467Sharti		fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1641144467Sharti		/*
1642144467Sharti		 * Send the commands to the command file, flush all its
1643144467Sharti		 * buffers then rewind and remove the thing.
1644144467Sharti		 */
1645144467Sharti		noExec = FALSE;
1646138564Sharti
1647138564Sharti		/*
1648144467Sharti		 * Used to be backwards; replace when start doing multiple
1649144467Sharti		 * commands per shell.
1650138564Sharti		 */
1651144467Sharti		if (compatMake) {
1652144467Sharti			/*
1653144467Sharti			 * Be compatible: If this is the first time for this
1654144467Sharti			 * node, verify its commands are ok and open the
1655144467Sharti			 * commands list for sequential access by later
1656144467Sharti			 * invocations of JobStart. Once that is done, we take
1657144467Sharti			 * the next command off the list and print it to the
1658144467Sharti			 * command file. If the command was an ellipsis, note
1659144467Sharti			 * that there's nothing more to execute.
1660144467Sharti			 */
1661144467Sharti			if (job->flags & JOB_FIRST)
1662144467Sharti				gn->compat_command = Lst_First(&gn->commands);
1663144467Sharti			else
1664144467Sharti				gn->compat_command =
1665144467Sharti				    Lst_Succ(gn->compat_command);
16668874Srgrimes
1667144467Sharti			if (gn->compat_command == NULL ||
1668144467Sharti			    JobPrintCommand(Lst_Datum(gn->compat_command), job))
1669144467Sharti				noExec = TRUE;
1670144467Sharti
1671144467Sharti			if (noExec && !(job->flags & JOB_FIRST)) {
1672144467Sharti				/*
1673144467Sharti				 * If we're not going to execute anything, the
1674144467Sharti				 * job is done and we need to close down the
1675144467Sharti				 * various file descriptors we've opened for
1676144467Sharti				 * output, then call JobDoOutput to catch the
1677144467Sharti				 * final characters or send the file to the
1678144467Sharti				 * screen... Note that the i/o streams are only
1679144467Sharti				 * open if this isn't the first job. Note also
1680144467Sharti				 * that this could not be done in
1681144467Sharti				 * Job_CatchChildren b/c it wasn't clear if
1682144467Sharti				 * there were more commands to execute or not...
1683144467Sharti				 */
1684144467Sharti				JobClose(job);
1685144467Sharti			}
1686144467Sharti		} else {
1687144467Sharti			/*
1688144467Sharti			 * We can do all the commands at once. hooray for sanity
1689144467Sharti			 */
1690144467Sharti			numCommands = 0;
1691144467Sharti			LST_FOREACH(ln, &gn->commands) {
1692144467Sharti				if (JobPrintCommand(Lst_Datum(ln), job))
1693144467Sharti					break;
1694144467Sharti			}
1695144467Sharti
1696144467Sharti			/*
1697144467Sharti			 * If we didn't print out any commands to the shell
1698144467Sharti			 * script, there's not much point in executing the
1699144467Sharti			 * shell, is there?
1700144467Sharti			 */
1701144467Sharti			if (numCommands == 0) {
1702144467Sharti				noExec = TRUE;
1703144467Sharti			}
1704144467Sharti		}
1705144467Sharti
1706144467Sharti	} else if (noExecute) {
1707144467Sharti		/*
1708144467Sharti		 * Not executing anything -- just print all the commands to
1709144467Sharti		 * stdout in one fell swoop. This will still set up
1710144467Sharti		 * job->tailCmds correctly.
1711144467Sharti		 */
1712144467Sharti		if (lastNode != gn) {
1713144467Sharti			MESSAGE(stdout, gn);
1714144467Sharti			lastNode = gn;
1715144467Sharti		}
1716144467Sharti		job->cmdFILE = stdout;
1717144467Sharti
1718144467Sharti		/*
1719144467Sharti		 * Only print the commands if they're ok, but don't die if
1720144467Sharti		 * they're not -- just let the user know they're bad and keep
1721144467Sharti		 * going. It doesn't do any harm in this case and may do
1722144467Sharti		 * some good.
1723144467Sharti		 */
1724144467Sharti		if (cmdsOK) {
1725144467Sharti			LST_FOREACH(ln, &gn->commands) {
1726144467Sharti				if (JobPrintCommand(Lst_Datum(ln), job))
1727144467Sharti					break;
1728144467Sharti			}
1729144467Sharti		}
1730144467Sharti		/*
1731144467Sharti		* Don't execute the shell, thank you.
1732144467Sharti		*/
17331590Srgrimes		noExec = TRUE;
1734144467Sharti
1735144467Sharti	} else {
1736144467Sharti		/*
1737144467Sharti		 * Just touch the target and note that no shell should be
1738144467Sharti		 * executed. Set cmdFILE to stdout to make life easier. Check
1739144467Sharti		 * the commands, too, but don't die if they're no good -- it
1740144467Sharti		 * does no harm to keep working up the graph.
1741144467Sharti		 */
1742144467Sharti		job->cmdFILE = stdout;
1743144467Sharti		Job_Touch(gn, job->flags & JOB_SILENT);
1744144467Sharti		noExec = TRUE;
17451590Srgrimes	}
1746144467Sharti
17471590Srgrimes	/*
1748144467Sharti	 * If we're not supposed to execute a shell, don't.
17491590Srgrimes	 */
1750144467Sharti	if (noExec) {
1751144467Sharti		/*
1752144467Sharti		 * Unlink and close the command file if we opened one
1753144467Sharti		 */
1754144467Sharti		if (job->cmdFILE != stdout) {
1755144467Sharti			if (job->cmdFILE != NULL)
1756144467Sharti				fclose(job->cmdFILE);
1757144467Sharti		} else {
1758144467Sharti			fflush(stdout);
1759144467Sharti		}
1760144467Sharti
1761144467Sharti		/*
1762144467Sharti		 * We only want to work our way up the graph if we aren't here
1763144467Sharti		 * because the commands for the job were no good.
1764144467Sharti		*/
1765144467Sharti		if (cmdsOK) {
1766144467Sharti			if (aborting == 0) {
1767144467Sharti				for (ln = job->tailCmds; ln != NULL;
1768144467Sharti				    ln = LST_NEXT(ln)) {
1769144467Sharti					Lst_AtEnd(&postCommands->commands,
1770146027Sharti					    Buf_Peel(Var_Subst(Lst_Datum(ln),
1771146027Sharti					    job->node, FALSE)));
1772144467Sharti				}
1773144467Sharti				job->node->made = MADE;
1774144467Sharti				Make_Update(job->node);
1775144467Sharti			}
1776144467Sharti			free(job);
1777144467Sharti			return(JOB_FINISHED);
1778144467Sharti		} else {
1779144467Sharti			free(job);
1780144467Sharti			return(JOB_ERROR);
1781144467Sharti		}
1782144467Sharti	} else {
1783144467Sharti		fflush(job->cmdFILE);
17841590Srgrimes	}
1785144467Sharti
17861590Srgrimes	/*
1787144467Sharti	 * Set up the control arguments to the shell. This is based on the flags
1788144467Sharti	 * set earlier for this job.
17891590Srgrimes	 */
1790144467Sharti	JobMakeArgv(job, argv);
17911590Srgrimes
17921590Srgrimes	/*
1793144467Sharti	 * If we're using pipes to catch output, create the pipe by which we'll
1794144467Sharti	 * get the shell's output. If we're using files, print out that we're
1795144467Sharti	 * starting a job and then set up its temporary-file name.
17961590Srgrimes	 */
1797144467Sharti	if (!compatMake || (job->flags & JOB_FIRST)) {
1798144467Sharti		if (usePipes) {
1799144467Sharti			int fd[2];
18001590Srgrimes
1801144467Sharti			if (pipe(fd) == -1)
1802144467Sharti				Punt("Cannot create pipe: %s", strerror(errno));
1803144467Sharti			job->inPipe = fd[0];
1804144467Sharti			job->outPipe = fd[1];
1805144467Sharti			fcntl(job->inPipe, F_SETFD, 1);
1806144467Sharti			fcntl(job->outPipe, F_SETFD, 1);
1807144467Sharti		} else {
1808144467Sharti			fprintf(stdout, "Remaking `%s'\n", gn->name);
1809144467Sharti			fflush(stdout);
1810144467Sharti			strcpy(job->outFile, TMPPAT);
1811144467Sharti			if ((job->outFd = mkstemp(job->outFile)) == -1)
1812144467Sharti				Punt("cannot create temp file: %s",
1813144467Sharti				    strerror(errno));
1814144467Sharti			fcntl(job->outFd, F_SETFD, 1);
18151590Srgrimes		}
18161590Srgrimes	}
18171590Srgrimes
1818144657Sharti	if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL) && maxJobs != 0) {
1819144467Sharti		/*
1820144467Sharti		 * We've hit the limit of concurrency, so put the job on hold
1821144467Sharti		 * until some other job finishes. Note that the special jobs
1822144467Sharti		 * (.BEGIN, .INTERRUPT and .END) may be run even when the
1823144467Sharti		 * limit has been reached (e.g. when maxJobs == 0).
1824144467Sharti		 */
1825144467Sharti		jobFull = TRUE;
18261590Srgrimes
1827144467Sharti		DEBUGF(JOB, ("Can only run job locally.\n"));
1828144467Sharti		job->flags |= JOB_RESTART;
1829144494Sharti		TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
18301590Srgrimes	} else {
1831144467Sharti		if (nJobs >= maxJobs) {
1832144467Sharti			/*
1833144657Sharti			 * If we're running this job as a special case
1834144467Sharti			 * (see above), at least say the table is full.
1835144467Sharti			 */
1836144467Sharti			jobFull = TRUE;
1837144467Sharti			DEBUGF(JOB, ("Local job queue is full.\n"));
1838144467Sharti		}
1839144467Sharti		JobExec(job, argv);
18401590Srgrimes	}
1841144467Sharti	return (JOB_RUNNING);
18421590Srgrimes}
18431590Srgrimes
184418730Sstevestatic char *
1845104696SjmallettJobOutput(Job *job, char *cp, char *endp, int msg)
184618730Ssteve{
1847144467Sharti	char *ecp;
184818730Ssteve
1849144467Sharti	if (commandShell->noPrint) {
1850144467Sharti		ecp = strstr(cp, commandShell->noPrint);
1851144467Sharti		while (ecp != NULL) {
1852144467Sharti			if (cp != ecp) {
1853144467Sharti				*ecp = '\0';
1854144467Sharti				if (msg && job->node != lastNode) {
1855144467Sharti					MESSAGE(stdout, job->node);
1856144467Sharti					lastNode = job->node;
1857144467Sharti				}
1858144467Sharti				/*
1859144467Sharti				 * The only way there wouldn't be a newline
1860144467Sharti				 * after this line is if it were the last in
1861144467Sharti				 * the buffer. However, since the non-printable
1862144467Sharti				 * comes after it, there must be a newline, so
1863144467Sharti				 * we don't print one.
1864144467Sharti				 */
1865144467Sharti				fprintf(stdout, "%s", cp);
1866144467Sharti				fflush(stdout);
1867144467Sharti			}
1868144741Sharti			cp = ecp + strlen(commandShell->noPrint);
1869144467Sharti			if (cp != endp) {
1870144467Sharti				/*
1871144467Sharti				 * Still more to print, look again after
1872144467Sharti				 * skipping the whitespace following the
1873144467Sharti				 * non-printable command....
1874144467Sharti				 */
1875144467Sharti				cp++;
1876144467Sharti				while (*cp == ' ' || *cp == '\t' ||
1877144467Sharti				    *cp == '\n') {
1878144467Sharti					cp++;
1879144467Sharti				}
1880144467Sharti				ecp = strstr(cp, commandShell->noPrint);
1881144467Sharti			} else {
1882144467Sharti				return (cp);
1883144467Sharti			}
188418730Ssteve		}
188518730Ssteve	}
1886144467Sharti	return (cp);
188718730Ssteve}
188818730Ssteve
1889144467Sharti/**
1890144467Sharti * JobDoOutput
18911590Srgrimes *	This function is called at different times depending on
18921590Srgrimes *	whether the user has specified that output is to be collected
18931590Srgrimes *	via pipes or temporary files. In the former case, we are called
18941590Srgrimes *	whenever there is something to read on the pipe. We collect more
18951590Srgrimes *	output from the given job and store it in the job's outBuf. If
18961590Srgrimes *	this makes up a line, we print it tagged by the job's identifier,
18971590Srgrimes *	as necessary.
18981590Srgrimes *	If output has been collected in a temporary file, we open the
18991590Srgrimes *	file and read it line by line, transfering it to our own
19001590Srgrimes *	output channel until the file is empty. At which point we
19011590Srgrimes *	remove the temporary file.
19021590Srgrimes *	In both cases, however, we keep our figurative eye out for the
19031590Srgrimes *	'noPrint' line for the shell from which the output came. If
19041590Srgrimes *	we recognize a line, we don't print it. If the command is not
19051590Srgrimes *	alone on the line (the character after it is not \0 or \n), we
19061590Srgrimes *	do print whatever follows it.
19071590Srgrimes *
19081590Srgrimes * Side Effects:
19091590Srgrimes *	curPos may be shifted as may the contents of outBuf.
19101590Srgrimes */
1911144656Shartistatic void
1912104696SjmallettJobDoOutput(Job *job, Boolean finish)
19131590Srgrimes{
1914144467Sharti	Boolean	gotNL = FALSE;	/* true if got a newline */
1915144467Sharti	Boolean	fbuf;		/* true if our buffer filled up */
1916144467Sharti	int	nr;		/* number of bytes read */
1917144467Sharti	int	i;		/* auxiliary index into outBuf */
1918144467Sharti	int	max;		/* limit for i (end of current data) */
1919144467Sharti	int	nRead;		/* (Temporary) number of bytes read */
1920144467Sharti	FILE	*oFILE;		/* Stream pointer to shell's output file */
1921144467Sharti	char	inLine[132];
19221590Srgrimes
1923144467Sharti	if (usePipes) {
19241590Srgrimes		/*
1925144467Sharti		 * Read as many bytes as will fit in the buffer.
19261590Srgrimes		 */
1927144467Sharti  end_loop:
1928144467Sharti		gotNL = FALSE;
1929144467Sharti		fbuf = FALSE;
19308874Srgrimes
1931144467Sharti		nRead = read(job->inPipe, &job->outBuf[job->curPos],
1932144467Sharti		    JOB_BUFSIZE - job->curPos);
19331590Srgrimes		/*
1934144467Sharti		 * Check for interrupt here too, because the above read may
1935144467Sharti		 * block when the child process is stopped. In this case the
1936144467Sharti		 * interrupt will unblock it (we don't use SA_RESTART).
19371590Srgrimes		 */
1938144467Sharti		if (interrupted)
1939144467Sharti			JobPassSig(interrupted);
19401590Srgrimes
1941144467Sharti		if (nRead < 0) {
1942144467Sharti			DEBUGF(JOB, ("JobDoOutput(piperead)"));
1943144467Sharti			nr = 0;
1944144467Sharti		} else {
1945144467Sharti			nr = nRead;
1946144467Sharti		}
19471590Srgrimes
19481590Srgrimes		/*
1949144467Sharti		 * If we hit the end-of-file (the job is dead), we must flush
1950144467Sharti		 * its remaining output, so pretend we read a newline if
1951144467Sharti		 * there's any output remaining in the buffer.
1952144467Sharti		 * Also clear the 'finish' flag so we stop looping.
19531590Srgrimes		 */
1954144657Sharti		if (nr == 0 && job->curPos != 0) {
1955144467Sharti			job->outBuf[job->curPos] = '\n';
1956144467Sharti			nr = 1;
1957144467Sharti			finish = FALSE;
1958144467Sharti		} else if (nr == 0) {
1959144467Sharti			finish = FALSE;
19601590Srgrimes		}
19618874Srgrimes
19621590Srgrimes		/*
1963144467Sharti		 * Look for the last newline in the bytes we just got. If there
1964144467Sharti		 * is one, break out of the loop with 'i' as its index and
1965144467Sharti		 * gotNL set TRUE.
1966144467Sharti		*/
1967144467Sharti		max = job->curPos + nr;
1968144467Sharti		for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1969144467Sharti			if (job->outBuf[i] == '\n') {
1970144467Sharti				gotNL = TRUE;
1971144467Sharti				break;
1972144467Sharti			} else if (job->outBuf[i] == '\0') {
1973144467Sharti				/*
1974144467Sharti				 * Why?
1975144467Sharti				 */
1976144467Sharti				job->outBuf[i] = ' ';
1977144467Sharti			}
1978144467Sharti		}
19791590Srgrimes
1980144467Sharti		if (!gotNL) {
1981144467Sharti			job->curPos += nr;
1982144467Sharti			if (job->curPos == JOB_BUFSIZE) {
1983144467Sharti				/*
1984144467Sharti				 * If we've run out of buffer space, we have
1985144467Sharti				 * no choice but to print the stuff. sigh.
1986144467Sharti				 */
1987144467Sharti				fbuf = TRUE;
1988144467Sharti				i = job->curPos;
1989144467Sharti			}
19901590Srgrimes		}
1991144467Sharti		if (gotNL || fbuf) {
1992144467Sharti			/*
1993144467Sharti			 * Need to send the output to the screen. Null terminate
1994144467Sharti			 * it first, overwriting the newline character if there
1995144467Sharti			 * was one. So long as the line isn't one we should
1996144467Sharti			 * filter (according to the shell description), we print
1997144467Sharti			 * the line, preceded by a target banner if this target
1998144467Sharti			 * isn't the same as the one for which we last printed
1999144467Sharti			 * something. The rest of the data in the buffer are
2000144467Sharti			 * then shifted down to the start of the buffer and
2001144467Sharti			 * curPos is set accordingly.
2002144467Sharti			 */
2003144467Sharti			job->outBuf[i] = '\0';
2004144467Sharti			if (i >= job->curPos) {
2005144467Sharti				char *cp;
20061590Srgrimes
2007144467Sharti				cp = JobOutput(job, job->outBuf,
2008144467Sharti				    &job->outBuf[i], FALSE);
2009144467Sharti
2010144467Sharti				/*
2011144467Sharti				 * There's still more in that buffer. This time,
2012144467Sharti				 * though, we know there's no newline at the
2013144467Sharti				 * end, so we add one of our own free will.
2014144467Sharti				 */
2015144467Sharti				if (*cp != '\0') {
2016144467Sharti					if (job->node != lastNode) {
2017144467Sharti						MESSAGE(stdout, job->node);
2018144467Sharti						lastNode = job->node;
2019144467Sharti					}
2020144467Sharti					fprintf(stdout, "%s%s", cp,
2021144467Sharti					    gotNL ? "\n" : "");
2022144467Sharti					fflush(stdout);
2023144467Sharti				}
2024144467Sharti			}
2025144467Sharti			if (i < max - 1) {
2026144467Sharti				/* shift the remaining characters down */
2027144467Sharti				memcpy(job->outBuf, &job->outBuf[i + 1],
2028144467Sharti				    max - (i + 1));
2029144467Sharti				job->curPos = max - (i + 1);
2030144467Sharti
2031144467Sharti			} else {
2032144467Sharti				/*
2033144467Sharti				 * We have written everything out, so we just
2034144467Sharti				 * start over from the start of the buffer.
2035144467Sharti				 * No copying. No nothing.
2036144467Sharti				 */
2037144467Sharti				job->curPos = 0;
2038144467Sharti			}
2039144467Sharti		}
2040144467Sharti		if (finish) {
2041144467Sharti			/*
2042144467Sharti			 * If the finish flag is true, we must loop until we hit
2043144467Sharti			 * end-of-file on the pipe. This is guaranteed to happen
2044144467Sharti			 * eventually since the other end of the pipe is now
2045144467Sharti			 * closed (we closed it explicitly and the child has
2046144467Sharti			 * exited). When we do get an EOF, finish will be set
2047144467Sharti			 * FALSE and we'll fall through and out.
2048144467Sharti			 */
2049144467Sharti			goto end_loop;
2050144467Sharti		}
2051144467Sharti
2052144467Sharti	} else {
20531590Srgrimes		/*
2054144467Sharti		 * We've been called to retrieve the output of the job from the
2055144467Sharti		 * temporary file where it's been squirreled away. This consists
2056144467Sharti		 * of opening the file, reading the output line by line, being
2057144467Sharti		 * sure not to print the noPrint line for the shell we used,
2058144467Sharti		 * then close and remove the temporary file. Very simple.
2059144467Sharti		 *
2060144467Sharti		 * Change to read in blocks and do FindSubString type things
2061144467Sharti		 * as for pipes? That would allow for "@echo -n..."
20621590Srgrimes		 */
2063144467Sharti		oFILE = fopen(job->outFile, "r");
2064144467Sharti		if (oFILE != NULL) {
2065144467Sharti			fprintf(stdout, "Results of making %s:\n",
2066144467Sharti			    job->node->name);
2067144467Sharti			fflush(stdout);
2068144467Sharti
2069144467Sharti			while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2070144467Sharti				char	*cp, *endp, *oendp;
2071144467Sharti
2072144467Sharti				cp = inLine;
2073144467Sharti				oendp = endp = inLine + strlen(inLine);
2074144467Sharti				if (endp[-1] == '\n') {
2075144467Sharti					*--endp = '\0';
2076144467Sharti				}
2077144467Sharti				cp = JobOutput(job, inLine, endp, FALSE);
2078144467Sharti
2079144467Sharti				/*
2080144467Sharti				 * There's still more in that buffer. This time,
2081144467Sharti				 * though, we know there's no newline at the
2082144467Sharti				 * end, so we add one of our own free will.
2083144467Sharti				 */
2084144467Sharti				fprintf(stdout, "%s", cp);
2085144467Sharti				fflush(stdout);
2086144467Sharti				if (endp != oendp) {
2087144467Sharti					fprintf(stdout, "\n");
2088144467Sharti					fflush(stdout);
2089144467Sharti				}
2090144467Sharti			}
2091144467Sharti			fclose(oFILE);
2092144467Sharti			eunlink(job->outFile);
20931590Srgrimes		}
20941590Srgrimes	}
20951590Srgrimes}
20961590Srgrimes
2097144467Sharti/**
2098144467Sharti * Job_CatchChildren
20991590Srgrimes *	Handle the exit of a child. Called from Make_Make.
21001590Srgrimes *
21011590Srgrimes * Side Effects:
21021590Srgrimes *	The job descriptor is removed from the list of children.
21031590Srgrimes *
21041590Srgrimes * Notes:
21051590Srgrimes *	We do waits, blocking or not, according to the wisdom of our
21061590Srgrimes *	caller, until there are no more children to report. For each
21071590Srgrimes *	job, call JobFinish to finish things off. This will take care of
21081590Srgrimes *	putting jobs on the stoppedJobs queue.
21091590Srgrimes */
21101590Srgrimesvoid
2111104696SjmallettJob_CatchChildren(Boolean block)
21121590Srgrimes{
2113144665Sharti	pid_t	pid;	/* pid of dead child */
2114144467Sharti	Job	*job;	/* job descriptor for dead child */
2115144467Sharti	int	status;	/* Exit/termination status */
21161590Srgrimes
2117144467Sharti	/*
2118144467Sharti	 * Don't even bother if we know there's no one around.
2119144467Sharti	 */
2120144467Sharti	if (nJobs == 0) {
2121144467Sharti		return;
2122144467Sharti	}
21238874Srgrimes
2124144467Sharti	for (;;) {
2125144467Sharti		pid = waitpid((pid_t)-1, &status,
2126144467Sharti		    (block ? 0 : WNOHANG) | WUNTRACED);
2127144467Sharti		if (pid <= 0)
2128144467Sharti			break;
21291590Srgrimes
2130144665Sharti		DEBUGF(JOB, ("Process %jd exited or stopped.\n",
2131144665Sharti		    (intmax_t)pid));
21321590Srgrimes
2133144494Sharti		TAILQ_FOREACH(job, &jobs, link) {
2134144494Sharti			if (job->pid == pid)
2135144467Sharti				break;
2136143810Sharti		}
2137144467Sharti
2138144494Sharti		if (job == NULL) {
2139144467Sharti			if (WIFSIGNALED(status) &&
2140144467Sharti			    (WTERMSIG(status) == SIGCONT)) {
2141144494Sharti				TAILQ_FOREACH(job, &jobs, link) {
2142144494Sharti					if (job->pid == pid)
2143144467Sharti						break;
2144144467Sharti				}
2145144494Sharti				if (job == NULL) {
2146144665Sharti					Error("Resumed child (%jd) "
2147144665Sharti					    "not in table", (intmax_t)pid);
2148144467Sharti					continue;
2149144467Sharti				}
2150144494Sharti				TAILQ_REMOVE(&stoppedJobs, job, link);
2151144467Sharti			} else {
2152144665Sharti				Error("Child (%jd) not in table?",
2153144665Sharti				    (intmax_t)pid);
2154144467Sharti				continue;
2155144467Sharti			}
2156144467Sharti		} else {
2157144494Sharti			TAILQ_REMOVE(&jobs, job, link);
2158144467Sharti			nJobs -= 1;
2159144467Sharti			if (fifoFd >= 0 && maxJobs > 1) {
2160144467Sharti				write(fifoFd, "+", 1);
2161144467Sharti				maxJobs--;
2162144467Sharti				if (nJobs >= maxJobs)
2163144467Sharti					jobFull = TRUE;
2164144467Sharti				else
2165144467Sharti					jobFull = FALSE;
2166144467Sharti			} else {
2167144467Sharti				DEBUGF(JOB, ("Job queue is no longer full.\n"));
2168144467Sharti				jobFull = FALSE;
2169144467Sharti			}
21701590Srgrimes		}
2171144467Sharti
2172144467Sharti		JobFinish(job, &status);
21731590Srgrimes	}
2174144467Sharti	if (interrupted)
2175144467Sharti		JobPassSig(interrupted);
21761590Srgrimes}
21771590Srgrimes
2178144467Sharti/**
2179144467Sharti * Job_CatchOutput
21801590Srgrimes *	Catch the output from our children, if we're using
21811590Srgrimes *	pipes do so. Otherwise just block time until we get a
2182138232Sharti *	signal(most likely a SIGCHLD) since there's no point in
21831590Srgrimes *	just spinning when there's nothing to do and the reaping
21848874Srgrimes *	of a child can wait for a while.
21851590Srgrimes *
21861590Srgrimes * Side Effects:
21871590Srgrimes *	Output is read from pipes if we're piping.
21881590Srgrimes * -----------------------------------------------------------------------
21891590Srgrimes */
21901590Srgrimesvoid
2191139064Sharti#ifdef USE_KQUEUE
2192139064ShartiJob_CatchOutput(int flag __unused)
2193139064Sharti#else
2194137606SphkJob_CatchOutput(int flag)
2195139064Sharti#endif
21961590Srgrimes{
2197144467Sharti	int		nfds;
2198104475Sphk#ifdef USE_KQUEUE
2199104475Sphk#define KEV_SIZE	4
2200144467Sharti	struct kevent	kev[KEV_SIZE];
2201144467Sharti	int		i;
2202104475Sphk#else
2203144467Sharti	struct timeval	timeout;
2204144467Sharti	fd_set		readfds;
2205144467Sharti	Job		*job;
2206104475Sphk#endif
22071590Srgrimes
2208144467Sharti	fflush(stdout);
22091590Srgrimes
2210144467Sharti	if (usePipes) {
2211104475Sphk#ifdef USE_KQUEUE
2212144467Sharti		if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
2213144467Sharti			if (errno != EINTR)
2214144467Sharti				Punt("kevent: %s", strerror(errno));
2215144467Sharti			if (interrupted)
2216144467Sharti				JobPassSig(interrupted);
2217144467Sharti		} else {
2218144467Sharti			for (i = 0; i < nfds; i++) {
2219144467Sharti				if (kev[i].flags & EV_ERROR) {
2220144467Sharti					warnc(kev[i].data, "kevent");
2221144467Sharti					continue;
2222144467Sharti				}
2223144467Sharti				switch (kev[i].filter) {
2224144467Sharti				  case EVFILT_READ:
2225144467Sharti					JobDoOutput(kev[i].udata, FALSE);
2226144467Sharti					break;
2227144467Sharti				  case EVFILT_PROC:
2228144467Sharti					/*
2229144467Sharti					 * Just wake up and let
2230144467Sharti					 * Job_CatchChildren() collect the
2231144467Sharti					 * terminated job.
2232144467Sharti					 */
2233144467Sharti					break;
2234144467Sharti				}
2235144467Sharti			}
2236104475Sphk		}
2237104475Sphk#else
2238144467Sharti		readfds = outputs;
2239144467Sharti		timeout.tv_sec = SEL_SEC;
2240144467Sharti		timeout.tv_usec = SEL_USEC;
2241144467Sharti		if (flag && jobFull && fifoFd >= 0)
2242144467Sharti			FD_SET(fifoFd, &readfds);
22431590Srgrimes
2244144467Sharti		nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
2245144467Sharti		    (fd_set *)NULL, &timeout);
2246144467Sharti		if (nfds <= 0) {
2247144467Sharti			if (interrupted)
2248144467Sharti				JobPassSig(interrupted);
2249144467Sharti			return;
2250144467Sharti		}
2251144467Sharti		if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2252144467Sharti			if (--nfds <= 0)
2253144467Sharti				return;
2254144467Sharti		}
2255144494Sharti		job = TAILQ_FIRST(&jobs);
2256144494Sharti		while (nfds != 0 && job != NULL) {
2257144467Sharti			if (FD_ISSET(job->inPipe, &readfds)) {
2258144467Sharti				JobDoOutput(job, FALSE);
2259144494Sharti				nfds--;
2260144467Sharti			}
2261144494Sharti			job = TAILQ_NEXT(job, link);
2262144467Sharti		}
2263144467Sharti#endif /* !USE_KQUEUE */
2264137606Sphk	}
22651590Srgrimes}
22661590Srgrimes
2267144467Sharti/**
2268144467Sharti * Job_Make
22691590Srgrimes *	Start the creation of a target. Basically a front-end for
22701590Srgrimes *	JobStart used by the Make module.
22711590Srgrimes *
22721590Srgrimes * Side Effects:
22731590Srgrimes *	Another job is started.
22741590Srgrimes */
22751590Srgrimesvoid
2276104696SjmallettJob_Make(GNode *gn)
22771590Srgrimes{
2278138232Sharti
2279144467Sharti	JobStart(gn, 0, NULL);
22801590Srgrimes}
22811590Srgrimes
2282144467Sharti/**
2283144467Sharti * Job_Init
2284137572Sphk *	Initialize the process module, given a maximum number of jobs.
22851590Srgrimes *
22861590Srgrimes * Side Effects:
22871590Srgrimes *	lists and counters are initialized
22881590Srgrimes */
22891590Srgrimesvoid
2290137572SphkJob_Init(int maxproc)
22911590Srgrimes{
2292144467Sharti	GNode		*begin;	/* node for commands to do at the very start */
2293144467Sharti	const char	*env;
2294144467Sharti	struct sigaction sa;
22951590Srgrimes
2296144467Sharti	fifoFd = -1;
2297144467Sharti	env = getenv("MAKE_JOBS_FIFO");
2298137606Sphk
2299144467Sharti	if (env == NULL && maxproc > 1) {
2300144467Sharti		/*
2301144467Sharti		 * We did not find the environment variable so we are the
2302144467Sharti		 * leader. Create the fifo, open it, write one char per
2303144467Sharti		 * allowed job into the pipe.
2304144467Sharti		 */
2305146155Sharti		fifoFd = mkfifotemp(fifoName);
2306146155Sharti		if (fifoFd < 0) {
2307146155Sharti			env = NULL;
2308146155Sharti		} else {
2309146155Sharti			fifoMaster = 1;
2310146155Sharti			fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2311146155Sharti			env = fifoName;
2312146155Sharti			setenv("MAKE_JOBS_FIFO", env, 1);
2313146155Sharti			while (maxproc-- > 0) {
2314146155Sharti				write(fifoFd, "+", 1);
2315144467Sharti			}
2316146155Sharti			/* The master make does not get a magic token */
2317146155Sharti			jobFull = TRUE;
2318146155Sharti			maxJobs = 0;
2319137606Sphk		}
2320144467Sharti
2321144467Sharti	} else if (env != NULL) {
2322144467Sharti		/*
2323144467Sharti		 * We had the environment variable so we are a slave.
2324144467Sharti		 * Open fifo and give ourselves a magic token which represents
2325144467Sharti		 * the token our parent make has grabbed to start his make
2326144467Sharti		 * process. Otherwise the sub-makes would gobble up tokens and
2327144467Sharti		 * the proper number of tokens to specify to -j would depend
2328144467Sharti		 * on the depth of the tree and the order of execution.
2329144467Sharti		 */
2330144467Sharti		fifoFd = open(env, O_RDWR, 0);
2331144467Sharti		if (fifoFd >= 0) {
2332144467Sharti			fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2333144467Sharti			maxJobs = 1;
2334144467Sharti			jobFull = FALSE;
2335144467Sharti		}
2336137606Sphk	}
2337167329Swill	if (fifoFd < 0) {
2338144467Sharti		maxJobs = maxproc;
2339144467Sharti		jobFull = FALSE;
2340144467Sharti	} else {
2341137606Sphk	}
2342144467Sharti	nJobs = 0;
23431590Srgrimes
2344144467Sharti	aborting = 0;
2345144467Sharti	errors = 0;
23461590Srgrimes
2347144467Sharti	lastNode = NULL;
23481590Srgrimes
2349144467Sharti	if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2350144467Sharti		/*
2351144467Sharti		 * If only one job can run at a time, there's no need for a
2352144467Sharti		 * banner, no is there?
2353144467Sharti		 */
2354144467Sharti		targFmt = "";
2355144467Sharti	} else {
2356144467Sharti		targFmt = TARG_FMT;
2357144467Sharti	}
2358144467Sharti
23591590Srgrimes	/*
2360144467Sharti	 * Catch the four signals that POSIX specifies if they aren't ignored.
2361144467Sharti	 * JobCatchSignal will just set global variables and hope someone
2362144467Sharti	 * else is going to handle the interrupt.
23631590Srgrimes	 */
2364144467Sharti	sa.sa_handler = JobCatchSig;
2365144467Sharti	sigemptyset(&sa.sa_mask);
2366144467Sharti	sa.sa_flags = 0;
23678874Srgrimes
2368144467Sharti	if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2369144467Sharti		sigaction(SIGINT, &sa, NULL);
2370144467Sharti	}
2371144467Sharti	if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2372144467Sharti		sigaction(SIGHUP, &sa, NULL);
2373144467Sharti	}
2374144467Sharti	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2375144467Sharti		sigaction(SIGQUIT, &sa, NULL);
2376144467Sharti	}
2377144467Sharti	if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2378144467Sharti		sigaction(SIGTERM, &sa, NULL);
2379144467Sharti	}
2380144467Sharti	/*
2381144467Sharti	 * There are additional signals that need to be caught and passed if
2382144467Sharti	 * either the export system wants to be told directly of signals or if
2383144467Sharti	 * we're giving each job its own process group (since then it won't get
2384144467Sharti	 * signals from the terminal driver as we own the terminal)
2385144467Sharti	 */
2386137202Sharti#if defined(USE_PGRP)
2387144467Sharti	if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2388144467Sharti		sigaction(SIGTSTP, &sa, NULL);
2389144467Sharti	}
2390144467Sharti	if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2391144467Sharti		sigaction(SIGTTOU, &sa, NULL);
2392144467Sharti	}
2393144467Sharti	if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2394144467Sharti		sigaction(SIGTTIN, &sa, NULL);
2395144467Sharti	}
2396144467Sharti	if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2397144467Sharti		sigaction(SIGWINCH, &sa, NULL);
2398144467Sharti	}
23991590Srgrimes#endif
24008874Srgrimes
2401104475Sphk#ifdef USE_KQUEUE
2402144467Sharti	if ((kqfd = kqueue()) == -1) {
2403144467Sharti		Punt("kqueue: %s", strerror(errno));
2404144467Sharti	}
2405104475Sphk#endif
2406104475Sphk
2407144467Sharti	begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
24081590Srgrimes
2409144467Sharti	if (begin != NULL) {
2410144467Sharti		JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2411144467Sharti		while (nJobs) {
2412144467Sharti			Job_CatchOutput(0);
2413144467Sharti			Job_CatchChildren(!usePipes);
2414144467Sharti		}
24151590Srgrimes	}
2416144467Sharti	postCommands = Targ_FindNode(".END", TARG_CREATE);
24171590Srgrimes}
24181590Srgrimes
2419144467Sharti/**
2420144467Sharti * Job_Full
24211590Srgrimes *	See if the job table is full. It is considered full if it is OR
24221590Srgrimes *	if we are in the process of aborting OR if we have
24231590Srgrimes *	reached/exceeded our local quota. This prevents any more jobs
24241590Srgrimes *	from starting up.
24251590Srgrimes *
24261590Srgrimes * Results:
24271590Srgrimes *	TRUE if the job table is full, FALSE otherwise
24281590Srgrimes */
24291590SrgrimesBoolean
2430104696SjmallettJob_Full(void)
24311590Srgrimes{
2432144467Sharti	char c;
2433144467Sharti	int i;
2434137606Sphk
2435144467Sharti	if (aborting)
2436144467Sharti		return (aborting);
2437144467Sharti	if (fifoFd >= 0 && jobFull) {
2438144467Sharti		i = read(fifoFd, &c, 1);
2439144467Sharti		if (i > 0) {
2440144467Sharti			maxJobs++;
2441144467Sharti			jobFull = FALSE;
2442144467Sharti		}
2443137606Sphk	}
2444144467Sharti	return (jobFull);
24451590Srgrimes}
24461590Srgrimes
2447144467Sharti/**
2448144467Sharti * Job_Empty
24491590Srgrimes *	See if the job table is empty.  Because the local concurrency may
24501590Srgrimes *	be set to 0, it is possible for the job table to become empty,
24511590Srgrimes *	while the list of stoppedJobs remains non-empty. In such a case,
24521590Srgrimes *	we want to restart as many jobs as we can.
24531590Srgrimes *
24541590Srgrimes * Results:
24551590Srgrimes *	TRUE if it is. FALSE if it ain't.
24561590Srgrimes */
24571590SrgrimesBoolean
2458104696SjmallettJob_Empty(void)
24591590Srgrimes{
2460144467Sharti	if (nJobs == 0) {
2461144494Sharti		if (!TAILQ_EMPTY(&stoppedJobs) && !aborting) {
2462144467Sharti			/*
2463144467Sharti			 * The job table is obviously not full if it has no
2464144467Sharti			 * jobs in it...Try and restart the stopped jobs.
2465144467Sharti			 */
2466144467Sharti			jobFull = FALSE;
2467144467Sharti			JobRestartJobs();
2468144467Sharti			return (FALSE);
2469144467Sharti		} else {
2470144467Sharti			return (TRUE);
2471144467Sharti		}
24721590Srgrimes	} else {
2473144467Sharti		return (FALSE);
24741590Srgrimes	}
24751590Srgrimes}
24761590Srgrimes
2477144467Sharti/**
2478144467Sharti * JobInterrupt
24791590Srgrimes *	Handle the receipt of an interrupt.
24801590Srgrimes *
24811590Srgrimes * Side Effects:
24821590Srgrimes *	All children are killed. Another job will be started if the
24831590Srgrimes *	.INTERRUPT target was given.
24841590Srgrimes */
24851590Srgrimesstatic void
2486104696SjmallettJobInterrupt(int runINTERRUPT, int signo)
24871590Srgrimes{
2488144467Sharti	Job	*job;		/* job descriptor in that element */
2489144467Sharti	GNode	*interrupt;	/* the node describing the .INTERRUPT target */
24908874Srgrimes
2491144467Sharti	aborting = ABORT_INTERRUPT;
24921590Srgrimes
2493144494Sharti	TAILQ_FOREACH(job, &jobs, link) {
2494144467Sharti		if (!Targ_Precious(job->node)) {
2495144467Sharti			char *file = (job->node->path == NULL ?
2496144467Sharti			    job->node->name : job->node->path);
2497144467Sharti
2498144467Sharti			if (!noExecute && eunlink(file) != -1) {
2499144467Sharti				Error("*** %s removed", file);
2500144467Sharti			}
2501144467Sharti		}
2502144467Sharti		if (job->pid) {
2503144467Sharti			DEBUGF(JOB, ("JobInterrupt passing signal to child "
2504144665Sharti			    "%jd.\n", (intmax_t)job->pid));
2505144467Sharti			KILL(job->pid, signo);
2506144467Sharti		}
25071590Srgrimes	}
250818730Ssteve
2509144467Sharti	if (runINTERRUPT && !touchFlag) {
2510144467Sharti		/*
2511144467Sharti		 * clear the interrupted flag because we would get an
2512144467Sharti		 * infinite loop otherwise.
2513144467Sharti		 */
2514144467Sharti		interrupted = 0;
2515137605Sharti
2516144467Sharti		interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2517144467Sharti		if (interrupt != NULL) {
2518144467Sharti			ignoreErrors = FALSE;
25191590Srgrimes
2520144467Sharti			JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
2521144467Sharti			while (nJobs) {
2522144467Sharti				Job_CatchOutput(0);
2523144467Sharti				Job_CatchChildren(!usePipes);
2524144467Sharti			}
2525144467Sharti		}
25261590Srgrimes	}
2527151162Sscottl	if (fifoMaster)
2528151162Sscottl		unlink(fifoName);
25291590Srgrimes}
25301590Srgrimes
2531144467Sharti/**
2532144467Sharti * Job_Finish
25331590Srgrimes *	Do final processing such as the running of the commands
25348874Srgrimes *	attached to the .END target.
25351590Srgrimes *
25361590Srgrimes * Results:
25371590Srgrimes *	Number of errors reported.
25381590Srgrimes */
25391590Srgrimesint
2540104696SjmallettJob_Finish(void)
25411590Srgrimes{
2542138232Sharti
2543144467Sharti	if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
2544144467Sharti		if (errors) {
2545144467Sharti			Error("Errors reported so .END ignored");
2546144467Sharti		} else {
2547144467Sharti			JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
25481590Srgrimes
2549144467Sharti			while (nJobs) {
2550144467Sharti				Job_CatchOutput(0);
2551144467Sharti				Job_CatchChildren(!usePipes);
2552144467Sharti			}
2553144467Sharti		}
25541590Srgrimes	}
2555144467Sharti	if (fifoFd >= 0) {
2556144467Sharti		close(fifoFd);
2557144467Sharti		fifoFd = -1;
2558144467Sharti		if (fifoMaster)
2559144467Sharti			unlink(fifoName);
2560144467Sharti	}
2561144467Sharti	return (errors);
25621590Srgrimes}
25631590Srgrimes
2564144467Sharti/**
2565144467Sharti * Job_Wait
25661590Srgrimes *	Waits for all running jobs to finish and returns. Sets 'aborting'
25671590Srgrimes *	to ABORT_WAIT to prevent other jobs from starting.
25681590Srgrimes *
25691590Srgrimes * Side Effects:
25701590Srgrimes *	Currently running jobs finish.
25711590Srgrimes */
25721590Srgrimesvoid
2573104696SjmallettJob_Wait(void)
25741590Srgrimes{
2575138232Sharti
2576144467Sharti	aborting = ABORT_WAIT;
2577144467Sharti	while (nJobs != 0) {
2578144467Sharti		Job_CatchOutput(0);
2579144467Sharti		Job_CatchChildren(!usePipes);
2580144467Sharti	}
2581144467Sharti	aborting = 0;
25821590Srgrimes}
25831590Srgrimes
2584144467Sharti/**
2585144467Sharti * Job_AbortAll
25861590Srgrimes *	Abort all currently running jobs without handling output or anything.
25871590Srgrimes *	This function is to be called only in the event of a major
25881590Srgrimes *	error. Most definitely NOT to be called from JobInterrupt.
25891590Srgrimes *
25901590Srgrimes * Side Effects:
25911590Srgrimes *	All children are killed, not just the firstborn
25921590Srgrimes */
25931590Srgrimesvoid
2594104696SjmallettJob_AbortAll(void)
25951590Srgrimes{
2596144467Sharti	Job	*job;	/* the job descriptor in that element */
2597144467Sharti	int	foo;
25988874Srgrimes
2599144467Sharti	aborting = ABORT_ERROR;
26008874Srgrimes
2601144467Sharti	if (nJobs) {
2602144494Sharti		TAILQ_FOREACH(job, &jobs, link) {
2603144467Sharti			/*
2604144467Sharti			 * kill the child process with increasingly drastic
2605144467Sharti			 * signals to make darn sure it's dead.
2606144467Sharti			 */
2607144467Sharti			KILL(job->pid, SIGINT);
2608144467Sharti			KILL(job->pid, SIGKILL);
2609144467Sharti		}
26101590Srgrimes	}
26118874Srgrimes
2612144467Sharti	/*
2613144467Sharti	 * Catch as many children as want to report in at first, then give up
2614144467Sharti	 */
2615144467Sharti	while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2616144665Sharti		;
26171590Srgrimes}
261818730Ssteve
2619144467Sharti/**
2620144467Sharti * JobRestartJobs
262118730Ssteve *	Tries to restart stopped jobs if there are slots available.
262218730Ssteve *	Note that this tries to restart them regardless of pending errors.
262318730Ssteve *	It's not good to leave stopped jobs lying around!
262418730Ssteve *
262518730Ssteve * Side Effects:
262618730Ssteve *	Resumes(and possibly migrates) jobs.
262718730Ssteve */
262818730Sstevestatic void
2629104696SjmallettJobRestartJobs(void)
263018730Ssteve{
2631144494Sharti	Job *job;
2632144494Sharti
2633144494Sharti	while (!jobFull && (job = TAILQ_FIRST(&stoppedJobs)) != NULL) {
2634144467Sharti		DEBUGF(JOB, ("Job queue is not full. "
2635144467Sharti		    "Restarting a stopped job.\n"));
2636144494Sharti		TAILQ_REMOVE(&stoppedJobs, job, link);
2637144494Sharti		JobRestart(job);
2638144467Sharti	}
263918730Ssteve}
2640146054Sharti
2641146054Sharti/**
2642146054Sharti * Cmd_Exec
2643146054Sharti *	Execute the command in cmd, and return the output of that command
2644146054Sharti *	in a string.
2645146054Sharti *
2646146054Sharti * Results:
2647146054Sharti *	A string containing the output of the command, or the empty string
2648146054Sharti *	If error is not NULL, it contains the reason for the command failure
2649146129Sharti *	Any output sent to stderr in the child process is passed to stderr,
2650146129Sharti *	and not captured in the string.
2651146054Sharti *
2652146054Sharti * Side Effects:
2653146054Sharti *	The string must be freed by the caller.
2654146054Sharti */
2655146054ShartiBuffer *
2656146054ShartiCmd_Exec(const char *cmd, const char **error)
2657146054Sharti{
2658146054Sharti	int	fds[2];	/* Pipe streams */
2659146054Sharti	int	status;	/* command exit status */
2660146054Sharti	Buffer	*buf;	/* buffer to store the result */
2661146054Sharti	ssize_t	rcnt;
2662146129Sharti	ProcStuff	ps;
2663146054Sharti
2664146054Sharti	*error = NULL;
2665146054Sharti	buf = Buf_Init(0);
2666146054Sharti
2667146054Sharti	/*
2668146054Sharti	 * Open a pipe for fetching its output
2669146054Sharti	 */
2670146054Sharti	if (pipe(fds) == -1) {
2671146054Sharti		*error = "Couldn't create pipe for \"%s\"";
2672146054Sharti		return (buf);
2673146054Sharti	}
2674146054Sharti
2675146129Sharti	/* Set close-on-exec on read side of pipe. */
2676146129Sharti	fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC);
2677146129Sharti
2678146129Sharti	ps.in = STDIN_FILENO;
2679146129Sharti	ps.out = fds[1];
2680146129Sharti	ps.err = STDERR_FILENO;
2681146129Sharti
2682146129Sharti	ps.merge_errors = 0;
2683146129Sharti	ps.pgroup = 0;
2684146129Sharti	ps.searchpath = 0;
2685146129Sharti
2686146129Sharti	/* Set up arguments for shell */
2687146129Sharti	ps.argv = emalloc(4 * sizeof(char *));
2688146557Sharti	ps.argv[0] = strdup(commandShell->name);
2689146129Sharti	ps.argv[1] = strdup("-c");
2690146129Sharti	ps.argv[2] = strdup(cmd);
2691146129Sharti	ps.argv[3] = NULL;
2692146156Sharti	ps.argv_free = 1;
2693146129Sharti
2694146054Sharti	/*
2695146129Sharti	 * Fork.  Warning since we are doing vfork() instead of fork(),
2696146129Sharti	 * do not allocate memory in the child process!
2697146054Sharti	 */
2698146130Sharti	if ((ps.child_pid = vfork()) == -1) {
2699146058Sharti		*error = "Couldn't exec \"%s\"";
2700146058Sharti		return (buf);
2701146058Sharti
2702146130Sharti	} else if (ps.child_pid == 0) {
2703146129Sharti  		/*
2704146129Sharti		 * Child
2705146129Sharti  		 */
2706146574Sharti		Proc_Exec(&ps);
2707146129Sharti		/* NOTREACHED */
2708146129Sharti	}
2709146054Sharti
2710146129Sharti	free(ps.argv[2]);
2711146129Sharti	free(ps.argv[1]);
2712146129Sharti	free(ps.argv[0]);
2713146129Sharti	free(ps.argv);
2714146054Sharti
2715146129Sharti	close(fds[1]); /* No need for the writing half of the pipe. */
2716146054Sharti
2717146058Sharti	do {
2718146058Sharti		char	result[BUFSIZ];
2719146054Sharti
2720146058Sharti		rcnt = read(fds[0], result, sizeof(result));
2721146058Sharti		if (rcnt != -1)
2722146058Sharti			Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
2723146058Sharti	} while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
2724146054Sharti
2725146058Sharti	if (rcnt == -1)
2726146058Sharti		*error = "Error reading shell's output for \"%s\"";
2727146054Sharti
2728146058Sharti	/*
2729146058Sharti	 * Close the input side of the pipe.
2730146058Sharti	 */
2731146058Sharti	close(fds[0]);
2732146054Sharti
2733146130Sharti	status = ProcWait(&ps);
2734146054Sharti
2735146058Sharti	if (status)
2736146058Sharti		*error = "\"%s\" returned non-zero status";
2737146054Sharti
2738146058Sharti	Buf_StripNewlines(buf);
2739146054Sharti
2740146054Sharti	return (buf);
2741146054Sharti}
2742146054Sharti
2743146056Sharti
2744146056Sharti/*
2745146056Sharti * Interrupt handler - set flag and defer handling to the main code
2746146056Sharti */
2747146056Shartistatic void
2748146056ShartiCompatCatchSig(int signo)
2749146056Sharti{
2750146056Sharti
2751146056Sharti	interrupted = signo;
2752146056Sharti}
2753146056Sharti
2754146056Sharti/*-
2755146056Sharti *-----------------------------------------------------------------------
2756146056Sharti * CompatInterrupt --
2757146056Sharti *	Interrupt the creation of the current target and remove it if
2758146056Sharti *	it ain't precious.
2759146056Sharti *
2760146056Sharti * Results:
2761146056Sharti *	None.
2762146056Sharti *
2763146056Sharti * Side Effects:
2764146056Sharti *	The target is removed and the process exits. If .INTERRUPT exists,
2765146056Sharti *	its commands are run first WITH INTERRUPTS IGNORED..
2766146056Sharti *
2767146056Sharti *-----------------------------------------------------------------------
2768146056Sharti */
2769146056Shartistatic void
2770146056ShartiCompatInterrupt(int signo)
2771146056Sharti{
2772146056Sharti	GNode		*gn;
2773146056Sharti	sigset_t	nmask, omask;
2774146056Sharti	LstNode		*ln;
2775146056Sharti
2776146056Sharti	sigemptyset(&nmask);
2777146056Sharti	sigaddset(&nmask, SIGINT);
2778146056Sharti	sigaddset(&nmask, SIGTERM);
2779146056Sharti	sigaddset(&nmask, SIGHUP);
2780146056Sharti	sigaddset(&nmask, SIGQUIT);
2781146056Sharti	sigprocmask(SIG_SETMASK, &nmask, &omask);
2782146056Sharti
2783146056Sharti	/* prevent recursion in evaluation of .INTERRUPT */
2784146056Sharti	interrupted = 0;
2785146056Sharti
2786146056Sharti	if (curTarg != NULL && !Targ_Precious(curTarg)) {
2787146581Sharti		const char	*file = Var_Value(TARGET, curTarg);
2788146056Sharti
2789146056Sharti		if (!noExecute && eunlink(file) != -1) {
2790146056Sharti			printf("*** %s removed\n", file);
2791146056Sharti		}
2792146056Sharti	}
2793146056Sharti
2794146056Sharti	/*
2795146056Sharti	 * Run .INTERRUPT only if hit with interrupt signal
2796146056Sharti	 */
2797146056Sharti	if (signo == SIGINT) {
2798146056Sharti		gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2799146056Sharti		if (gn != NULL) {
2800146056Sharti			LST_FOREACH(ln, &gn->commands) {
2801146056Sharti				if (Compat_RunCommand(Lst_Datum(ln), gn))
2802146056Sharti					break;
2803146056Sharti			}
2804146056Sharti		}
2805146056Sharti	}
2806146056Sharti
2807146056Sharti	sigprocmask(SIG_SETMASK, &omask, NULL);
2808146056Sharti
2809146056Sharti	if (signo == SIGQUIT)
2810146056Sharti		exit(signo);
2811146056Sharti	signal(signo, SIG_DFL);
2812146056Sharti	kill(getpid(), signo);
2813146056Sharti}
2814146056Sharti
2815146129Sharti/**
2816146129Sharti * shellneed
2817146056Sharti *
2818146056Sharti * Results:
2819146129Sharti *	Returns NULL if a specified line must be executed by the shell,
2820146129Sharti *	and an argument vector if it can be run via execvp().
2821146056Sharti *
2822146056Sharti * Side Effects:
2823146056Sharti *	Uses brk_string so destroys the contents of argv.
2824146056Sharti */
2825146129Shartistatic char **
2826146345Shartishellneed(ArgArray *aa, char *cmd)
2827146056Sharti{
2828146557Sharti	char	**p;
2829146557Sharti	int	ret;
2830146056Sharti
2831146557Sharti	if (commandShell->meta == NULL || commandShell->builtins.argc <= 1)
2832146557Sharti		/* use shell */
2833146129Sharti		return (NULL);
2834146129Sharti
2835146557Sharti	if (strpbrk(cmd, commandShell->meta) != NULL)
2836146557Sharti		return (NULL);
2837146557Sharti
2838146147Sharti	/*
2839146147Sharti	 * Break the command into words to form an argument
2840146345Sharti	 * vector we can execute.
2841146147Sharti	 */
2842146345Sharti	brk_string(aa, cmd, TRUE);
2843146557Sharti	for (p = commandShell->builtins.argv + 1; *p != 0; p++) {
2844146557Sharti		if ((ret = strcmp(aa->argv[1], *p)) == 0) {
2845146557Sharti			/* found - use shell */
2846146345Sharti			ArgArray_Done(aa);
2847146129Sharti			return (NULL);
2848146345Sharti		}
2849146557Sharti		if (ret < 0) {
2850146557Sharti			/* not found */
2851146557Sharti			break;
2852146557Sharti		}
2853146345Sharti	}
2854146345Sharti	return (aa->argv + 1);
2855146056Sharti}
2856146056Sharti
2857146557Sharti/**
2858146557Sharti * Execute the next command for a target. If the command returns an
2859146557Sharti * error, the node's made field is set to ERROR and creation stops.
2860146557Sharti * The node from which the command came is also given. This is used
2861146557Sharti * to execute the commands in compat mode and when executing commands
2862146557Sharti * with the '+' flag in non-compat mode. In these modes each command
2863146557Sharti * line should be executed by its own shell. We do some optimisation here:
2864146557Sharti * if the shell description defines both a string of meta characters and
2865146557Sharti * a list of builtins and the command line neither contains a meta character
2866146557Sharti * nor starts with one of the builtins then we execute the command directly
2867146557Sharti * without invoking a shell.
2868146056Sharti *
2869146056Sharti * Results:
2870146056Sharti *	0 if the command succeeded, 1 if an error occurred.
2871146056Sharti *
2872146056Sharti * Side Effects:
2873146056Sharti *	The node's 'made' field may be set to ERROR.
2874146056Sharti */
2875146142Shartistatic int
2876146056ShartiCompat_RunCommand(char *cmd, GNode *gn)
2877146056Sharti{
2878146345Sharti	ArgArray	aa;
2879146345Sharti	char		*cmdStart;	/* Start of expanded command */
2880146345Sharti	Boolean		silent;		/* Don't print command */
2881146345Sharti	Boolean		doit;		/* Execute even in -n */
2882146345Sharti	Boolean		errCheck;	/* Check errors */
2883146345Sharti	int		reason;		/* Reason for child's death */
2884146345Sharti	int		status;		/* Description of child's death */
2885146345Sharti	LstNode		*cmdNode;	/* Node where current cmd is located */
2886146345Sharti	char		**av;		/* Argument vector for thing to exec */
2887146129Sharti	ProcStuff	ps;
2888146056Sharti
2889146056Sharti	silent = gn->type & OP_SILENT;
2890146056Sharti	errCheck = !(gn->type & OP_IGNORE);
2891146056Sharti	doit = FALSE;
2892146056Sharti
2893146056Sharti	cmdNode = Lst_Member(&gn->commands, cmd);
2894146056Sharti	cmdStart = Buf_Peel(Var_Subst(cmd, gn, FALSE));
2895146056Sharti
2896146056Sharti	/*
2897146056Sharti	 * brk_string will return an argv with a NULL in av[0], thus causing
2898146129Sharti	 * execvp() to choke and die horribly. Besides, how can we execute a
2899146129Sharti	 * null command? In any case, we warn the user that the command
2900146129Sharti	 * expanded to nothing (is this the right thing to do?).
2901146056Sharti	 */
2902146056Sharti	if (*cmdStart == '\0') {
2903146056Sharti		free(cmdStart);
2904146056Sharti		Error("%s expands to empty string", cmd);
2905146056Sharti		return (0);
2906146056Sharti	} else {
2907146056Sharti		cmd = cmdStart;
2908146056Sharti	}
2909146056Sharti	Lst_Replace(cmdNode, cmdStart);
2910146056Sharti
2911146056Sharti	if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
2912146056Sharti		Lst_AtEnd(&ENDNode->commands, cmdStart);
2913146056Sharti		return (0);
2914146056Sharti	} else if (strcmp(cmdStart, "...") == 0) {
2915146056Sharti		gn->type |= OP_SAVE_CMDS;
2916146056Sharti		return (0);
2917146056Sharti	}
2918146056Sharti
2919146056Sharti	while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
2920146056Sharti		switch (*cmd) {
2921146056Sharti
2922146056Sharti		  case '@':
2923146056Sharti			silent = DEBUG(LOUD) ? FALSE : TRUE;
2924146056Sharti			break;
2925146056Sharti
2926146056Sharti		  case '-':
2927146056Sharti			errCheck = FALSE;
2928146056Sharti			break;
2929146056Sharti
2930146129Sharti		  case '+':
2931146056Sharti			doit = TRUE;
2932146056Sharti			break;
2933146056Sharti		}
2934146056Sharti		cmd++;
2935146056Sharti	}
2936146056Sharti
2937146056Sharti	while (isspace((unsigned char)*cmd))
2938146056Sharti		cmd++;
2939146056Sharti
2940146056Sharti	/*
2941146056Sharti	 * Print the command before echoing if we're not supposed to be quiet
2942146056Sharti	 * for this one. We also print the command if -n given, but not if '+'.
2943146056Sharti	 */
2944146056Sharti	if (!silent || (noExecute && !doit)) {
2945146056Sharti		printf("%s\n", cmd);
2946146056Sharti		fflush(stdout);
2947146056Sharti	}
2948146056Sharti
2949146056Sharti	/*
2950146056Sharti	 * If we're not supposed to execute any commands, this is as far as
2951146056Sharti	 * we go...
2952146056Sharti	 */
2953146056Sharti	if (!doit && noExecute) {
2954146056Sharti		return (0);
2955146056Sharti	}
2956146056Sharti
2957146129Sharti	ps.in = STDIN_FILENO;
2958146129Sharti	ps.out = STDOUT_FILENO;
2959146129Sharti	ps.err = STDERR_FILENO;
2960146056Sharti
2961146129Sharti	ps.merge_errors = 0;
2962146129Sharti	ps.pgroup = 0;
2963146129Sharti	ps.searchpath = 1;
2964146056Sharti
2965146345Sharti	if ((av = shellneed(&aa, cmd)) == NULL) {
2966146056Sharti		/*
2967146129Sharti		 * Shell meta character or shell builtin found - pass
2968146129Sharti		 * command to shell. We give the shell the -e flag as
2969146129Sharti		 * well as -c if it is supposed to exit when it hits an error.
2970146056Sharti		 */
2971146129Sharti		ps.argv = emalloc(4 * sizeof(char *));
2972146557Sharti		ps.argv[0] = strdup(commandShell->path);
2973146129Sharti		ps.argv[1] = strdup(errCheck ? "-ec" : "-c");
2974146129Sharti		ps.argv[2] = strdup(cmd);
2975146129Sharti		ps.argv[3] = NULL;
2976146156Sharti		ps.argv_free = 1;
2977146056Sharti	} else {
2978146129Sharti		ps.argv = av;
2979146156Sharti		ps.argv_free = 0;
2980146056Sharti	}
2981146156Sharti	ps.errCheck = errCheck;
2982146056Sharti
2983146056Sharti	/*
2984146129Sharti	 * Warning since we are doing vfork() instead of fork(),
2985146129Sharti	 * do not allocate memory in the child process!
2986146056Sharti	 */
2987146130Sharti	if ((ps.child_pid = vfork()) == -1) {
2988146056Sharti		Fatal("Could not fork");
2989146058Sharti
2990146130Sharti	} else if (ps.child_pid == 0) {
2991146129Sharti		/*
2992146129Sharti		 * Child
2993146129Sharti		 */
2994146574Sharti		Proc_Exec(&ps);
2995146129Sharti  		/* NOTREACHED */
2996146129Sharti
2997146131Sharti	} else {
2998146156Sharti		if (ps.argv_free) {
2999146131Sharti			free(ps.argv[2]);
3000146131Sharti			free(ps.argv[1]);
3001146131Sharti			free(ps.argv[0]);
3002146131Sharti			free(ps.argv);
3003146345Sharti		} else {
3004146345Sharti			ArgArray_Done(&aa);
3005146131Sharti		}
3006146129Sharti
3007146131Sharti		/*
3008146131Sharti		 * we need to print out the command associated with this
3009146131Sharti		 * Gnode in Targ_PrintCmd from Targ_PrintGraph when debugging
3010146131Sharti		 * at level g2, in main(), Fatal() and DieHorribly(),
3011146131Sharti		 * therefore do not free it when debugging.
3012146131Sharti		 */
3013146131Sharti		if (!DEBUG(GRAPH2)) {
3014146131Sharti			free(cmdStart);
3015146131Sharti		}
3016146129Sharti
3017146131Sharti		/*
3018146131Sharti		 * The child is off and running. Now all we can do is wait...
3019146131Sharti		 */
3020146131Sharti		reason = ProcWait(&ps);
3021146132Sharti
3022146056Sharti		if (interrupted)
3023146056Sharti			CompatInterrupt(interrupted);
3024146131Sharti
3025146132Sharti		/*
3026146132Sharti		 * Decode and report the reason child exited, then
3027146132Sharti		 * indicate how we handled it.
3028146132Sharti		 */
3029146131Sharti		if (WIFEXITED(reason)) {
3030146131Sharti			status = WEXITSTATUS(reason);
3031146131Sharti			if (status == 0) {
3032146131Sharti				return (0);
3033146131Sharti  			} else {
3034146131Sharti				printf("*** Error code %d", status);
3035146131Sharti  			}
3036146131Sharti		} else if (WIFSTOPPED(reason)) {
3037146131Sharti			status = WSTOPSIG(reason);
3038146131Sharti		} else {
3039146131Sharti			status = WTERMSIG(reason);
3040146131Sharti			printf("*** Signal %d", status);
3041146131Sharti  		}
3042146131Sharti
3043146156Sharti		if (ps.errCheck) {
3044146131Sharti			gn->made = ERROR;
3045146131Sharti			if (keepgoing) {
3046146131Sharti				/*
3047146131Sharti				 * Abort the current
3048146131Sharti				 * target, but let
3049146131Sharti				 * others continue.
3050146131Sharti				 */
3051146131Sharti				printf(" (continuing)\n");
3052146056Sharti			}
3053146131Sharti			return (status);
3054146056Sharti		} else {
3055146131Sharti			/*
3056146131Sharti			 * Continue executing
3057146131Sharti			 * commands for this target.
3058146131Sharti			 * If we return 0, this will
3059146131Sharti			 * happen...
3060146131Sharti			 */
3061146131Sharti			printf(" (ignored)\n");
3062146131Sharti			return (0);
3063146056Sharti		}
3064146056Sharti	}
3065146056Sharti}
3066146056Sharti
3067146056Sharti/*-
3068146056Sharti *-----------------------------------------------------------------------
3069167330Sfjoe * Compat_Make --
3070146056Sharti *	Make a target, given the parent, to abort if necessary.
3071146056Sharti *
3072146056Sharti * Side Effects:
3073146056Sharti *	If an error is detected and not being ignored, the process exits.
3074146056Sharti *
3075146056Sharti *-----------------------------------------------------------------------
3076146056Sharti */
3077167330Sfjoeint
3078167330SfjoeCompat_Make(GNode *gn, GNode *pgn)
3079146056Sharti{
3080146056Sharti	LstNode	*ln;
3081146056Sharti
3082146056Sharti	if (gn->type & OP_USE) {
3083146056Sharti		Make_HandleUse(gn, pgn);
3084146056Sharti
3085146056Sharti	} else if (gn->made == UNMADE) {
3086146056Sharti		/*
3087146056Sharti		 * First mark ourselves to be made, then apply whatever
3088146056Sharti		 * transformations the suffix module thinks are necessary.
3089146056Sharti		 * Once that's done, we can descend and make all our children.
3090146056Sharti		 * If any of them has an error but the -k flag was given, our
3091146056Sharti		 * 'make' field will be set FALSE again. This is our signal to
3092146056Sharti		 * not attempt to do anything but abort our parent as well.
3093146056Sharti		 */
3094146056Sharti		gn->make = TRUE;
3095146056Sharti		gn->made = BEINGMADE;
3096146056Sharti		Suff_FindDeps(gn);
3097146056Sharti		LST_FOREACH(ln, &gn->children)
3098167330Sfjoe			Compat_Make(Lst_Datum(ln), gn);
3099146056Sharti		if (!gn->make) {
3100146056Sharti			gn->made = ABORTED;
3101146056Sharti			pgn->make = FALSE;
3102146056Sharti			return (0);
3103146056Sharti		}
3104146056Sharti
3105146056Sharti		if (Lst_Member(&gn->iParents, pgn) != NULL) {
3106146580Sharti			Var_Set(IMPSRC, Var_Value(TARGET, gn), pgn);
3107146056Sharti		}
3108146056Sharti
3109146056Sharti		/*
3110146056Sharti		 * All the children were made ok. Now cmtime contains the
3111146056Sharti		 * modification time of the newest child, we need to find out
3112146056Sharti		 * if we exist and when we were modified last. The criteria for
3113146056Sharti		 * datedness are defined by the Make_OODate function.
3114146056Sharti		 */
3115146056Sharti		DEBUGF(MAKE, ("Examining %s...", gn->name));
3116146056Sharti		if (!Make_OODate(gn)) {
3117146056Sharti			gn->made = UPTODATE;
3118146056Sharti			DEBUGF(MAKE, ("up-to-date.\n"));
3119146056Sharti			return (0);
3120146056Sharti		} else {
3121146056Sharti			DEBUGF(MAKE, ("out-of-date.\n"));
3122146056Sharti		}
3123146056Sharti
3124146056Sharti		/*
3125146056Sharti		 * If the user is just seeing if something is out-of-date,
3126146056Sharti		 * exit now to tell him/her "yes".
3127146056Sharti		 */
3128146056Sharti		if (queryFlag) {
3129146056Sharti			exit(1);
3130146056Sharti		}
3131146056Sharti
3132146056Sharti		/*
3133146056Sharti		 * We need to be re-made. We also have to make sure we've got
3134146056Sharti		 * a $? variable. To be nice, we also define the $> variable
3135146056Sharti		 * using Make_DoAllVar().
3136146056Sharti		 */
3137146056Sharti		Make_DoAllVar(gn);
3138146056Sharti
3139146056Sharti		/*
3140146056Sharti		 * Alter our type to tell if errors should be ignored or things
3141146056Sharti		 * should not be printed so Compat_RunCommand knows what to do.
3142146056Sharti		 */
3143146056Sharti		if (Targ_Ignore(gn)) {
3144146056Sharti			gn->type |= OP_IGNORE;
3145146056Sharti		}
3146146056Sharti		if (Targ_Silent(gn)) {
3147146056Sharti			gn->type |= OP_SILENT;
3148146056Sharti		}
3149146056Sharti
3150146056Sharti		if (Job_CheckCommands(gn, Fatal)) {
3151146056Sharti			/*
3152146056Sharti			 * Our commands are ok, but we still have to worry
3153146056Sharti			 * about the -t flag...
3154146056Sharti			 */
3155146056Sharti			if (!touchFlag) {
3156146056Sharti				curTarg = gn;
3157146056Sharti				LST_FOREACH(ln, &gn->commands) {
3158146056Sharti					if (Compat_RunCommand(Lst_Datum(ln),
3159146056Sharti					    gn))
3160146056Sharti						break;
3161146056Sharti				}
3162146056Sharti				curTarg = NULL;
3163146056Sharti			} else {
3164146056Sharti				Job_Touch(gn, gn->type & OP_SILENT);
3165146056Sharti			}
3166146056Sharti		} else {
3167146056Sharti			gn->made = ERROR;
3168146056Sharti		}
3169146056Sharti
3170146056Sharti		if (gn->made != ERROR) {
3171146056Sharti			/*
3172146056Sharti			 * If the node was made successfully, mark it so, update
3173146056Sharti			 * its modification time and timestamp all its parents.
3174146056Sharti			 * Note that for .ZEROTIME targets, the timestamping
3175146056Sharti			 * isn't done. This is to keep its state from affecting
3176146056Sharti			 * that of its parent.
3177146056Sharti			 */
3178146056Sharti			gn->made = MADE;
3179146056Sharti#ifndef RECHECK
3180146056Sharti			/*
3181146056Sharti			 * We can't re-stat the thing, but we can at least take
3182146056Sharti			 * care of rules where a target depends on a source that
3183146056Sharti			 * actually creates the target, but only if it has
3184146056Sharti			 * changed, e.g.
3185146056Sharti			 *
3186146056Sharti			 * parse.h : parse.o
3187146056Sharti			 *
3188146056Sharti			 * parse.o : parse.y
3189146061Sharti			 *	yacc -d parse.y
3190146061Sharti			 *	cc -c y.tab.c
3191146061Sharti			 *	mv y.tab.o parse.o
3192146061Sharti			 *	cmp -s y.tab.h parse.h || mv y.tab.h parse.h
3193146056Sharti			 *
3194146056Sharti			 * In this case, if the definitions produced by yacc
3195146056Sharti			 * haven't changed from before, parse.h won't have been
3196146056Sharti			 * updated and gn->mtime will reflect the current
3197146056Sharti			 * modification time for parse.h. This is something of a
3198146056Sharti			 * kludge, I admit, but it's a useful one..
3199146056Sharti			 *
3200146056Sharti			 * XXX: People like to use a rule like
3201146056Sharti			 *
3202146056Sharti			 * FRC:
3203146056Sharti			 *
3204146056Sharti			 * To force things that depend on FRC to be made, so we
3205146056Sharti			 * have to check for gn->children being empty as well...
3206146056Sharti			 */
3207146056Sharti			if (!Lst_IsEmpty(&gn->commands) ||
3208146056Sharti			    Lst_IsEmpty(&gn->children)) {
3209146056Sharti				gn->mtime = now;
3210146056Sharti			}
3211146056Sharti#else
3212146056Sharti			/*
3213146056Sharti			 * This is what Make does and it's actually a good
3214146056Sharti			 * thing, as it allows rules like
3215146056Sharti			 *
3216146056Sharti			 *	cmp -s y.tab.h parse.h || cp y.tab.h parse.h
3217146056Sharti			 *
3218146056Sharti			 * to function as intended. Unfortunately, thanks to
3219146056Sharti			 * the stateless nature of NFS (and the speed of this
3220146056Sharti			 * program), there are times when the modification time
3221146056Sharti			 * of a file created on a remote machine will not be
3222146056Sharti			 * modified before the stat() implied by the Dir_MTime
3223146056Sharti			 * occurs, thus leading us to believe that the file
3224146056Sharti			 * is unchanged, wreaking havoc with files that depend
3225146056Sharti			 * on this one.
3226146056Sharti			 *
3227146056Sharti			 * I have decided it is better to make too much than to
3228146056Sharti			 * make too little, so this stuff is commented out
3229146056Sharti			 * unless you're sure it's ok.
3230146056Sharti			 * -- ardeb 1/12/88
3231146056Sharti			 */
3232146056Sharti			if (noExecute || Dir_MTime(gn) == 0) {
3233146056Sharti				gn->mtime = now;
3234146056Sharti			}
3235146056Sharti			if (gn->cmtime > gn->mtime)
3236146056Sharti				gn->mtime = gn->cmtime;
3237146056Sharti			DEBUGF(MAKE, ("update time: %s\n",
3238146056Sharti			    Targ_FmtTime(gn->mtime)));
3239146056Sharti#endif
3240146056Sharti			if (!(gn->type & OP_EXEC)) {
3241146056Sharti				pgn->childMade = TRUE;
3242146056Sharti				Make_TimeStamp(pgn, gn);
3243146056Sharti			}
3244146056Sharti
3245146056Sharti		} else if (keepgoing) {
3246146056Sharti			pgn->make = FALSE;
3247146056Sharti
3248146056Sharti		} else {
3249146580Sharti			printf("\n\nStop in %s.\n", Var_Value(".CURDIR", gn));
3250146056Sharti			exit(1);
3251146056Sharti		}
3252146056Sharti	} else if (gn->made == ERROR) {
3253146056Sharti		/*
3254146056Sharti		 * Already had an error when making this beastie. Tell the
3255146056Sharti		 * parent to abort.
3256146056Sharti		 */
3257146056Sharti		pgn->make = FALSE;
3258146056Sharti	} else {
3259146056Sharti		if (Lst_Member(&gn->iParents, pgn) != NULL) {
3260146580Sharti			Var_Set(IMPSRC, Var_Value(TARGET, gn), pgn);
3261146056Sharti		}
3262146056Sharti		switch(gn->made) {
3263146056Sharti		  case BEINGMADE:
3264146056Sharti			Error("Graph cycles through %s\n", gn->name);
3265146056Sharti			gn->made = ERROR;
3266146056Sharti			pgn->make = FALSE;
3267146056Sharti			break;
3268146056Sharti		  case MADE:
3269146056Sharti			if ((gn->type & OP_EXEC) == 0) {
3270146056Sharti			    pgn->childMade = TRUE;
3271146056Sharti			    Make_TimeStamp(pgn, gn);
3272146056Sharti			}
3273146056Sharti			break;
3274146056Sharti		  case UPTODATE:
3275146056Sharti			if ((gn->type & OP_EXEC) == 0) {
3276146056Sharti			    Make_TimeStamp(pgn, gn);
3277146056Sharti			}
3278146056Sharti			break;
3279146056Sharti		  default:
3280146056Sharti			break;
3281146056Sharti		}
3282146056Sharti	}
3283146056Sharti
3284146056Sharti	return (0);
3285146056Sharti}
3286146056Sharti
3287146056Sharti/*-
3288167330Sfjoe * Install signal handlers for Compat_Run
3289167330Sfjoe */
3290167330Sfjoevoid
3291167330SfjoeCompat_InstallSignalHandlers(void)
3292167330Sfjoe{
3293167330Sfjoe
3294167330Sfjoe	if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
3295167330Sfjoe		signal(SIGINT, CompatCatchSig);
3296167330Sfjoe	}
3297167330Sfjoe	if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
3298167330Sfjoe		signal(SIGTERM, CompatCatchSig);
3299167330Sfjoe	}
3300167330Sfjoe	if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
3301167330Sfjoe		signal(SIGHUP, CompatCatchSig);
3302167330Sfjoe	}
3303167330Sfjoe	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
3304167330Sfjoe		signal(SIGQUIT, CompatCatchSig);
3305167330Sfjoe	}
3306167330Sfjoe}
3307167330Sfjoe
3308167330Sfjoe/*-
3309146056Sharti *-----------------------------------------------------------------------
3310146056Sharti * Compat_Run --
3311146056Sharti *	Start making again, given a list of target nodes.
3312146056Sharti *
3313146056Sharti * Results:
3314146056Sharti *	None.
3315146056Sharti *
3316146056Sharti * Side Effects:
3317146056Sharti *	Guess what?
3318146056Sharti *
3319146056Sharti *-----------------------------------------------------------------------
3320146056Sharti */
3321146056Shartivoid
3322146056ShartiCompat_Run(Lst *targs)
3323146056Sharti{
3324146056Sharti	GNode	*gn = NULL;	/* Current root target */
3325146056Sharti	int	error_cnt;		/* Number of targets not remade due to errors */
3326146056Sharti	LstNode	*ln;
3327146056Sharti
3328167330Sfjoe	Compat_InstallSignalHandlers();
3329146056Sharti	ENDNode = Targ_FindNode(".END", TARG_CREATE);
3330146056Sharti	/*
3331146056Sharti	 * If the user has defined a .BEGIN target, execute the commands
3332146056Sharti	 * attached to it.
3333146056Sharti	*/
3334146056Sharti	if (!queryFlag) {
3335146056Sharti		gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
3336146056Sharti		if (gn != NULL) {
3337146056Sharti			LST_FOREACH(ln, &gn->commands) {
3338146056Sharti				if (Compat_RunCommand(Lst_Datum(ln), gn))
3339146056Sharti					break;
3340146056Sharti			}
3341146056Sharti			if (gn->made == ERROR) {
3342146056Sharti				printf("\n\nStop.\n");
3343146056Sharti				exit(1);
3344146056Sharti			}
3345146056Sharti		}
3346146056Sharti	}
3347146056Sharti
3348146056Sharti	/*
3349167330Sfjoe	 * For each entry in the list of targets to create, call Compat_Make on
3350167330Sfjoe	 * it to create the thing. Compat_Make will leave the 'made' field of gn
3351146056Sharti	 * in one of several states:
3352146056Sharti	 *	UPTODATE  gn was already up-to-date
3353146056Sharti	 *	MADE	  gn was recreated successfully
3354146056Sharti	 *	ERROR	  An error occurred while gn was being created
3355146056Sharti	 *	ABORTED	  gn was not remade because one of its inferiors
3356146056Sharti	 *		  could not be made due to errors.
3357146056Sharti	 */
3358146056Sharti	error_cnt = 0;
3359146056Sharti	while (!Lst_IsEmpty(targs)) {
3360146056Sharti		gn = Lst_DeQueue(targs);
3361167330Sfjoe		Compat_Make(gn, gn);
3362146056Sharti
3363146056Sharti		if (gn->made == UPTODATE) {
3364146056Sharti			printf("`%s' is up to date.\n", gn->name);
3365146056Sharti		} else if (gn->made == ABORTED) {
3366146056Sharti			printf("`%s' not remade because of errors.\n",
3367146056Sharti			    gn->name);
3368146056Sharti			error_cnt += 1;
3369146056Sharti		}
3370146056Sharti	}
3371146056Sharti
3372146056Sharti	/*
3373146056Sharti	 * If the user has defined a .END target, run its commands.
3374146056Sharti	 */
3375146056Sharti	if (error_cnt == 0) {
3376146056Sharti		LST_FOREACH(ln, &ENDNode->commands) {
3377148151Sharti			if (Compat_RunCommand(Lst_Datum(ln), ENDNode))
3378146056Sharti				break;
3379146056Sharti		}
3380146056Sharti	}
3381146056Sharti}
3382146155Sharti
3383