job.c revision 237578
1237578Sobrien/*	$NetBSD: job.c,v 1.162 2012/06/12 19:21:50 joerg Exp $	*/
2236769Sobrien
3236769Sobrien/*
4236769Sobrien * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5236769Sobrien * All rights reserved.
6236769Sobrien *
7236769Sobrien * This code is derived from software contributed to Berkeley by
8236769Sobrien * Adam de Boor.
9236769Sobrien *
10236769Sobrien * Redistribution and use in source and binary forms, with or without
11236769Sobrien * modification, are permitted provided that the following conditions
12236769Sobrien * are met:
13236769Sobrien * 1. Redistributions of source code must retain the above copyright
14236769Sobrien *    notice, this list of conditions and the following disclaimer.
15236769Sobrien * 2. Redistributions in binary form must reproduce the above copyright
16236769Sobrien *    notice, this list of conditions and the following disclaimer in the
17236769Sobrien *    documentation and/or other materials provided with the distribution.
18236769Sobrien * 3. Neither the name of the University nor the names of its contributors
19236769Sobrien *    may be used to endorse or promote products derived from this software
20236769Sobrien *    without specific prior written permission.
21236769Sobrien *
22236769Sobrien * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23236769Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24236769Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25236769Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26236769Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27236769Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28236769Sobrien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29236769Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30236769Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31236769Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32236769Sobrien * SUCH DAMAGE.
33236769Sobrien */
34236769Sobrien
35236769Sobrien/*
36236769Sobrien * Copyright (c) 1988, 1989 by Adam de Boor
37236769Sobrien * Copyright (c) 1989 by Berkeley Softworks
38236769Sobrien * All rights reserved.
39236769Sobrien *
40236769Sobrien * This code is derived from software contributed to Berkeley by
41236769Sobrien * Adam de Boor.
42236769Sobrien *
43236769Sobrien * Redistribution and use in source and binary forms, with or without
44236769Sobrien * modification, are permitted provided that the following conditions
45236769Sobrien * are met:
46236769Sobrien * 1. Redistributions of source code must retain the above copyright
47236769Sobrien *    notice, this list of conditions and the following disclaimer.
48236769Sobrien * 2. Redistributions in binary form must reproduce the above copyright
49236769Sobrien *    notice, this list of conditions and the following disclaimer in the
50236769Sobrien *    documentation and/or other materials provided with the distribution.
51236769Sobrien * 3. All advertising materials mentioning features or use of this software
52236769Sobrien *    must display the following acknowledgement:
53236769Sobrien *	This product includes software developed by the University of
54236769Sobrien *	California, Berkeley and its contributors.
55236769Sobrien * 4. Neither the name of the University nor the names of its contributors
56236769Sobrien *    may be used to endorse or promote products derived from this software
57236769Sobrien *    without specific prior written permission.
58236769Sobrien *
59236769Sobrien * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60236769Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61236769Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62236769Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63236769Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64236769Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65236769Sobrien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66236769Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67236769Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68236769Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69236769Sobrien * SUCH DAMAGE.
70236769Sobrien */
71236769Sobrien
72236769Sobrien#ifndef MAKE_NATIVE
73237578Sobrienstatic char rcsid[] = "$NetBSD: job.c,v 1.162 2012/06/12 19:21:50 joerg Exp $";
74236769Sobrien#else
75236769Sobrien#include <sys/cdefs.h>
76236769Sobrien#ifndef lint
77236769Sobrien#if 0
78236769Sobrienstatic char sccsid[] = "@(#)job.c	8.2 (Berkeley) 3/19/94";
79236769Sobrien#else
80237578Sobrien__RCSID("$NetBSD: job.c,v 1.162 2012/06/12 19:21:50 joerg Exp $");
81236769Sobrien#endif
82236769Sobrien#endif /* not lint */
83236769Sobrien#endif
84236769Sobrien
85236769Sobrien/*-
86236769Sobrien * job.c --
87236769Sobrien *	handle the creation etc. of our child processes.
88236769Sobrien *
89236769Sobrien * Interface:
90236769Sobrien *	Job_Make  	    	Start the creation of the given target.
91236769Sobrien *
92236769Sobrien *	Job_CatchChildren   	Check for and handle the termination of any
93236769Sobrien *	    	  	    	children. This must be called reasonably
94236769Sobrien *	    	  	    	frequently to keep the whole make going at
95236769Sobrien *	    	  	    	a decent clip, since job table entries aren't
96236769Sobrien *	    	  	    	removed until their process is caught this way.
97236769Sobrien *
98236769Sobrien *	Job_CatchOutput	    	Print any output our children have produced.
99236769Sobrien *	    	  	    	Should also be called fairly frequently to
100236769Sobrien *	    	  	    	keep the user informed of what's going on.
101236769Sobrien *	    	  	    	If no output is waiting, it will block for
102236769Sobrien *	    	  	    	a time given by the SEL_* constants, below,
103236769Sobrien *	    	  	    	or until output is ready.
104236769Sobrien *
105236769Sobrien *	Job_Init  	    	Called to intialize this module. in addition,
106236769Sobrien *	    	  	    	any commands attached to the .BEGIN target
107236769Sobrien *	    	  	    	are executed before this function returns.
108236769Sobrien *	    	  	    	Hence, the makefile must have been parsed
109236769Sobrien *	    	  	    	before this function is called.
110236769Sobrien *
111236769Sobrien *	Job_End  	    	Cleanup any memory used.
112236769Sobrien *
113236769Sobrien *	Job_ParseShell	    	Given the line following a .SHELL target, parse
114236769Sobrien *	    	  	    	the line as a shell specification. Returns
115236769Sobrien *	    	  	    	FAILURE if the spec was incorrect.
116236769Sobrien *
117236769Sobrien *	Job_Finish	    	Perform any final processing which needs doing.
118236769Sobrien *	    	  	    	This includes the execution of any commands
119236769Sobrien *	    	  	    	which have been/were attached to the .END
120236769Sobrien *	    	  	    	target. It should only be called when the
121236769Sobrien *	    	  	    	job table is empty.
122236769Sobrien *
123236769Sobrien *	Job_AbortAll	    	Abort all currently running jobs. It doesn't
124236769Sobrien *	    	  	    	handle output or do anything for the jobs,
125236769Sobrien *	    	  	    	just kills them. It should only be called in
126236769Sobrien *	    	  	    	an emergency, as it were.
127236769Sobrien *
128236769Sobrien *	Job_CheckCommands   	Verify that the commands for a target are
129236769Sobrien *	    	  	    	ok. Provide them if necessary and possible.
130236769Sobrien *
131236769Sobrien *	Job_Touch 	    	Update a target without really updating it.
132236769Sobrien *
133236769Sobrien *	Job_Wait  	    	Wait for all currently-running jobs to finish.
134236769Sobrien */
135236769Sobrien
136236769Sobrien#ifdef HAVE_CONFIG_H
137236769Sobrien# include "config.h"
138236769Sobrien#endif
139236769Sobrien#include <sys/types.h>
140236769Sobrien#include <sys/stat.h>
141236769Sobrien#include <sys/file.h>
142236769Sobrien#include <sys/time.h>
143236769Sobrien#include "wait.h"
144236769Sobrien
145236769Sobrien#include <errno.h>
146236769Sobrien#include <fcntl.h>
147236769Sobrien#if !defined(USE_SELECT) && defined(HAVE_POLL_H)
148236769Sobrien#include <poll.h>
149236769Sobrien#else
150236769Sobrien#ifndef USE_SELECT			/* no poll.h */
151236769Sobrien# define USE_SELECT
152236769Sobrien#endif
153236769Sobrien#if defined(HAVE_SYS_SELECT_H)
154236769Sobrien# include <sys/select.h>
155236769Sobrien#endif
156236769Sobrien#endif
157236769Sobrien#include <signal.h>
158236769Sobrien#include <stdio.h>
159236769Sobrien#include <string.h>
160236769Sobrien#include <utime.h>
161236769Sobrien#if defined(HAVE_SYS_SOCKET_H)
162236769Sobrien# include <sys/socket.h>
163236769Sobrien#endif
164236769Sobrien
165236769Sobrien#include "make.h"
166236769Sobrien#include "hash.h"
167236769Sobrien#include "dir.h"
168236769Sobrien#include "job.h"
169236769Sobrien#include "pathnames.h"
170236769Sobrien#include "trace.h"
171236769Sobrien# define STATIC static
172236769Sobrien
173236769Sobrien/*
174236769Sobrien * error handling variables
175236769Sobrien */
176236769Sobrienstatic int     	errors = 0;	    /* number of errors reported */
177236769Sobrienstatic int    	aborting = 0;	    /* why is the make aborting? */
178236769Sobrien#define ABORT_ERROR	1   	    /* Because of an error */
179236769Sobrien#define ABORT_INTERRUPT	2   	    /* Because it was interrupted */
180236769Sobrien#define ABORT_WAIT	3   	    /* Waiting for jobs to finish */
181236769Sobrien#define JOB_TOKENS	"+EI+"	    /* Token to requeue for each abort state */
182236769Sobrien
183236769Sobrien/*
184236769Sobrien * this tracks the number of tokens currently "out" to build jobs.
185236769Sobrien */
186236769Sobrienint jobTokensRunning = 0;
187236769Sobrienint not_parallel = 0;		    /* set if .NOT_PARALLEL */
188236769Sobrien
189236769Sobrien/*
190236769Sobrien * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
191236769Sobrien * is a char! So when we go above 127 we turn negative!
192236769Sobrien */
193236769Sobrien#define FILENO(a) ((unsigned) fileno(a))
194236769Sobrien
195236769Sobrien/*
196236769Sobrien * post-make command processing. The node postCommands is really just the
197236769Sobrien * .END target but we keep it around to avoid having to search for it
198236769Sobrien * all the time.
199236769Sobrien */
200236769Sobrienstatic GNode   	  *postCommands = NULL;
201236769Sobrien				    /* node containing commands to execute when
202236769Sobrien				     * everything else is done */
203236769Sobrienstatic int     	  numCommands; 	    /* The number of commands actually printed
204236769Sobrien				     * for a target. Should this number be
205236769Sobrien				     * 0, no shell will be executed. */
206236769Sobrien
207236769Sobrien/*
208236769Sobrien * Return values from JobStart.
209236769Sobrien */
210236769Sobrien#define JOB_RUNNING	0   	/* Job is running */
211236769Sobrien#define JOB_ERROR 	1   	/* Error in starting the job */
212236769Sobrien#define JOB_FINISHED	2   	/* The job is already finished */
213236769Sobrien
214236769Sobrien/*
215236769Sobrien * Descriptions for various shells.
216236769Sobrien *
217236769Sobrien * The build environment may set DEFSHELL_INDEX to one of
218236769Sobrien * DEFSHELL_INDEX_SH, DEFSHELL_INDEX_KSH, or DEFSHELL_INDEX_CSH, to
219236769Sobrien * select one of the prefedined shells as the default shell.
220236769Sobrien *
221236769Sobrien * Alternatively, the build environment may set DEFSHELL_CUSTOM to the
222236769Sobrien * name or the full path of a sh-compatible shell, which will be used as
223236769Sobrien * the default shell.
224236769Sobrien *
225236769Sobrien * ".SHELL" lines in Makefiles can choose the default shell from the
226236769Sobrien # set defined here, or add additional shells.
227236769Sobrien */
228236769Sobrien
229236769Sobrien#ifdef DEFSHELL_CUSTOM
230236769Sobrien#define DEFSHELL_INDEX_CUSTOM 0
231236769Sobrien#define DEFSHELL_INDEX_SH     1
232236769Sobrien#define DEFSHELL_INDEX_KSH    2
233236769Sobrien#define DEFSHELL_INDEX_CSH    3
234236769Sobrien#else /* !DEFSHELL_CUSTOM */
235236769Sobrien#define DEFSHELL_INDEX_SH     0
236236769Sobrien#define DEFSHELL_INDEX_KSH    1
237236769Sobrien#define DEFSHELL_INDEX_CSH    2
238236769Sobrien#endif /* !DEFSHELL_CUSTOM */
239236769Sobrien
240236769Sobrien#ifndef DEFSHELL_INDEX
241236769Sobrien#define DEFSHELL_INDEX 0	/* DEFSHELL_INDEX_CUSTOM or DEFSHELL_INDEX_SH */
242236769Sobrien#endif /* !DEFSHELL_INDEX */
243236769Sobrien
244236769Sobrienstatic Shell    shells[] = {
245236769Sobrien#ifdef DEFSHELL_CUSTOM
246236769Sobrien    /*
247236769Sobrien     * An sh-compatible shell with a non-standard name.
248236769Sobrien     *
249236769Sobrien     * Keep this in sync with the "sh" description below, but avoid
250236769Sobrien     * non-portable features that might not be supplied by all
251236769Sobrien     * sh-compatible shells.
252236769Sobrien     */
253236769Sobrien{
254236769Sobrien    DEFSHELL_CUSTOM,
255236769Sobrien    FALSE, "", "", "", 0,
256236769Sobrien    FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
257236769Sobrien    "",
258236769Sobrien    "",
259236769Sobrien},
260236769Sobrien#endif /* DEFSHELL_CUSTOM */
261236769Sobrien    /*
262236769Sobrien     * SH description. Echo control is also possible and, under
263236769Sobrien     * sun UNIX anyway, one can even control error checking.
264236769Sobrien     */
265236769Sobrien{
266236769Sobrien    "sh",
267236769Sobrien    FALSE, "", "", "", 0,
268236769Sobrien    FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
269236769Sobrien#if defined(MAKE_NATIVE) && defined(__NetBSD__)
270236769Sobrien    "q",
271236769Sobrien#else
272236769Sobrien    "",
273236769Sobrien#endif
274236769Sobrien    "",
275236769Sobrien},
276236769Sobrien    /*
277236769Sobrien     * KSH description.
278236769Sobrien     */
279236769Sobrien{
280236769Sobrien    "ksh",
281236769Sobrien    TRUE, "set +v", "set -v", "set +v", 6,
282236769Sobrien    FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
283236769Sobrien    "v",
284236769Sobrien    "",
285236769Sobrien},
286236769Sobrien    /*
287236769Sobrien     * CSH description. The csh can do echo control by playing
288236769Sobrien     * with the setting of the 'echo' shell variable. Sadly,
289236769Sobrien     * however, it is unable to do error control nicely.
290236769Sobrien     */
291236769Sobrien{
292236769Sobrien    "csh",
293236769Sobrien    TRUE, "unset verbose", "set verbose", "unset verbose", 10,
294236769Sobrien    FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"\n", "", "'\\\n'", '#',
295236769Sobrien    "v", "e",
296236769Sobrien},
297236769Sobrien    /*
298236769Sobrien     * UNKNOWN.
299236769Sobrien     */
300236769Sobrien{
301236769Sobrien    NULL,
302236769Sobrien    FALSE, NULL, NULL, NULL, 0,
303236769Sobrien    FALSE, NULL, NULL, NULL, NULL, 0,
304236769Sobrien    NULL, NULL,
305236769Sobrien}
306236769Sobrien};
307236769Sobrienstatic Shell *commandShell = &shells[DEFSHELL_INDEX]; /* this is the shell to
308236769Sobrien						   * which we pass all
309236769Sobrien						   * commands in the Makefile.
310236769Sobrien						   * It is set by the
311236769Sobrien						   * Job_ParseShell function */
312236769Sobrienconst char *shellPath = NULL,		  	  /* full pathname of
313236769Sobrien						   * executable image */
314236769Sobrien           *shellName = NULL;		      	  /* last component of shell */
315236769Sobrienstatic const char *shellArgv = NULL;		  /* Custom shell args */
316236769Sobrien
317236769Sobrien
318236769SobrienSTATIC Job	*job_table;	/* The structures that describe them */
319236769SobrienSTATIC Job	*job_table_end;	/* job_table + maxJobs */
320236769Sobrienstatic int	wantToken;	/* we want a token */
321236769Sobrienstatic int lurking_children = 0;
322236769Sobrienstatic int make_suspended = 0;	/* non-zero if we've seen a SIGTSTP (etc) */
323236769Sobrien
324236769Sobrien/*
325236769Sobrien * Set of descriptors of pipes connected to
326236769Sobrien * the output channels of children
327236769Sobrien */
328236769Sobrienstatic struct pollfd *fds = NULL;
329236769Sobrienstatic Job **jobfds = NULL;
330236769Sobrienstatic int nfds = 0;
331236769Sobrienstatic void watchfd(Job *);
332236769Sobrienstatic void clearfd(Job *);
333236769Sobrienstatic int readyfd(Job *);
334236769Sobrien
335236769SobrienSTATIC GNode   	*lastNode;	/* The node for which output was most recently
336236769Sobrien				 * produced. */
337236769Sobrienstatic char *targPrefix = NULL; /* What we print at the start of TARG_FMT */
338236769Sobrienstatic Job tokenWaitJob;	/* token wait pseudo-job */
339236769Sobrien
340236769Sobrienstatic Job childExitJob;	/* child exit pseudo-job */
341236769Sobrien#define	CHILD_EXIT	"."
342236769Sobrien#define	DO_JOB_RESUME	"R"
343236769Sobrien
344236769Sobrien#define TARG_FMT  "%s %s ---\n" /* Default format */
345236769Sobrien#define MESSAGE(fp, gn) \
346236769Sobrien	if (maxJobs != 1) \
347236769Sobrien	    (void)fprintf(fp, TARG_FMT, targPrefix, gn->name)
348236769Sobrien
349236769Sobrienstatic sigset_t caught_signals;	/* Set of signals we handle */
350236769Sobrien#if defined(SYSV)
351236769Sobrien#define KILLPG(pid, sig)	kill(-(pid), (sig))
352236769Sobrien#else
353236769Sobrien#define KILLPG(pid, sig)	killpg((pid), (sig))
354236769Sobrien#endif
355236769Sobrien
356236769Sobrienstatic void JobChildSig(int);
357236769Sobrienstatic void JobContinueSig(int);
358236769Sobrienstatic Job *JobFindPid(int, int, Boolean);
359236769Sobrienstatic int JobPrintCommand(void *, void *);
360236769Sobrienstatic int JobSaveCommand(void *, void *);
361236769Sobrienstatic void JobClose(Job *);
362236769Sobrienstatic void JobExec(Job *, char **);
363236769Sobrienstatic void JobMakeArgv(Job *, char **);
364236769Sobrienstatic int JobStart(GNode *, int);
365236769Sobrienstatic char *JobOutput(Job *, char *, char *, int);
366236769Sobrienstatic void JobDoOutput(Job *, Boolean);
367236769Sobrienstatic Shell *JobMatchShell(const char *);
368237578Sobrienstatic void JobInterrupt(int, int) MAKE_ATTR_DEAD;
369236769Sobrienstatic void JobRestartJobs(void);
370236769Sobrienstatic void JobTokenAdd(void);
371236769Sobrienstatic void JobSigLock(sigset_t *);
372236769Sobrienstatic void JobSigUnlock(sigset_t *);
373236769Sobrienstatic void JobSigReset(void);
374236769Sobrien
375236769Sobrienconst char *malloc_options="A";
376236769Sobrien
377236769Sobrienstatic void
378236769Sobrienjob_table_dump(const char *where)
379236769Sobrien{
380236769Sobrien    Job *job;
381236769Sobrien
382236769Sobrien    fprintf(debug_file, "job table @ %s\n", where);
383236769Sobrien    for (job = job_table; job < job_table_end; job++) {
384236769Sobrien	fprintf(debug_file, "job %d, status %d, flags %d, pid %d\n",
385236769Sobrien	    (int)(job - job_table), job->job_state, job->flags, job->pid);
386236769Sobrien    }
387236769Sobrien}
388236769Sobrien
389236769Sobrien/*
390236769Sobrien * JobSigLock/JobSigUnlock
391236769Sobrien *
392236769Sobrien * Signal lock routines to get exclusive access. Currently used to
393236769Sobrien * protect `jobs' and `stoppedJobs' list manipulations.
394236769Sobrien */
395236769Sobrienstatic void JobSigLock(sigset_t *omaskp)
396236769Sobrien{
397236769Sobrien	if (sigprocmask(SIG_BLOCK, &caught_signals, omaskp) != 0) {
398236769Sobrien		Punt("JobSigLock: sigprocmask: %s", strerror(errno));
399236769Sobrien		sigemptyset(omaskp);
400236769Sobrien	}
401236769Sobrien}
402236769Sobrien
403236769Sobrienstatic void JobSigUnlock(sigset_t *omaskp)
404236769Sobrien{
405236769Sobrien	(void)sigprocmask(SIG_SETMASK, omaskp, NULL);
406236769Sobrien}
407236769Sobrien
408236769Sobrienstatic void
409236769SobrienJobCreatePipe(Job *job, int minfd)
410236769Sobrien{
411236769Sobrien    int i, fd;
412236769Sobrien
413236769Sobrien    if (pipe(job->jobPipe) == -1)
414236769Sobrien	Punt("Cannot create pipe: %s", strerror(errno));
415236769Sobrien
416236769Sobrien    /* Set close-on-exec flag for both */
417236769Sobrien    (void)fcntl(job->jobPipe[0], F_SETFD, 1);
418236769Sobrien    (void)fcntl(job->jobPipe[1], F_SETFD, 1);
419236769Sobrien
420236769Sobrien    /*
421236769Sobrien     * We mark the input side of the pipe non-blocking; we poll(2) the
422236769Sobrien     * pipe when we're waiting for a job token, but we might lose the
423236769Sobrien     * race for the token when a new one becomes available, so the read
424236769Sobrien     * from the pipe should not block.
425236769Sobrien     */
426236769Sobrien    fcntl(job->jobPipe[0], F_SETFL,
427236769Sobrien	fcntl(job->jobPipe[0], F_GETFL, 0) | O_NONBLOCK);
428236769Sobrien
429236769Sobrien    for (i = 0; i < 2; i++) {
430236769Sobrien       /* Avoid using low numbered fds */
431236769Sobrien       fd = fcntl(job->jobPipe[i], F_DUPFD, minfd);
432236769Sobrien       if (fd != -1) {
433236769Sobrien	   close(job->jobPipe[i]);
434236769Sobrien	   job->jobPipe[i] = fd;
435236769Sobrien       }
436236769Sobrien    }
437236769Sobrien}
438236769Sobrien
439236769Sobrien/*-
440236769Sobrien *-----------------------------------------------------------------------
441236769Sobrien * JobCondPassSig --
442236769Sobrien *	Pass a signal to a job
443236769Sobrien *
444236769Sobrien * Input:
445236769Sobrien *	signop		Signal to send it
446236769Sobrien *
447236769Sobrien * Side Effects:
448236769Sobrien *	None, except the job may bite it.
449236769Sobrien *
450236769Sobrien *-----------------------------------------------------------------------
451236769Sobrien */
452236769Sobrienstatic void
453236769SobrienJobCondPassSig(int signo)
454236769Sobrien{
455236769Sobrien    Job *job;
456236769Sobrien
457236769Sobrien    if (DEBUG(JOB)) {
458236769Sobrien	(void)fprintf(debug_file, "JobCondPassSig(%d) called.\n", signo);
459236769Sobrien    }
460236769Sobrien
461236769Sobrien    for (job = job_table; job < job_table_end; job++) {
462236769Sobrien	if (job->job_state != JOB_ST_RUNNING)
463236769Sobrien	    continue;
464236769Sobrien	if (DEBUG(JOB)) {
465236769Sobrien	    (void)fprintf(debug_file,
466236769Sobrien			   "JobCondPassSig passing signal %d to child %d.\n",
467236769Sobrien			   signo, job->pid);
468236769Sobrien	}
469236769Sobrien	KILLPG(job->pid, signo);
470236769Sobrien    }
471236769Sobrien}
472236769Sobrien
473236769Sobrien/*-
474236769Sobrien *-----------------------------------------------------------------------
475236769Sobrien * JobChldSig --
476236769Sobrien *	SIGCHLD handler.
477236769Sobrien *
478236769Sobrien * Input:
479236769Sobrien *	signo		The signal number we've received
480236769Sobrien *
481236769Sobrien * Results:
482236769Sobrien *	None.
483236769Sobrien *
484236769Sobrien * Side Effects:
485236769Sobrien *	Sends a token on the child exit pipe to wake us up from
486236769Sobrien *	select()/poll().
487236769Sobrien *
488236769Sobrien *-----------------------------------------------------------------------
489236769Sobrien */
490236769Sobrienstatic void
491237578SobrienJobChildSig(int signo MAKE_ATTR_UNUSED)
492236769Sobrien{
493236769Sobrien    write(childExitJob.outPipe, CHILD_EXIT, 1);
494236769Sobrien}
495236769Sobrien
496236769Sobrien
497236769Sobrien/*-
498236769Sobrien *-----------------------------------------------------------------------
499236769Sobrien * JobContinueSig --
500236769Sobrien *	Resume all stopped jobs.
501236769Sobrien *
502236769Sobrien * Input:
503236769Sobrien *	signo		The signal number we've received
504236769Sobrien *
505236769Sobrien * Results:
506236769Sobrien *	None.
507236769Sobrien *
508236769Sobrien * Side Effects:
509236769Sobrien *	Jobs start running again.
510236769Sobrien *
511236769Sobrien *-----------------------------------------------------------------------
512236769Sobrien */
513236769Sobrienstatic void
514237578SobrienJobContinueSig(int signo MAKE_ATTR_UNUSED)
515236769Sobrien{
516236769Sobrien    /*
517236769Sobrien     * Defer sending to SIGCONT to our stopped children until we return
518236769Sobrien     * from the signal handler.
519236769Sobrien     */
520236769Sobrien    write(childExitJob.outPipe, DO_JOB_RESUME, 1);
521236769Sobrien}
522236769Sobrien
523236769Sobrien/*-
524236769Sobrien *-----------------------------------------------------------------------
525236769Sobrien * JobPassSig --
526236769Sobrien *	Pass a signal on to all jobs, then resend to ourselves.
527236769Sobrien *
528236769Sobrien * Input:
529236769Sobrien *	signo		The signal number we've received
530236769Sobrien *
531236769Sobrien * Results:
532236769Sobrien *	None.
533236769Sobrien *
534236769Sobrien * Side Effects:
535236769Sobrien *	We die by the same signal.
536236769Sobrien *
537236769Sobrien *-----------------------------------------------------------------------
538236769Sobrien */
539237578SobrienMAKE_ATTR_DEAD static void
540236769SobrienJobPassSig_int(int signo)
541236769Sobrien{
542236769Sobrien    /* Run .INTERRUPT target then exit */
543236769Sobrien    JobInterrupt(TRUE, signo);
544236769Sobrien}
545236769Sobrien
546237578SobrienMAKE_ATTR_DEAD static void
547236769SobrienJobPassSig_term(int signo)
548236769Sobrien{
549236769Sobrien    /* Dont run .INTERRUPT target then exit */
550236769Sobrien    JobInterrupt(FALSE, signo);
551236769Sobrien}
552236769Sobrien
553236769Sobrienstatic void
554236769SobrienJobPassSig_suspend(int signo)
555236769Sobrien{
556236769Sobrien    sigset_t nmask, omask;
557236769Sobrien    struct sigaction act;
558236769Sobrien
559236769Sobrien    /* Suppress job started/continued messages */
560236769Sobrien    make_suspended = 1;
561236769Sobrien
562236769Sobrien    /* Pass the signal onto every job */
563236769Sobrien    JobCondPassSig(signo);
564236769Sobrien
565236769Sobrien    /*
566236769Sobrien     * Send ourselves the signal now we've given the message to everyone else.
567236769Sobrien     * Note we block everything else possible while we're getting the signal.
568236769Sobrien     * This ensures that all our jobs get continued when we wake up before
569236769Sobrien     * we take any other signal.
570236769Sobrien     */
571236769Sobrien    sigfillset(&nmask);
572236769Sobrien    sigdelset(&nmask, signo);
573236769Sobrien    (void)sigprocmask(SIG_SETMASK, &nmask, &omask);
574236769Sobrien
575236769Sobrien    act.sa_handler = SIG_DFL;
576236769Sobrien    sigemptyset(&act.sa_mask);
577236769Sobrien    act.sa_flags = 0;
578236769Sobrien    (void)sigaction(signo, &act, NULL);
579236769Sobrien
580236769Sobrien    if (DEBUG(JOB)) {
581236769Sobrien	(void)fprintf(debug_file,
582236769Sobrien		       "JobPassSig passing signal %d to self.\n", signo);
583236769Sobrien    }
584236769Sobrien
585236769Sobrien    (void)kill(getpid(), signo);
586236769Sobrien
587236769Sobrien    /*
588236769Sobrien     * We've been continued.
589236769Sobrien     *
590236769Sobrien     * A whole host of signals continue to happen!
591236769Sobrien     * SIGCHLD for any processes that actually suspended themselves.
592236769Sobrien     * SIGCHLD for any processes that exited while we were alseep.
593236769Sobrien     * The SIGCONT that actually caused us to wakeup.
594236769Sobrien     *
595236769Sobrien     * Since we defer passing the SIGCONT on to our children until
596236769Sobrien     * the main processing loop, we can be sure that all the SIGCHLD
597236769Sobrien     * events will have happened by then - and that the waitpid() will
598236769Sobrien     * collect the child 'suspended' events.
599236769Sobrien     * For correct sequencing we just need to ensure we process the
600236769Sobrien     * waitpid() before passign on the SIGCONT.
601236769Sobrien     *
602236769Sobrien     * In any case nothing else is needed here.
603236769Sobrien     */
604236769Sobrien
605236769Sobrien    /* Restore handler and signal mask */
606236769Sobrien    act.sa_handler = JobPassSig_suspend;
607236769Sobrien    (void)sigaction(signo, &act, NULL);
608236769Sobrien    (void)sigprocmask(SIG_SETMASK, &omask, NULL);
609236769Sobrien}
610236769Sobrien
611236769Sobrien/*-
612236769Sobrien *-----------------------------------------------------------------------
613236769Sobrien * JobFindPid  --
614236769Sobrien *	Compare the pid of the job with the given pid and return 0 if they
615236769Sobrien *	are equal. This function is called from Job_CatchChildren
616236769Sobrien *	to find the job descriptor of the finished job.
617236769Sobrien *
618236769Sobrien * Input:
619236769Sobrien *	job		job to examine
620236769Sobrien *	pid		process id desired
621236769Sobrien *
622236769Sobrien * Results:
623236769Sobrien *	Job with matching pid
624236769Sobrien *
625236769Sobrien * Side Effects:
626236769Sobrien *	None
627236769Sobrien *-----------------------------------------------------------------------
628236769Sobrien */
629236769Sobrienstatic Job *
630236769SobrienJobFindPid(int pid, int status, Boolean isJobs)
631236769Sobrien{
632236769Sobrien    Job *job;
633236769Sobrien
634236769Sobrien    for (job = job_table; job < job_table_end; job++) {
635236769Sobrien	if ((job->job_state == status) && job->pid == pid)
636236769Sobrien	    return job;
637236769Sobrien    }
638236769Sobrien    if (DEBUG(JOB) && isJobs)
639236769Sobrien	job_table_dump("no pid");
640236769Sobrien    return NULL;
641236769Sobrien}
642236769Sobrien
643236769Sobrien/*-
644236769Sobrien *-----------------------------------------------------------------------
645236769Sobrien * JobPrintCommand  --
646236769Sobrien *	Put out another command for the given job. If the command starts
647236769Sobrien *	with an @ or a - we process it specially. In the former case,
648236769Sobrien *	so long as the -s and -n flags weren't given to make, we stick
649236769Sobrien *	a shell-specific echoOff command in the script. In the latter,
650236769Sobrien *	we ignore errors for the entire job, unless the shell has error
651236769Sobrien *	control.
652236769Sobrien *	If the command is just "..." we take all future commands for this
653236769Sobrien *	job to be commands to be executed once the entire graph has been
654236769Sobrien *	made and return non-zero to signal that the end of the commands
655236769Sobrien *	was reached. These commands are later attached to the postCommands
656236769Sobrien *	node and executed by Job_End when all things are done.
657236769Sobrien *	This function is called from JobStart via Lst_ForEach.
658236769Sobrien *
659236769Sobrien * Input:
660236769Sobrien *	cmdp		command string to print
661236769Sobrien *	jobp		job for which to print it
662236769Sobrien *
663236769Sobrien * Results:
664236769Sobrien *	Always 0, unless the command was "..."
665236769Sobrien *
666236769Sobrien * Side Effects:
667236769Sobrien *	If the command begins with a '-' and the shell has no error control,
668236769Sobrien *	the JOB_IGNERR flag is set in the job descriptor.
669236769Sobrien *	If the command is "..." and we're not ignoring such things,
670236769Sobrien *	tailCmds is set to the successor node of the cmd.
671236769Sobrien *	numCommands is incremented if the command is actually printed.
672236769Sobrien *-----------------------------------------------------------------------
673236769Sobrien */
674236769Sobrienstatic int
675236769SobrienJobPrintCommand(void *cmdp, void *jobp)
676236769Sobrien{
677236769Sobrien    Boolean	  noSpecials;	    /* true if we shouldn't worry about
678236769Sobrien				     * inserting special commands into
679236769Sobrien				     * the input stream. */
680236769Sobrien    Boolean       shutUp = FALSE;   /* true if we put a no echo command
681236769Sobrien				     * into the command file */
682236769Sobrien    Boolean	  errOff = FALSE;   /* true if we turned error checking
683236769Sobrien				     * off before printing the command
684236769Sobrien				     * and need to turn it back on */
685236769Sobrien    const char    *cmdTemplate;	    /* Template to use when printing the
686236769Sobrien				     * command */
687236769Sobrien    char    	  *cmdStart;	    /* Start of expanded command */
688236769Sobrien    char	  *escCmd = NULL;    /* Command with quotes/backticks escaped */
689236769Sobrien    char     	  *cmd = (char *)cmdp;
690236769Sobrien    Job           *job = (Job *)jobp;
691236769Sobrien    char	  *cp, *tmp;
692236769Sobrien    int           i, j;
693236769Sobrien
694236769Sobrien    noSpecials = NoExecute(job->node);
695236769Sobrien
696236769Sobrien    if (strcmp(cmd, "...") == 0) {
697236769Sobrien	job->node->type |= OP_SAVE_CMDS;
698236769Sobrien	if ((job->flags & JOB_IGNDOTS) == 0) {
699236769Sobrien	    job->tailCmds = Lst_Succ(Lst_Member(job->node->commands,
700236769Sobrien						cmd));
701236769Sobrien	    return 1;
702236769Sobrien	}
703236769Sobrien	return 0;
704236769Sobrien    }
705236769Sobrien
706236769Sobrien#define DBPRINTF(fmt, arg) if (DEBUG(JOB)) {	\
707236769Sobrien	(void)fprintf(debug_file, fmt, arg); 	\
708236769Sobrien    }						\
709236769Sobrien   (void)fprintf(job->cmdFILE, fmt, arg);	\
710236769Sobrien   (void)fflush(job->cmdFILE);
711236769Sobrien
712236769Sobrien    numCommands += 1;
713236769Sobrien
714236769Sobrien    cmdStart = cmd = Var_Subst(NULL, cmd, job->node, FALSE);
715236769Sobrien
716236769Sobrien    cmdTemplate = "%s\n";
717236769Sobrien
718236769Sobrien    /*
719236769Sobrien     * Check for leading @' and -'s to control echoing and error checking.
720236769Sobrien     */
721236769Sobrien    while (*cmd == '@' || *cmd == '-' || (*cmd == '+')) {
722236769Sobrien	switch (*cmd) {
723236769Sobrien	case '@':
724236769Sobrien	    shutUp = DEBUG(LOUD) ? FALSE : TRUE;
725236769Sobrien	    break;
726236769Sobrien	case '-':
727236769Sobrien	    job->flags |= JOB_IGNERR;
728236769Sobrien	    errOff = TRUE;
729236769Sobrien	    break;
730236769Sobrien	case '+':
731236769Sobrien	    if (noSpecials) {
732236769Sobrien		/*
733236769Sobrien		 * We're not actually executing anything...
734236769Sobrien		 * but this one needs to be - use compat mode just for it.
735236769Sobrien		 */
736236769Sobrien		CompatRunCommand(cmdp, job->node);
737236769Sobrien		return 0;
738236769Sobrien	    }
739236769Sobrien	    break;
740236769Sobrien	}
741236769Sobrien	cmd++;
742236769Sobrien    }
743236769Sobrien
744236769Sobrien    while (isspace((unsigned char) *cmd))
745236769Sobrien	cmd++;
746236769Sobrien
747236769Sobrien    /*
748236769Sobrien     * If the shell doesn't have error control the alternate echo'ing will
749236769Sobrien     * be done (to avoid showing additional error checking code)
750236769Sobrien     * and this will need the characters '$ ` \ "' escaped
751236769Sobrien     */
752236769Sobrien
753236769Sobrien    if (!commandShell->hasErrCtl) {
754236769Sobrien	/* Worst that could happen is every char needs escaping. */
755236769Sobrien	escCmd = bmake_malloc((strlen(cmd) * 2) + 1);
756236769Sobrien	for (i = 0, j= 0; cmd[i] != '\0'; i++, j++) {
757236769Sobrien		if (cmd[i] == '$' || cmd[i] == '`' || cmd[i] == '\\' ||
758236769Sobrien			cmd[i] == '"')
759236769Sobrien			escCmd[j++] = '\\';
760236769Sobrien		escCmd[j] = cmd[i];
761236769Sobrien	}
762236769Sobrien	escCmd[j] = 0;
763236769Sobrien    }
764236769Sobrien
765236769Sobrien    if (shutUp) {
766236769Sobrien	if (!(job->flags & JOB_SILENT) && !noSpecials &&
767236769Sobrien	    commandShell->hasEchoCtl) {
768236769Sobrien		DBPRINTF("%s\n", commandShell->echoOff);
769236769Sobrien	} else {
770236769Sobrien	    if (commandShell->hasErrCtl)
771236769Sobrien		shutUp = FALSE;
772236769Sobrien	}
773236769Sobrien    }
774236769Sobrien
775236769Sobrien    if (errOff) {
776236769Sobrien	if (!noSpecials) {
777236769Sobrien	    if (commandShell->hasErrCtl) {
778236769Sobrien		/*
779236769Sobrien		 * we don't want the error-control commands showing
780236769Sobrien		 * up either, so we turn off echoing while executing
781236769Sobrien		 * them. We could put another field in the shell
782236769Sobrien		 * structure to tell JobDoOutput to look for this
783236769Sobrien		 * string too, but why make it any more complex than
784236769Sobrien		 * it already is?
785236769Sobrien		 */
786236769Sobrien		if (!(job->flags & JOB_SILENT) && !shutUp &&
787236769Sobrien		    commandShell->hasEchoCtl) {
788236769Sobrien			DBPRINTF("%s\n", commandShell->echoOff);
789236769Sobrien			DBPRINTF("%s\n", commandShell->ignErr);
790236769Sobrien			DBPRINTF("%s\n", commandShell->echoOn);
791236769Sobrien		} else {
792236769Sobrien			DBPRINTF("%s\n", commandShell->ignErr);
793236769Sobrien		}
794236769Sobrien	    } else if (commandShell->ignErr &&
795236769Sobrien		      (*commandShell->ignErr != '\0'))
796236769Sobrien	    {
797236769Sobrien		/*
798236769Sobrien		 * The shell has no error control, so we need to be
799236769Sobrien		 * weird to get it to ignore any errors from the command.
800236769Sobrien		 * If echoing is turned on, we turn it off and use the
801236769Sobrien		 * errCheck template to echo the command. Leave echoing
802236769Sobrien		 * off so the user doesn't see the weirdness we go through
803236769Sobrien		 * to ignore errors. Set cmdTemplate to use the weirdness
804236769Sobrien		 * instead of the simple "%s\n" template.
805236769Sobrien		 */
806236769Sobrien		if (!(job->flags & JOB_SILENT) && !shutUp) {
807236769Sobrien			if (commandShell->hasEchoCtl) {
808236769Sobrien				DBPRINTF("%s\n", commandShell->echoOff);
809236769Sobrien			}
810236769Sobrien			DBPRINTF(commandShell->errCheck, escCmd);
811236769Sobrien			shutUp = TRUE;
812236769Sobrien		} else {
813236769Sobrien			if (!shutUp) {
814236769Sobrien				DBPRINTF(commandShell->errCheck, escCmd);
815236769Sobrien			}
816236769Sobrien		}
817236769Sobrien		cmdTemplate = commandShell->ignErr;
818236769Sobrien		/*
819236769Sobrien		 * The error ignoration (hee hee) is already taken care
820236769Sobrien		 * of by the ignErr template, so pretend error checking
821236769Sobrien		 * is still on.
822236769Sobrien		 */
823236769Sobrien		errOff = FALSE;
824236769Sobrien	    } else {
825236769Sobrien		errOff = FALSE;
826236769Sobrien	    }
827236769Sobrien	} else {
828236769Sobrien	    errOff = FALSE;
829236769Sobrien	}
830236769Sobrien    } else {
831236769Sobrien
832236769Sobrien	/*
833236769Sobrien	 * If errors are being checked and the shell doesn't have error control
834236769Sobrien	 * but does supply an errOut template, then setup commands to run
835236769Sobrien	 * through it.
836236769Sobrien	 */
837236769Sobrien
838236769Sobrien	if (!commandShell->hasErrCtl && commandShell->errOut &&
839236769Sobrien	    (*commandShell->errOut != '\0')) {
840236769Sobrien		if (!(job->flags & JOB_SILENT) && !shutUp) {
841236769Sobrien			if (commandShell->hasEchoCtl) {
842236769Sobrien				DBPRINTF("%s\n", commandShell->echoOff);
843236769Sobrien			}
844236769Sobrien			DBPRINTF(commandShell->errCheck, escCmd);
845236769Sobrien			shutUp = TRUE;
846236769Sobrien		}
847236769Sobrien		/* If it's a comment line or blank, treat as an ignored error */
848236769Sobrien		if ((escCmd[0] == commandShell->commentChar) ||
849236769Sobrien		    (escCmd[0] == 0))
850236769Sobrien			cmdTemplate = commandShell->ignErr;
851236769Sobrien		else
852236769Sobrien			cmdTemplate = commandShell->errOut;
853236769Sobrien		errOff = FALSE;
854236769Sobrien	}
855236769Sobrien    }
856236769Sobrien
857236769Sobrien    if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0 &&
858236769Sobrien	(job->flags & JOB_TRACED) == 0) {
859236769Sobrien	    DBPRINTF("set -%s\n", "x");
860236769Sobrien	    job->flags |= JOB_TRACED;
861236769Sobrien    }
862236769Sobrien
863236769Sobrien    if ((cp = Check_Cwd_Cmd(cmd)) != NULL) {
864236769Sobrien	    DBPRINTF("test -d %s && ", cp);
865236769Sobrien	    DBPRINTF("cd %s\n", cp);
866236769Sobrien    }
867236769Sobrien
868236769Sobrien    DBPRINTF(cmdTemplate, cmd);
869236769Sobrien    free(cmdStart);
870236769Sobrien    if (escCmd)
871236769Sobrien        free(escCmd);
872236769Sobrien    if (errOff) {
873236769Sobrien	/*
874236769Sobrien	 * If echoing is already off, there's no point in issuing the
875236769Sobrien	 * echoOff command. Otherwise we issue it and pretend it was on
876236769Sobrien	 * for the whole command...
877236769Sobrien	 */
878236769Sobrien	if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl){
879236769Sobrien	    DBPRINTF("%s\n", commandShell->echoOff);
880236769Sobrien	    shutUp = TRUE;
881236769Sobrien	}
882236769Sobrien	DBPRINTF("%s\n", commandShell->errCheck);
883236769Sobrien    }
884236769Sobrien    if (shutUp && commandShell->hasEchoCtl) {
885236769Sobrien	DBPRINTF("%s\n", commandShell->echoOn);
886236769Sobrien    }
887236769Sobrien    if (cp != NULL) {
888236769Sobrien	    DBPRINTF("test -d %s && ", cp);
889236769Sobrien	    DBPRINTF("cd %s\n", Var_Value(".OBJDIR", VAR_GLOBAL, &tmp));
890236769Sobrien    }
891236769Sobrien    return 0;
892236769Sobrien}
893236769Sobrien
894236769Sobrien/*-
895236769Sobrien *-----------------------------------------------------------------------
896236769Sobrien * JobSaveCommand --
897236769Sobrien *	Save a command to be executed when everything else is done.
898236769Sobrien *	Callback function for JobFinish...
899236769Sobrien *
900236769Sobrien * Results:
901236769Sobrien *	Always returns 0
902236769Sobrien *
903236769Sobrien * Side Effects:
904236769Sobrien *	The command is tacked onto the end of postCommands's commands list.
905236769Sobrien *
906236769Sobrien *-----------------------------------------------------------------------
907236769Sobrien */
908236769Sobrienstatic int
909236769SobrienJobSaveCommand(void *cmd, void *gn)
910236769Sobrien{
911236769Sobrien    cmd = Var_Subst(NULL, (char *)cmd, (GNode *)gn, FALSE);
912236769Sobrien    (void)Lst_AtEnd(postCommands->commands, cmd);
913236769Sobrien    return(0);
914236769Sobrien}
915236769Sobrien
916236769Sobrien
917236769Sobrien/*-
918236769Sobrien *-----------------------------------------------------------------------
919236769Sobrien * JobClose --
920236769Sobrien *	Called to close both input and output pipes when a job is finished.
921236769Sobrien *
922236769Sobrien * Results:
923236769Sobrien *	Nada
924236769Sobrien *
925236769Sobrien * Side Effects:
926236769Sobrien *	The file descriptors associated with the job are closed.
927236769Sobrien *
928236769Sobrien *-----------------------------------------------------------------------
929236769Sobrien */
930236769Sobrienstatic void
931236769SobrienJobClose(Job *job)
932236769Sobrien{
933236769Sobrien    clearfd(job);
934236769Sobrien    (void)close(job->outPipe);
935236769Sobrien    job->outPipe = -1;
936236769Sobrien
937236769Sobrien    JobDoOutput(job, TRUE);
938236769Sobrien    (void)close(job->inPipe);
939236769Sobrien    job->inPipe = -1;
940236769Sobrien}
941236769Sobrien
942236769Sobrien/*-
943236769Sobrien *-----------------------------------------------------------------------
944236769Sobrien * JobFinish  --
945236769Sobrien *	Do final processing for the given job including updating
946236769Sobrien *	parents and starting new jobs as available/necessary. Note
947236769Sobrien *	that we pay no attention to the JOB_IGNERR flag here.
948236769Sobrien *	This is because when we're called because of a noexecute flag
949236769Sobrien *	or something, jstat.w_status is 0 and when called from
950236769Sobrien *	Job_CatchChildren, the status is zeroed if it s/b ignored.
951236769Sobrien *
952236769Sobrien * Input:
953236769Sobrien *	job		job to finish
954236769Sobrien *	status		sub-why job went away
955236769Sobrien *
956236769Sobrien * Results:
957236769Sobrien *	None
958236769Sobrien *
959236769Sobrien * Side Effects:
960236769Sobrien *	Final commands for the job are placed on postCommands.
961236769Sobrien *
962236769Sobrien *	If we got an error and are aborting (aborting == ABORT_ERROR) and
963236769Sobrien *	the job list is now empty, we are done for the day.
964236769Sobrien *	If we recognized an error (errors !=0), we set the aborting flag
965236769Sobrien *	to ABORT_ERROR so no more jobs will be started.
966236769Sobrien *-----------------------------------------------------------------------
967236769Sobrien */
968236769Sobrien/*ARGSUSED*/
969236769Sobrienstatic void
970236769SobrienJobFinish (Job *job, WAIT_T status)
971236769Sobrien{
972236769Sobrien    Boolean 	 done, return_job_token;
973236769Sobrien
974236769Sobrien    if (DEBUG(JOB)) {
975236769Sobrien	fprintf(debug_file, "Jobfinish: %d [%s], status %d\n",
976236769Sobrien				job->pid, job->node->name, status);
977236769Sobrien    }
978236769Sobrien
979236769Sobrien    if ((WIFEXITED(status) &&
980236769Sobrien	 (((WEXITSTATUS(status) != 0) && !(job->flags & JOB_IGNERR)))) ||
981236769Sobrien	WIFSIGNALED(status))
982236769Sobrien    {
983236769Sobrien	/*
984236769Sobrien	 * If it exited non-zero and either we're doing things our
985236769Sobrien	 * way or we're not ignoring errors, the job is finished.
986236769Sobrien	 * Similarly, if the shell died because of a signal
987236769Sobrien	 * the job is also finished. In these
988236769Sobrien	 * cases, finish out the job's output before printing the exit
989236769Sobrien	 * status...
990236769Sobrien	 */
991236769Sobrien	JobClose(job);
992236769Sobrien	if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
993236769Sobrien	   (void)fclose(job->cmdFILE);
994236769Sobrien	   job->cmdFILE = NULL;
995236769Sobrien	}
996236769Sobrien	done = TRUE;
997236769Sobrien    } else if (WIFEXITED(status)) {
998236769Sobrien	/*
999236769Sobrien	 * Deal with ignored errors in -B mode. We need to print a message
1000236769Sobrien	 * telling of the ignored error as well as setting status.w_status
1001236769Sobrien	 * to 0 so the next command gets run. To do this, we set done to be
1002236769Sobrien	 * TRUE if in -B mode and the job exited non-zero.
1003236769Sobrien	 */
1004236769Sobrien	done = WEXITSTATUS(status) != 0;
1005236769Sobrien	/*
1006236769Sobrien	 * Old comment said: "Note we don't
1007236769Sobrien	 * want to close down any of the streams until we know we're at the
1008236769Sobrien	 * end."
1009236769Sobrien	 * But we do. Otherwise when are we going to print the rest of the
1010236769Sobrien	 * stuff?
1011236769Sobrien	 */
1012236769Sobrien	JobClose(job);
1013236769Sobrien    } else {
1014236769Sobrien	/*
1015236769Sobrien	 * No need to close things down or anything.
1016236769Sobrien	 */
1017236769Sobrien	done = FALSE;
1018236769Sobrien    }
1019236769Sobrien
1020236769Sobrien    if (done) {
1021236769Sobrien	if (WIFEXITED(status)) {
1022236769Sobrien	    if (DEBUG(JOB)) {
1023236769Sobrien		(void)fprintf(debug_file, "Process %d [%s] exited.\n",
1024236769Sobrien				job->pid, job->node->name);
1025236769Sobrien	    }
1026236769Sobrien	    if (WEXITSTATUS(status) != 0) {
1027236769Sobrien		if (job->node != lastNode) {
1028236769Sobrien		    MESSAGE(stdout, job->node);
1029236769Sobrien		    lastNode = job->node;
1030236769Sobrien		}
1031236769Sobrien#ifdef USE_META
1032236769Sobrien		if (useMeta) {
1033236769Sobrien		    meta_job_error(job, job->node, job->flags, WEXITSTATUS(status));
1034236769Sobrien		}
1035236769Sobrien#endif
1036236769Sobrien		(void)printf("*** [%s] Error code %d%s\n",
1037236769Sobrien				job->node->name,
1038236769Sobrien			       WEXITSTATUS(status),
1039236769Sobrien			       (job->flags & JOB_IGNERR) ? " (ignored)" : "");
1040236769Sobrien		if (job->flags & JOB_IGNERR) {
1041236769Sobrien		    WAIT_STATUS(status) = 0;
1042236769Sobrien		} else {
1043236769Sobrien		    PrintOnError(job->node, NULL);
1044236769Sobrien		}
1045236769Sobrien	    } else if (DEBUG(JOB)) {
1046236769Sobrien		if (job->node != lastNode) {
1047236769Sobrien		    MESSAGE(stdout, job->node);
1048236769Sobrien		    lastNode = job->node;
1049236769Sobrien		}
1050236769Sobrien		(void)printf("*** [%s] Completed successfully\n",
1051236769Sobrien				job->node->name);
1052236769Sobrien	    }
1053236769Sobrien	} else {
1054236769Sobrien	    if (job->node != lastNode) {
1055236769Sobrien		MESSAGE(stdout, job->node);
1056236769Sobrien		lastNode = job->node;
1057236769Sobrien	    }
1058236769Sobrien	    (void)printf("*** [%s] Signal %d\n",
1059236769Sobrien			job->node->name, WTERMSIG(status));
1060236769Sobrien	}
1061236769Sobrien	(void)fflush(stdout);
1062236769Sobrien    }
1063236769Sobrien
1064236769Sobrien#ifdef USE_META
1065236769Sobrien    if (useMeta) {
1066236769Sobrien	meta_job_finish(job);
1067236769Sobrien    }
1068236769Sobrien#endif
1069236769Sobrien
1070236769Sobrien    return_job_token = FALSE;
1071236769Sobrien
1072236769Sobrien    Trace_Log(JOBEND, job);
1073236769Sobrien    if (!(job->flags & JOB_SPECIAL)) {
1074236769Sobrien	if ((WAIT_STATUS(status) != 0) ||
1075236769Sobrien		(aborting == ABORT_ERROR) ||
1076236769Sobrien		(aborting == ABORT_INTERRUPT))
1077236769Sobrien	    return_job_token = TRUE;
1078236769Sobrien    }
1079236769Sobrien
1080236769Sobrien    if ((aborting != ABORT_ERROR) && (aborting != ABORT_INTERRUPT) &&
1081236769Sobrien	(WAIT_STATUS(status) == 0)) {
1082236769Sobrien	/*
1083236769Sobrien	 * As long as we aren't aborting and the job didn't return a non-zero
1084236769Sobrien	 * status that we shouldn't ignore, we call Make_Update to update
1085236769Sobrien	 * the parents. In addition, any saved commands for the node are placed
1086236769Sobrien	 * on the .END target.
1087236769Sobrien	 */
1088236769Sobrien	if (job->tailCmds != NULL) {
1089236769Sobrien	    Lst_ForEachFrom(job->node->commands, job->tailCmds,
1090236769Sobrien			     JobSaveCommand,
1091236769Sobrien			    job->node);
1092236769Sobrien	}
1093236769Sobrien	job->node->made = MADE;
1094236769Sobrien	if (!(job->flags & JOB_SPECIAL))
1095236769Sobrien	    return_job_token = TRUE;
1096236769Sobrien	Make_Update(job->node);
1097236769Sobrien	job->job_state = JOB_ST_FREE;
1098236769Sobrien    } else if (WAIT_STATUS(status)) {
1099236769Sobrien	errors += 1;
1100236769Sobrien	job->job_state = JOB_ST_FREE;
1101236769Sobrien    }
1102236769Sobrien
1103236769Sobrien    /*
1104236769Sobrien     * Set aborting if any error.
1105236769Sobrien     */
1106236769Sobrien    if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
1107236769Sobrien	/*
1108236769Sobrien	 * If we found any errors in this batch of children and the -k flag
1109236769Sobrien	 * wasn't given, we set the aborting flag so no more jobs get
1110236769Sobrien	 * started.
1111236769Sobrien	 */
1112236769Sobrien	aborting = ABORT_ERROR;
1113236769Sobrien    }
1114236769Sobrien
1115236769Sobrien    if (return_job_token)
1116236769Sobrien	Job_TokenReturn();
1117236769Sobrien
1118236769Sobrien    if (aborting == ABORT_ERROR && jobTokensRunning == 0) {
1119236769Sobrien	/*
1120236769Sobrien	 * If we are aborting and the job table is now empty, we finish.
1121236769Sobrien	 */
1122236769Sobrien	Finish(errors);
1123236769Sobrien    }
1124236769Sobrien}
1125236769Sobrien
1126236769Sobrien/*-
1127236769Sobrien *-----------------------------------------------------------------------
1128236769Sobrien * Job_Touch --
1129236769Sobrien *	Touch the given target. Called by JobStart when the -t flag was
1130236769Sobrien *	given
1131236769Sobrien *
1132236769Sobrien * Input:
1133236769Sobrien *	gn		the node of the file to touch
1134236769Sobrien *	silent		TRUE if should not print message
1135236769Sobrien *
1136236769Sobrien * Results:
1137236769Sobrien *	None
1138236769Sobrien *
1139236769Sobrien * Side Effects:
1140236769Sobrien *	The data modification of the file is changed. In addition, if the
1141236769Sobrien *	file did not exist, it is created.
1142236769Sobrien *-----------------------------------------------------------------------
1143236769Sobrien */
1144236769Sobrienvoid
1145236769SobrienJob_Touch(GNode *gn, Boolean silent)
1146236769Sobrien{
1147236769Sobrien    int		  streamID;   	/* ID of stream opened to do the touch */
1148236769Sobrien    struct utimbuf times;	/* Times for utime() call */
1149236769Sobrien
1150236769Sobrien    if (gn->type & (OP_JOIN|OP_USE|OP_USEBEFORE|OP_EXEC|OP_OPTIONAL|
1151236769Sobrien	OP_SPECIAL|OP_PHONY)) {
1152236769Sobrien	/*
1153236769Sobrien	 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets
1154236769Sobrien	 * and, as such, shouldn't really be created.
1155236769Sobrien	 */
1156236769Sobrien	return;
1157236769Sobrien    }
1158236769Sobrien
1159236769Sobrien    if (!silent || NoExecute(gn)) {
1160236769Sobrien	(void)fprintf(stdout, "touch %s\n", gn->name);
1161236769Sobrien	(void)fflush(stdout);
1162236769Sobrien    }
1163236769Sobrien
1164236769Sobrien    if (NoExecute(gn)) {
1165236769Sobrien	return;
1166236769Sobrien    }
1167236769Sobrien
1168236769Sobrien    if (gn->type & OP_ARCHV) {
1169236769Sobrien	Arch_Touch(gn);
1170236769Sobrien    } else if (gn->type & OP_LIB) {
1171236769Sobrien	Arch_TouchLib(gn);
1172236769Sobrien    } else {
1173236769Sobrien	char	*file = gn->path ? gn->path : gn->name;
1174236769Sobrien
1175236769Sobrien	times.actime = times.modtime = now;
1176236769Sobrien	if (utime(file, &times) < 0){
1177236769Sobrien	    streamID = open(file, O_RDWR | O_CREAT, 0666);
1178236769Sobrien
1179236769Sobrien	    if (streamID >= 0) {
1180236769Sobrien		char	c;
1181236769Sobrien
1182236769Sobrien		/*
1183236769Sobrien		 * Read and write a byte to the file to change the
1184236769Sobrien		 * modification time, then close the file.
1185236769Sobrien		 */
1186236769Sobrien		if (read(streamID, &c, 1) == 1) {
1187236769Sobrien		    (void)lseek(streamID, (off_t)0, SEEK_SET);
1188236769Sobrien		    (void)write(streamID, &c, 1);
1189236769Sobrien		}
1190236769Sobrien
1191236769Sobrien		(void)close(streamID);
1192236769Sobrien	    } else {
1193236769Sobrien		(void)fprintf(stdout, "*** couldn't touch %s: %s",
1194236769Sobrien			       file, strerror(errno));
1195236769Sobrien		(void)fflush(stdout);
1196236769Sobrien	    }
1197236769Sobrien	}
1198236769Sobrien    }
1199236769Sobrien}
1200236769Sobrien
1201236769Sobrien/*-
1202236769Sobrien *-----------------------------------------------------------------------
1203236769Sobrien * Job_CheckCommands --
1204236769Sobrien *	Make sure the given node has all the commands it needs.
1205236769Sobrien *
1206236769Sobrien * Input:
1207236769Sobrien *	gn		The target whose commands need verifying
1208236769Sobrien *	abortProc	Function to abort with message
1209236769Sobrien *
1210236769Sobrien * Results:
1211236769Sobrien *	TRUE if the commands list is/was ok.
1212236769Sobrien *
1213236769Sobrien * Side Effects:
1214236769Sobrien *	The node will have commands from the .DEFAULT rule added to it
1215236769Sobrien *	if it needs them.
1216236769Sobrien *-----------------------------------------------------------------------
1217236769Sobrien */
1218236769SobrienBoolean
1219236769SobrienJob_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1220236769Sobrien{
1221236769Sobrien    if (OP_NOP(gn->type) && Lst_IsEmpty(gn->commands) &&
1222236769Sobrien	((gn->type & OP_LIB) == 0 || Lst_IsEmpty(gn->children))) {
1223236769Sobrien	/*
1224236769Sobrien	 * No commands. Look for .DEFAULT rule from which we might infer
1225236769Sobrien	 * commands
1226236769Sobrien	 */
1227236769Sobrien	if ((DEFAULT != NULL) && !Lst_IsEmpty(DEFAULT->commands) &&
1228236769Sobrien		(gn->type & OP_SPECIAL) == 0) {
1229236769Sobrien	    char *p1;
1230236769Sobrien	    /*
1231236769Sobrien	     * Make only looks for a .DEFAULT if the node was never the
1232236769Sobrien	     * target of an operator, so that's what we do too. If
1233236769Sobrien	     * a .DEFAULT was given, we substitute its commands for gn's
1234236769Sobrien	     * commands and set the IMPSRC variable to be the target's name
1235236769Sobrien	     * The DEFAULT node acts like a transformation rule, in that
1236236769Sobrien	     * gn also inherits any attributes or sources attached to
1237236769Sobrien	     * .DEFAULT itself.
1238236769Sobrien	     */
1239236769Sobrien	    Make_HandleUse(DEFAULT, gn);
1240236769Sobrien	    Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn, 0);
1241236769Sobrien	    if (p1)
1242236769Sobrien		free(p1);
1243236769Sobrien	} else if (Dir_MTime(gn, 0) == 0 && (gn->type & OP_SPECIAL) == 0) {
1244236769Sobrien	    /*
1245236769Sobrien	     * The node wasn't the target of an operator we have no .DEFAULT
1246236769Sobrien	     * rule to go on and the target doesn't already exist. There's
1247236769Sobrien	     * nothing more we can do for this branch. If the -k flag wasn't
1248236769Sobrien	     * given, we stop in our tracks, otherwise we just don't update
1249236769Sobrien	     * this node's parents so they never get examined.
1250236769Sobrien	     */
1251236769Sobrien	    static const char msg[] = ": don't know how to make";
1252236769Sobrien
1253236769Sobrien	    if (gn->flags & FROM_DEPEND) {
1254236769Sobrien		fprintf(stdout, "%s: ignoring stale %s for %s\n",
1255236769Sobrien			progname, makeDependfile, gn->name);
1256236769Sobrien		return TRUE;
1257236769Sobrien	    }
1258236769Sobrien
1259236769Sobrien	    if (gn->type & OP_OPTIONAL) {
1260236769Sobrien		(void)fprintf(stdout, "%s%s %s (ignored)\n", progname,
1261236769Sobrien		    msg, gn->name);
1262236769Sobrien		(void)fflush(stdout);
1263236769Sobrien	    } else if (keepgoing) {
1264236769Sobrien		(void)fprintf(stdout, "%s%s %s (continuing)\n", progname,
1265236769Sobrien		    msg, gn->name);
1266236769Sobrien		(void)fflush(stdout);
1267236769Sobrien  		return FALSE;
1268236769Sobrien	    } else {
1269236769Sobrien		(*abortProc)("%s%s %s. Stop", progname, msg, gn->name);
1270236769Sobrien		return FALSE;
1271236769Sobrien	    }
1272236769Sobrien	}
1273236769Sobrien    }
1274236769Sobrien    return TRUE;
1275236769Sobrien}
1276236769Sobrien
1277236769Sobrien/*-
1278236769Sobrien *-----------------------------------------------------------------------
1279236769Sobrien * JobExec --
1280236769Sobrien *	Execute the shell for the given job. Called from JobStart
1281236769Sobrien *
1282236769Sobrien * Input:
1283236769Sobrien *	job		Job to execute
1284236769Sobrien *
1285236769Sobrien * Results:
1286236769Sobrien *	None.
1287236769Sobrien *
1288236769Sobrien * Side Effects:
1289236769Sobrien *	A shell is executed, outputs is altered and the Job structure added
1290236769Sobrien *	to the job table.
1291236769Sobrien *
1292236769Sobrien *-----------------------------------------------------------------------
1293236769Sobrien */
1294236769Sobrienstatic void
1295236769SobrienJobExec(Job *job, char **argv)
1296236769Sobrien{
1297236769Sobrien    int	    	  cpid;	    	/* ID of new child */
1298236769Sobrien    sigset_t	  mask;
1299236769Sobrien
1300236769Sobrien    job->flags &= ~JOB_TRACED;
1301236769Sobrien
1302236769Sobrien    if (DEBUG(JOB)) {
1303236769Sobrien	int 	  i;
1304236769Sobrien
1305236769Sobrien	(void)fprintf(debug_file, "Running %s %sly\n", job->node->name, "local");
1306236769Sobrien	(void)fprintf(debug_file, "\tCommand: ");
1307236769Sobrien	for (i = 0; argv[i] != NULL; i++) {
1308236769Sobrien	    (void)fprintf(debug_file, "%s ", argv[i]);
1309236769Sobrien	}
1310236769Sobrien 	(void)fprintf(debug_file, "\n");
1311236769Sobrien    }
1312236769Sobrien
1313236769Sobrien    /*
1314236769Sobrien     * Some jobs produce no output and it's disconcerting to have
1315236769Sobrien     * no feedback of their running (since they produce no output, the
1316236769Sobrien     * banner with their name in it never appears). This is an attempt to
1317236769Sobrien     * provide that feedback, even if nothing follows it.
1318236769Sobrien     */
1319236769Sobrien    if ((lastNode != job->node) && !(job->flags & JOB_SILENT)) {
1320236769Sobrien	MESSAGE(stdout, job->node);
1321236769Sobrien	lastNode = job->node;
1322236769Sobrien    }
1323236769Sobrien
1324236769Sobrien    /* No interruptions until this job is on the `jobs' list */
1325236769Sobrien    JobSigLock(&mask);
1326236769Sobrien
1327236769Sobrien    /* Pre-emptively mark job running, pid still zero though */
1328236769Sobrien    job->job_state = JOB_ST_RUNNING;
1329236769Sobrien
1330236769Sobrien    cpid = vFork();
1331236769Sobrien    if (cpid == -1)
1332236769Sobrien	Punt("Cannot vfork: %s", strerror(errno));
1333236769Sobrien
1334236769Sobrien    if (cpid == 0) {
1335236769Sobrien	/* Child */
1336236769Sobrien	sigset_t tmask;
1337236769Sobrien
1338236769Sobrien#ifdef USE_META
1339236769Sobrien	if (useMeta) {
1340236769Sobrien	    meta_job_child(job);
1341236769Sobrien	}
1342236769Sobrien#endif
1343236769Sobrien	/*
1344236769Sobrien	 * Reset all signal handlers; this is necessary because we also
1345236769Sobrien	 * need to unblock signals before we exec(2).
1346236769Sobrien	 */
1347236769Sobrien	JobSigReset();
1348236769Sobrien
1349236769Sobrien	/* Now unblock signals */
1350236769Sobrien	sigemptyset(&tmask);
1351236769Sobrien	JobSigUnlock(&tmask);
1352236769Sobrien
1353236769Sobrien	/*
1354236769Sobrien	 * Must duplicate the input stream down to the child's input and
1355236769Sobrien	 * reset it to the beginning (again). Since the stream was marked
1356236769Sobrien	 * close-on-exec, we must clear that bit in the new input.
1357236769Sobrien	 */
1358236769Sobrien	if (dup2(FILENO(job->cmdFILE), 0) == -1) {
1359236769Sobrien	    execError("dup2", "job->cmdFILE");
1360236769Sobrien	    _exit(1);
1361236769Sobrien	}
1362236769Sobrien	(void)fcntl(0, F_SETFD, 0);
1363236769Sobrien	(void)lseek(0, (off_t)0, SEEK_SET);
1364236769Sobrien
1365236769Sobrien	if (job->node->type & OP_MAKE) {
1366236769Sobrien		/*
1367236769Sobrien		 * Pass job token pipe to submakes.
1368236769Sobrien		 */
1369236769Sobrien		fcntl(tokenWaitJob.inPipe, F_SETFD, 0);
1370236769Sobrien		fcntl(tokenWaitJob.outPipe, F_SETFD, 0);
1371236769Sobrien	}
1372236769Sobrien
1373236769Sobrien	/*
1374236769Sobrien	 * Set up the child's output to be routed through the pipe
1375236769Sobrien	 * we've created for it.
1376236769Sobrien	 */
1377236769Sobrien	if (dup2(job->outPipe, 1) == -1) {
1378236769Sobrien	    execError("dup2", "job->outPipe");
1379236769Sobrien	    _exit(1);
1380236769Sobrien	}
1381236769Sobrien	/*
1382236769Sobrien	 * The output channels are marked close on exec. This bit was
1383236769Sobrien	 * duplicated by the dup2(on some systems), so we have to clear
1384236769Sobrien	 * it before routing the shell's error output to the same place as
1385236769Sobrien	 * its standard output.
1386236769Sobrien	 */
1387236769Sobrien	(void)fcntl(1, F_SETFD, 0);
1388236769Sobrien	if (dup2(1, 2) == -1) {
1389236769Sobrien	    execError("dup2", "1, 2");
1390236769Sobrien	    _exit(1);
1391236769Sobrien	}
1392236769Sobrien
1393236769Sobrien	/*
1394236769Sobrien	 * We want to switch the child into a different process family so
1395236769Sobrien	 * we can kill it and all its descendants in one fell swoop,
1396236769Sobrien	 * by killing its process family, but not commit suicide.
1397236769Sobrien	 */
1398236769Sobrien#if defined(HAVE_SETPGID)
1399236769Sobrien	(void)setpgid(0, getpid());
1400236769Sobrien#else
1401236769Sobrien#if defined(HAVE_SETSID)
1402236769Sobrien	/* XXX: dsl - I'm sure this should be setpgrp()... */
1403236769Sobrien	(void)setsid();
1404236769Sobrien#else
1405236769Sobrien	(void)setpgrp(0, getpid());
1406236769Sobrien#endif
1407236769Sobrien#endif
1408236769Sobrien
1409236769Sobrien	Var_ExportVars();
1410236769Sobrien
1411236769Sobrien	(void)execv(shellPath, argv);
1412236769Sobrien	execError("exec", shellPath);
1413236769Sobrien	_exit(1);
1414236769Sobrien    }
1415236769Sobrien
1416236769Sobrien    /* Parent, continuing after the child exec */
1417236769Sobrien    job->pid = cpid;
1418236769Sobrien
1419236769Sobrien    Trace_Log(JOBSTART, job);
1420236769Sobrien
1421236769Sobrien    /*
1422236769Sobrien     * Set the current position in the buffer to the beginning
1423236769Sobrien     * and mark another stream to watch in the outputs mask
1424236769Sobrien     */
1425236769Sobrien    job->curPos = 0;
1426236769Sobrien
1427236769Sobrien    watchfd(job);
1428236769Sobrien
1429236769Sobrien    if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1430236769Sobrien	(void)fclose(job->cmdFILE);
1431236769Sobrien	job->cmdFILE = NULL;
1432236769Sobrien    }
1433236769Sobrien
1434236769Sobrien    /*
1435236769Sobrien     * Now the job is actually running, add it to the table.
1436236769Sobrien     */
1437236769Sobrien    if (DEBUG(JOB)) {
1438236769Sobrien	fprintf(debug_file, "JobExec(%s): pid %d added to jobs table\n",
1439236769Sobrien		job->node->name, job->pid);
1440236769Sobrien	job_table_dump("job started");
1441236769Sobrien    }
1442236769Sobrien    JobSigUnlock(&mask);
1443236769Sobrien}
1444236769Sobrien
1445236769Sobrien/*-
1446236769Sobrien *-----------------------------------------------------------------------
1447236769Sobrien * JobMakeArgv --
1448236769Sobrien *	Create the argv needed to execute the shell for a given job.
1449236769Sobrien *
1450236769Sobrien *
1451236769Sobrien * Results:
1452236769Sobrien *
1453236769Sobrien * Side Effects:
1454236769Sobrien *
1455236769Sobrien *-----------------------------------------------------------------------
1456236769Sobrien */
1457236769Sobrienstatic void
1458236769SobrienJobMakeArgv(Job *job, char **argv)
1459236769Sobrien{
1460236769Sobrien    int	    	  argc;
1461236769Sobrien    static char args[10]; 	/* For merged arguments */
1462236769Sobrien
1463236769Sobrien    argv[0] = UNCONST(shellName);
1464236769Sobrien    argc = 1;
1465236769Sobrien
1466236769Sobrien    if ((commandShell->exit && (*commandShell->exit != '-')) ||
1467236769Sobrien	(commandShell->echo && (*commandShell->echo != '-')))
1468236769Sobrien    {
1469236769Sobrien	/*
1470236769Sobrien	 * At least one of the flags doesn't have a minus before it, so
1471236769Sobrien	 * merge them together. Have to do this because the *(&(@*#*&#$#
1472236769Sobrien	 * Bourne shell thinks its second argument is a file to source.
1473236769Sobrien	 * Grrrr. Note the ten-character limitation on the combined arguments.
1474236769Sobrien	 */
1475236769Sobrien	(void)snprintf(args, sizeof(args), "-%s%s",
1476236769Sobrien		      ((job->flags & JOB_IGNERR) ? "" :
1477236769Sobrien		       (commandShell->exit ? commandShell->exit : "")),
1478236769Sobrien		      ((job->flags & JOB_SILENT) ? "" :
1479236769Sobrien		       (commandShell->echo ? commandShell->echo : "")));
1480236769Sobrien
1481236769Sobrien	if (args[1]) {
1482236769Sobrien	    argv[argc] = args;
1483236769Sobrien	    argc++;
1484236769Sobrien	}
1485236769Sobrien    } else {
1486236769Sobrien	if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1487236769Sobrien	    argv[argc] = UNCONST(commandShell->exit);
1488236769Sobrien	    argc++;
1489236769Sobrien	}
1490236769Sobrien	if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1491236769Sobrien	    argv[argc] = UNCONST(commandShell->echo);
1492236769Sobrien	    argc++;
1493236769Sobrien	}
1494236769Sobrien    }
1495236769Sobrien    argv[argc] = NULL;
1496236769Sobrien}
1497236769Sobrien
1498236769Sobrien/*-
1499236769Sobrien *-----------------------------------------------------------------------
1500236769Sobrien * JobStart  --
1501236769Sobrien *	Start a target-creation process going for the target described
1502236769Sobrien *	by the graph node gn.
1503236769Sobrien *
1504236769Sobrien * Input:
1505236769Sobrien *	gn		target to create
1506236769Sobrien *	flags		flags for the job to override normal ones.
1507236769Sobrien *			e.g. JOB_SPECIAL or JOB_IGNDOTS
1508236769Sobrien *	previous	The previous Job structure for this node, if any.
1509236769Sobrien *
1510236769Sobrien * Results:
1511236769Sobrien *	JOB_ERROR if there was an error in the commands, JOB_FINISHED
1512236769Sobrien *	if there isn't actually anything left to do for the job and
1513236769Sobrien *	JOB_RUNNING if the job has been started.
1514236769Sobrien *
1515236769Sobrien * Side Effects:
1516236769Sobrien *	A new Job node is created and added to the list of running
1517236769Sobrien *	jobs. PMake is forked and a child shell created.
1518236769Sobrien *
1519236769Sobrien * NB: I'm fairly sure that this code is never called with JOB_SPECIAL set
1520236769Sobrien *     JOB_IGNDOTS is never set (dsl)
1521236769Sobrien *     Also the return value is ignored by everyone.
1522236769Sobrien *-----------------------------------------------------------------------
1523236769Sobrien */
1524236769Sobrienstatic int
1525236769SobrienJobStart(GNode *gn, int flags)
1526236769Sobrien{
1527236769Sobrien    Job		  *job;       /* new job descriptor */
1528236769Sobrien    char	  *argv[10];  /* Argument vector to shell */
1529236769Sobrien    Boolean	  cmdsOK;     /* true if the nodes commands were all right */
1530236769Sobrien    Boolean 	  noExec;     /* Set true if we decide not to run the job */
1531236769Sobrien    int		  tfd;	      /* File descriptor to the temp file */
1532236769Sobrien
1533236769Sobrien    for (job = job_table; job < job_table_end; job++) {
1534236769Sobrien	if (job->job_state == JOB_ST_FREE)
1535236769Sobrien	    break;
1536236769Sobrien    }
1537236769Sobrien    if (job >= job_table_end)
1538236769Sobrien	Punt("JobStart no job slots vacant");
1539236769Sobrien
1540236769Sobrien    memset(job, 0, sizeof *job);
1541236769Sobrien    job->job_state = JOB_ST_SETUP;
1542236769Sobrien    if (gn->type & OP_SPECIAL)
1543236769Sobrien	flags |= JOB_SPECIAL;
1544236769Sobrien
1545236769Sobrien    job->node = gn;
1546236769Sobrien    job->tailCmds = NULL;
1547236769Sobrien
1548236769Sobrien    /*
1549236769Sobrien     * Set the initial value of the flags for this job based on the global
1550236769Sobrien     * ones and the node's attributes... Any flags supplied by the caller
1551236769Sobrien     * are also added to the field.
1552236769Sobrien     */
1553236769Sobrien    job->flags = 0;
1554236769Sobrien    if (Targ_Ignore(gn)) {
1555236769Sobrien	job->flags |= JOB_IGNERR;
1556236769Sobrien    }
1557236769Sobrien    if (Targ_Silent(gn)) {
1558236769Sobrien	job->flags |= JOB_SILENT;
1559236769Sobrien    }
1560236769Sobrien    job->flags |= flags;
1561236769Sobrien
1562236769Sobrien    /*
1563236769Sobrien     * Check the commands now so any attributes from .DEFAULT have a chance
1564236769Sobrien     * to migrate to the node
1565236769Sobrien     */
1566236769Sobrien    cmdsOK = Job_CheckCommands(gn, Error);
1567236769Sobrien
1568236769Sobrien    job->inPollfd = NULL;
1569236769Sobrien    /*
1570236769Sobrien     * If the -n flag wasn't given, we open up OUR (not the child's)
1571236769Sobrien     * temporary file to stuff commands in it. The thing is rd/wr so we don't
1572236769Sobrien     * need to reopen it to feed it to the shell. If the -n flag *was* given,
1573236769Sobrien     * we just set the file to be stdout. Cute, huh?
1574236769Sobrien     */
1575236769Sobrien    if (((gn->type & OP_MAKE) && !(noRecursiveExecute)) ||
1576236769Sobrien	    (!noExecute && !touchFlag)) {
1577236769Sobrien	/*
1578236769Sobrien	 * tfile is the name of a file into which all shell commands are
1579236769Sobrien	 * put. It is removed before the child shell is executed, unless
1580236769Sobrien	 * DEBUG(SCRIPT) is set.
1581236769Sobrien	 */
1582236769Sobrien	char *tfile;
1583236769Sobrien	sigset_t mask;
1584236769Sobrien	/*
1585236769Sobrien	 * We're serious here, but if the commands were bogus, we're
1586236769Sobrien	 * also dead...
1587236769Sobrien	 */
1588236769Sobrien	if (!cmdsOK) {
1589236769Sobrien	    PrintOnError(gn, NULL);	/* provide some clue */
1590236769Sobrien	    DieHorribly();
1591236769Sobrien	}
1592236769Sobrien
1593236769Sobrien	JobSigLock(&mask);
1594236769Sobrien	tfd = mkTempFile(TMPPAT, &tfile);
1595236769Sobrien	if (!DEBUG(SCRIPT))
1596236769Sobrien		(void)eunlink(tfile);
1597236769Sobrien	JobSigUnlock(&mask);
1598236769Sobrien
1599236769Sobrien	job->cmdFILE = fdopen(tfd, "w+");
1600236769Sobrien	if (job->cmdFILE == NULL) {
1601236769Sobrien	    Punt("Could not fdopen %s", tfile);
1602236769Sobrien	}
1603236769Sobrien	(void)fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1604236769Sobrien	/*
1605236769Sobrien	 * Send the commands to the command file, flush all its buffers then
1606236769Sobrien	 * rewind and remove the thing.
1607236769Sobrien	 */
1608236769Sobrien	noExec = FALSE;
1609236769Sobrien
1610236769Sobrien#ifdef USE_META
1611236769Sobrien	if (useMeta) {
1612236769Sobrien	    meta_job_start(job, gn);
1613236769Sobrien	    if (Targ_Silent(gn)) {	/* might have changed */
1614236769Sobrien		job->flags |= JOB_SILENT;
1615236769Sobrien	    }
1616236769Sobrien	}
1617236769Sobrien#endif
1618236769Sobrien	/*
1619236769Sobrien	 * We can do all the commands at once. hooray for sanity
1620236769Sobrien	 */
1621236769Sobrien	numCommands = 0;
1622236769Sobrien	Lst_ForEach(gn->commands, JobPrintCommand, job);
1623236769Sobrien
1624236769Sobrien	/*
1625236769Sobrien	 * If we didn't print out any commands to the shell script,
1626236769Sobrien	 * there's not much point in executing the shell, is there?
1627236769Sobrien	 */
1628236769Sobrien	if (numCommands == 0) {
1629236769Sobrien	    noExec = TRUE;
1630236769Sobrien	}
1631236769Sobrien
1632236769Sobrien	free(tfile);
1633236769Sobrien    } else if (NoExecute(gn)) {
1634236769Sobrien	/*
1635236769Sobrien	 * Not executing anything -- just print all the commands to stdout
1636236769Sobrien	 * in one fell swoop. This will still set up job->tailCmds correctly.
1637236769Sobrien	 */
1638236769Sobrien	if (lastNode != gn) {
1639236769Sobrien	    MESSAGE(stdout, gn);
1640236769Sobrien	    lastNode = gn;
1641236769Sobrien	}
1642236769Sobrien	job->cmdFILE = stdout;
1643236769Sobrien	/*
1644236769Sobrien	 * Only print the commands if they're ok, but don't die if they're
1645236769Sobrien	 * not -- just let the user know they're bad and keep going. It
1646236769Sobrien	 * doesn't do any harm in this case and may do some good.
1647236769Sobrien	 */
1648236769Sobrien	if (cmdsOK) {
1649236769Sobrien	    Lst_ForEach(gn->commands, JobPrintCommand, job);
1650236769Sobrien	}
1651236769Sobrien	/*
1652236769Sobrien	 * Don't execute the shell, thank you.
1653236769Sobrien	 */
1654236769Sobrien	noExec = TRUE;
1655236769Sobrien    } else {
1656236769Sobrien	/*
1657236769Sobrien	 * Just touch the target and note that no shell should be executed.
1658236769Sobrien	 * Set cmdFILE to stdout to make life easier. Check the commands, too,
1659236769Sobrien	 * but don't die if they're no good -- it does no harm to keep working
1660236769Sobrien	 * up the graph.
1661236769Sobrien	 */
1662236769Sobrien	job->cmdFILE = stdout;
1663236769Sobrien    	Job_Touch(gn, job->flags&JOB_SILENT);
1664236769Sobrien	noExec = TRUE;
1665236769Sobrien    }
1666236769Sobrien    /* Just in case it isn't already... */
1667236769Sobrien    (void)fflush(job->cmdFILE);
1668236769Sobrien
1669236769Sobrien    /*
1670236769Sobrien     * If we're not supposed to execute a shell, don't.
1671236769Sobrien     */
1672236769Sobrien    if (noExec) {
1673236769Sobrien	if (!(job->flags & JOB_SPECIAL))
1674236769Sobrien	    Job_TokenReturn();
1675236769Sobrien	/*
1676236769Sobrien	 * Unlink and close the command file if we opened one
1677236769Sobrien	 */
1678236769Sobrien	if (job->cmdFILE != stdout) {
1679236769Sobrien	    if (job->cmdFILE != NULL) {
1680236769Sobrien		(void)fclose(job->cmdFILE);
1681236769Sobrien		job->cmdFILE = NULL;
1682236769Sobrien	    }
1683236769Sobrien	}
1684236769Sobrien
1685236769Sobrien	/*
1686236769Sobrien	 * We only want to work our way up the graph if we aren't here because
1687236769Sobrien	 * the commands for the job were no good.
1688236769Sobrien	 */
1689236769Sobrien	if (cmdsOK && aborting == 0) {
1690236769Sobrien	    if (job->tailCmds != NULL) {
1691236769Sobrien		Lst_ForEachFrom(job->node->commands, job->tailCmds,
1692236769Sobrien				JobSaveCommand,
1693236769Sobrien			       job->node);
1694236769Sobrien	    }
1695236769Sobrien	    job->node->made = MADE;
1696236769Sobrien	    Make_Update(job->node);
1697236769Sobrien	}
1698236769Sobrien	job->job_state = JOB_ST_FREE;
1699236769Sobrien	return cmdsOK ? JOB_FINISHED : JOB_ERROR;
1700236769Sobrien    }
1701236769Sobrien
1702236769Sobrien    /*
1703236769Sobrien     * Set up the control arguments to the shell. This is based on the flags
1704236769Sobrien     * set earlier for this job.
1705236769Sobrien     */
1706236769Sobrien    JobMakeArgv(job, argv);
1707236769Sobrien
1708236769Sobrien    /* Create the pipe by which we'll get the shell's output.  */
1709236769Sobrien    JobCreatePipe(job, 3);
1710236769Sobrien
1711236769Sobrien    JobExec(job, argv);
1712236769Sobrien    return(JOB_RUNNING);
1713236769Sobrien}
1714236769Sobrien
1715236769Sobrienstatic char *
1716236769SobrienJobOutput(Job *job, char *cp, char *endp, int msg)
1717236769Sobrien{
1718236769Sobrien    char *ecp;
1719236769Sobrien
1720236769Sobrien    if (commandShell->noPrint) {
1721236769Sobrien	ecp = Str_FindSubstring(cp, commandShell->noPrint);
1722236769Sobrien	while (ecp != NULL) {
1723236769Sobrien	    if (cp != ecp) {
1724236769Sobrien		*ecp = '\0';
1725236769Sobrien		if (!beSilent && msg && job->node != lastNode) {
1726236769Sobrien		    MESSAGE(stdout, job->node);
1727236769Sobrien		    lastNode = job->node;
1728236769Sobrien		}
1729236769Sobrien		/*
1730236769Sobrien		 * The only way there wouldn't be a newline after
1731236769Sobrien		 * this line is if it were the last in the buffer.
1732236769Sobrien		 * however, since the non-printable comes after it,
1733236769Sobrien		 * there must be a newline, so we don't print one.
1734236769Sobrien		 */
1735236769Sobrien		(void)fprintf(stdout, "%s", cp);
1736236769Sobrien		(void)fflush(stdout);
1737236769Sobrien	    }
1738236769Sobrien	    cp = ecp + commandShell->noPLen;
1739236769Sobrien	    if (cp != endp) {
1740236769Sobrien		/*
1741236769Sobrien		 * Still more to print, look again after skipping
1742236769Sobrien		 * the whitespace following the non-printable
1743236769Sobrien		 * command....
1744236769Sobrien		 */
1745236769Sobrien		cp++;
1746236769Sobrien		while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
1747236769Sobrien		    cp++;
1748236769Sobrien		}
1749236769Sobrien		ecp = Str_FindSubstring(cp, commandShell->noPrint);
1750236769Sobrien	    } else {
1751236769Sobrien		return cp;
1752236769Sobrien	    }
1753236769Sobrien	}
1754236769Sobrien    }
1755236769Sobrien    return cp;
1756236769Sobrien}
1757236769Sobrien
1758236769Sobrien/*-
1759236769Sobrien *-----------------------------------------------------------------------
1760236769Sobrien * JobDoOutput  --
1761236769Sobrien *	This function is called at different times depending on
1762236769Sobrien *	whether the user has specified that output is to be collected
1763236769Sobrien *	via pipes or temporary files. In the former case, we are called
1764236769Sobrien *	whenever there is something to read on the pipe. We collect more
1765236769Sobrien *	output from the given job and store it in the job's outBuf. If
1766236769Sobrien *	this makes up a line, we print it tagged by the job's identifier,
1767236769Sobrien *	as necessary.
1768236769Sobrien *	If output has been collected in a temporary file, we open the
1769236769Sobrien *	file and read it line by line, transfering it to our own
1770236769Sobrien *	output channel until the file is empty. At which point we
1771236769Sobrien *	remove the temporary file.
1772236769Sobrien *	In both cases, however, we keep our figurative eye out for the
1773236769Sobrien *	'noPrint' line for the shell from which the output came. If
1774236769Sobrien *	we recognize a line, we don't print it. If the command is not
1775236769Sobrien *	alone on the line (the character after it is not \0 or \n), we
1776236769Sobrien *	do print whatever follows it.
1777236769Sobrien *
1778236769Sobrien * Input:
1779236769Sobrien *	job		the job whose output needs printing
1780236769Sobrien *	finish		TRUE if this is the last time we'll be called
1781236769Sobrien *			for this job
1782236769Sobrien *
1783236769Sobrien * Results:
1784236769Sobrien *	None
1785236769Sobrien *
1786236769Sobrien * Side Effects:
1787236769Sobrien *	curPos may be shifted as may the contents of outBuf.
1788236769Sobrien *-----------------------------------------------------------------------
1789236769Sobrien */
1790236769SobrienSTATIC void
1791236769SobrienJobDoOutput(Job *job, Boolean finish)
1792236769Sobrien{
1793236769Sobrien    Boolean       gotNL = FALSE;  /* true if got a newline */
1794236769Sobrien    Boolean       fbuf;  	  /* true if our buffer filled up */
1795236769Sobrien    int		  nr;	      	  /* number of bytes read */
1796236769Sobrien    int		  i;	      	  /* auxiliary index into outBuf */
1797236769Sobrien    int		  max;	      	  /* limit for i (end of current data) */
1798236769Sobrien    int		  nRead;      	  /* (Temporary) number of bytes read */
1799236769Sobrien
1800236769Sobrien    /*
1801236769Sobrien     * Read as many bytes as will fit in the buffer.
1802236769Sobrien     */
1803236769Sobrienend_loop:
1804236769Sobrien    gotNL = FALSE;
1805236769Sobrien    fbuf = FALSE;
1806236769Sobrien
1807236769Sobrien    nRead = read(job->inPipe, &job->outBuf[job->curPos],
1808236769Sobrien		     JOB_BUFSIZE - job->curPos);
1809236769Sobrien    if (nRead < 0) {
1810236769Sobrien	if (errno == EAGAIN)
1811236769Sobrien	    return;
1812236769Sobrien	if (DEBUG(JOB)) {
1813236769Sobrien	    perror("JobDoOutput(piperead)");
1814236769Sobrien	}
1815236769Sobrien	nr = 0;
1816236769Sobrien    } else {
1817236769Sobrien	nr = nRead;
1818236769Sobrien    }
1819236769Sobrien
1820236769Sobrien    /*
1821236769Sobrien     * If we hit the end-of-file (the job is dead), we must flush its
1822236769Sobrien     * remaining output, so pretend we read a newline if there's any
1823236769Sobrien     * output remaining in the buffer.
1824236769Sobrien     * Also clear the 'finish' flag so we stop looping.
1825236769Sobrien     */
1826236769Sobrien    if ((nr == 0) && (job->curPos != 0)) {
1827236769Sobrien	job->outBuf[job->curPos] = '\n';
1828236769Sobrien	nr = 1;
1829236769Sobrien	finish = FALSE;
1830236769Sobrien    } else if (nr == 0) {
1831236769Sobrien	finish = FALSE;
1832236769Sobrien    }
1833236769Sobrien
1834236769Sobrien    /*
1835236769Sobrien     * Look for the last newline in the bytes we just got. If there is
1836236769Sobrien     * one, break out of the loop with 'i' as its index and gotNL set
1837236769Sobrien     * TRUE.
1838236769Sobrien     */
1839236769Sobrien    max = job->curPos + nr;
1840236769Sobrien    for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1841236769Sobrien	if (job->outBuf[i] == '\n') {
1842236769Sobrien	    gotNL = TRUE;
1843236769Sobrien	    break;
1844236769Sobrien	} else if (job->outBuf[i] == '\0') {
1845236769Sobrien	    /*
1846236769Sobrien	     * Why?
1847236769Sobrien	     */
1848236769Sobrien	    job->outBuf[i] = ' ';
1849236769Sobrien	}
1850236769Sobrien    }
1851236769Sobrien
1852236769Sobrien    if (!gotNL) {
1853236769Sobrien	job->curPos += nr;
1854236769Sobrien	if (job->curPos == JOB_BUFSIZE) {
1855236769Sobrien	    /*
1856236769Sobrien	     * If we've run out of buffer space, we have no choice
1857236769Sobrien	     * but to print the stuff. sigh.
1858236769Sobrien	     */
1859236769Sobrien	    fbuf = TRUE;
1860236769Sobrien	    i = job->curPos;
1861236769Sobrien	}
1862236769Sobrien    }
1863236769Sobrien    if (gotNL || fbuf) {
1864236769Sobrien	/*
1865236769Sobrien	 * Need to send the output to the screen. Null terminate it
1866236769Sobrien	 * first, overwriting the newline character if there was one.
1867236769Sobrien	 * So long as the line isn't one we should filter (according
1868236769Sobrien	 * to the shell description), we print the line, preceded
1869236769Sobrien	 * by a target banner if this target isn't the same as the
1870236769Sobrien	 * one for which we last printed something.
1871236769Sobrien	 * The rest of the data in the buffer are then shifted down
1872236769Sobrien	 * to the start of the buffer and curPos is set accordingly.
1873236769Sobrien	 */
1874236769Sobrien	job->outBuf[i] = '\0';
1875236769Sobrien	if (i >= job->curPos) {
1876236769Sobrien	    char *cp;
1877236769Sobrien
1878236769Sobrien	    cp = JobOutput(job, job->outBuf, &job->outBuf[i], FALSE);
1879236769Sobrien
1880236769Sobrien	    /*
1881236769Sobrien	     * There's still more in that thar buffer. This time, though,
1882236769Sobrien	     * we know there's no newline at the end, so we add one of
1883236769Sobrien	     * our own free will.
1884236769Sobrien	     */
1885236769Sobrien	    if (*cp != '\0') {
1886236769Sobrien		if (!beSilent && job->node != lastNode) {
1887236769Sobrien		    MESSAGE(stdout, job->node);
1888236769Sobrien		    lastNode = job->node;
1889236769Sobrien		}
1890236769Sobrien#ifdef USE_META
1891236769Sobrien		if (useMeta) {
1892236769Sobrien		    meta_job_output(job, cp, gotNL ? "\n" : "");
1893236769Sobrien		}
1894236769Sobrien#endif
1895236769Sobrien		(void)fprintf(stdout, "%s%s", cp, gotNL ? "\n" : "");
1896236769Sobrien		(void)fflush(stdout);
1897236769Sobrien	    }
1898236769Sobrien	}
1899236769Sobrien	if (i < max - 1) {
1900236769Sobrien	    /* shift the remaining characters down */
1901236769Sobrien	    (void)memcpy(job->outBuf, &job->outBuf[i + 1], max - (i + 1));
1902236769Sobrien	    job->curPos = max - (i + 1);
1903236769Sobrien
1904236769Sobrien	} else {
1905236769Sobrien	    /*
1906236769Sobrien	     * We have written everything out, so we just start over
1907236769Sobrien	     * from the start of the buffer. No copying. No nothing.
1908236769Sobrien	     */
1909236769Sobrien	    job->curPos = 0;
1910236769Sobrien	}
1911236769Sobrien    }
1912236769Sobrien    if (finish) {
1913236769Sobrien	/*
1914236769Sobrien	 * If the finish flag is true, we must loop until we hit
1915236769Sobrien	 * end-of-file on the pipe. This is guaranteed to happen
1916236769Sobrien	 * eventually since the other end of the pipe is now closed
1917236769Sobrien	 * (we closed it explicitly and the child has exited). When
1918236769Sobrien	 * we do get an EOF, finish will be set FALSE and we'll fall
1919236769Sobrien	 * through and out.
1920236769Sobrien	 */
1921236769Sobrien	goto end_loop;
1922236769Sobrien    }
1923236769Sobrien}
1924236769Sobrien
1925236769Sobrienstatic void
1926236769SobrienJobRun(GNode *targ)
1927236769Sobrien{
1928236769Sobrien#ifdef notyet
1929236769Sobrien    /*
1930236769Sobrien     * Unfortunately it is too complicated to run .BEGIN, .END,
1931236769Sobrien     * and .INTERRUPT job in the parallel job module. This has
1932236769Sobrien     * the nice side effect that it avoids a lot of other problems.
1933236769Sobrien     */
1934236769Sobrien    Lst lst = Lst_Init(FALSE);
1935236769Sobrien    Lst_AtEnd(lst, targ);
1936236769Sobrien    (void)Make_Run(lst);
1937236769Sobrien    Lst_Destroy(lst, NULL);
1938236769Sobrien    JobStart(targ, JOB_SPECIAL);
1939236769Sobrien    while (jobTokensRunning) {
1940236769Sobrien	Job_CatchOutput();
1941236769Sobrien    }
1942236769Sobrien#else
1943236769Sobrien    Compat_Make(targ, targ);
1944236769Sobrien    if (targ->made == ERROR) {
1945236769Sobrien	PrintOnError(targ, "\n\nStop.");
1946236769Sobrien	exit(1);
1947236769Sobrien    }
1948236769Sobrien#endif
1949236769Sobrien}
1950236769Sobrien
1951236769Sobrien/*-
1952236769Sobrien *-----------------------------------------------------------------------
1953236769Sobrien * Job_CatchChildren --
1954236769Sobrien *	Handle the exit of a child. Called from Make_Make.
1955236769Sobrien *
1956236769Sobrien * Input:
1957236769Sobrien *	block		TRUE if should block on the wait
1958236769Sobrien *
1959236769Sobrien * Results:
1960236769Sobrien *	none.
1961236769Sobrien *
1962236769Sobrien * Side Effects:
1963236769Sobrien *	The job descriptor is removed from the list of children.
1964236769Sobrien *
1965236769Sobrien * Notes:
1966236769Sobrien *	We do waits, blocking or not, according to the wisdom of our
1967236769Sobrien *	caller, until there are no more children to report. For each
1968236769Sobrien *	job, call JobFinish to finish things off.
1969236769Sobrien *
1970236769Sobrien *-----------------------------------------------------------------------
1971236769Sobrien */
1972236769Sobrien
1973236769Sobrienvoid
1974236769SobrienJob_CatchChildren(void)
1975236769Sobrien{
1976236769Sobrien    int    	  pid;	    	/* pid of dead child */
1977236769Sobrien    WAIT_T	  status;   	/* Exit/termination status */
1978236769Sobrien
1979236769Sobrien    /*
1980236769Sobrien     * Don't even bother if we know there's no one around.
1981236769Sobrien     */
1982236769Sobrien    if (jobTokensRunning == 0)
1983236769Sobrien	return;
1984236769Sobrien
1985236769Sobrien    while ((pid = waitpid((pid_t) -1, &status, WNOHANG | WUNTRACED)) > 0) {
1986236769Sobrien	if (DEBUG(JOB)) {
1987236769Sobrien	    (void)fprintf(debug_file, "Process %d exited/stopped status %x.\n", pid,
1988236769Sobrien	      WAIT_STATUS(status));
1989236769Sobrien	}
1990236769Sobrien	JobReapChild(pid, status, TRUE);
1991236769Sobrien    }
1992236769Sobrien}
1993236769Sobrien
1994236769Sobrien/*
1995236769Sobrien * It is possible that wait[pid]() was called from elsewhere,
1996236769Sobrien * this lets us reap jobs regardless.
1997236769Sobrien */
1998236769Sobrienvoid
1999236769SobrienJobReapChild(pid_t pid, WAIT_T status, Boolean isJobs)
2000236769Sobrien{
2001236769Sobrien    Job		  *job;	    	/* job descriptor for dead child */
2002236769Sobrien
2003236769Sobrien    /*
2004236769Sobrien     * Don't even bother if we know there's no one around.
2005236769Sobrien     */
2006236769Sobrien    if (jobTokensRunning == 0)
2007236769Sobrien	return;
2008236769Sobrien
2009236769Sobrien    job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
2010236769Sobrien    if (job == NULL) {
2011236769Sobrien	if (isJobs) {
2012236769Sobrien	    if (!lurking_children)
2013236769Sobrien		Error("Child (%d) status %x not in table?", pid, status);
2014236769Sobrien	}
2015236769Sobrien	return;				/* not ours */
2016236769Sobrien    }
2017236769Sobrien    if (WIFSTOPPED(status)) {
2018236769Sobrien	if (DEBUG(JOB)) {
2019236769Sobrien	    (void)fprintf(debug_file, "Process %d (%s) stopped.\n",
2020236769Sobrien			  job->pid, job->node->name);
2021236769Sobrien	}
2022236769Sobrien	if (!make_suspended) {
2023236769Sobrien	    switch (WSTOPSIG(status)) {
2024236769Sobrien	    case SIGTSTP:
2025236769Sobrien		(void)printf("*** [%s] Suspended\n", job->node->name);
2026236769Sobrien		break;
2027236769Sobrien	    case SIGSTOP:
2028236769Sobrien		(void)printf("*** [%s] Stopped\n", job->node->name);
2029236769Sobrien		break;
2030236769Sobrien	    default:
2031236769Sobrien		(void)printf("*** [%s] Stopped -- signal %d\n",
2032236769Sobrien			     job->node->name, WSTOPSIG(status));
2033236769Sobrien	    }
2034236769Sobrien	    job->job_suspended = 1;
2035236769Sobrien	}
2036236769Sobrien	(void)fflush(stdout);
2037236769Sobrien	return;
2038236769Sobrien    }
2039236769Sobrien
2040236769Sobrien    job->job_state = JOB_ST_FINISHED;
2041236769Sobrien    job->exit_status = WAIT_STATUS(status);
2042236769Sobrien
2043236769Sobrien    JobFinish(job, status);
2044236769Sobrien}
2045236769Sobrien
2046236769Sobrien/*-
2047236769Sobrien *-----------------------------------------------------------------------
2048236769Sobrien * Job_CatchOutput --
2049236769Sobrien *	Catch the output from our children, if we're using
2050236769Sobrien *	pipes do so. Otherwise just block time until we get a
2051236769Sobrien *	signal(most likely a SIGCHLD) since there's no point in
2052236769Sobrien *	just spinning when there's nothing to do and the reaping
2053236769Sobrien *	of a child can wait for a while.
2054236769Sobrien *
2055236769Sobrien * Results:
2056236769Sobrien *	None
2057236769Sobrien *
2058236769Sobrien * Side Effects:
2059236769Sobrien *	Output is read from pipes if we're piping.
2060236769Sobrien * -----------------------------------------------------------------------
2061236769Sobrien */
2062236769Sobrienvoid
2063236769SobrienJob_CatchOutput(void)
2064236769Sobrien{
2065236769Sobrien    int nready;
2066236769Sobrien    Job *job;
2067236769Sobrien    int i;
2068236769Sobrien
2069236769Sobrien    (void)fflush(stdout);
2070236769Sobrien
2071236769Sobrien    /* The first fd in the list is the job token pipe */
2072236769Sobrien    nready = poll(fds + 1 - wantToken, nfds - 1 + wantToken, POLL_MSEC);
2073236769Sobrien
2074236769Sobrien    if (nready < 0 || readyfd(&childExitJob)) {
2075236769Sobrien	char token = 0;
2076236769Sobrien	nready -= 1;
2077236769Sobrien	(void)read(childExitJob.inPipe, &token, 1);
2078236769Sobrien	if (token == DO_JOB_RESUME[0])
2079236769Sobrien	    /* Complete relay requested from our SIGCONT handler */
2080236769Sobrien	    JobRestartJobs();
2081236769Sobrien	Job_CatchChildren();
2082236769Sobrien    }
2083236769Sobrien
2084236769Sobrien    if (nready <= 0)
2085236769Sobrien	return;
2086236769Sobrien
2087236769Sobrien    if (wantToken && readyfd(&tokenWaitJob))
2088236769Sobrien	nready--;
2089236769Sobrien
2090236769Sobrien    for (i = 2; i < nfds; i++) {
2091236769Sobrien	if (!fds[i].revents)
2092236769Sobrien	    continue;
2093236769Sobrien	job = jobfds[i];
2094236769Sobrien	if (job->job_state != JOB_ST_RUNNING)
2095236769Sobrien	    continue;
2096236769Sobrien	JobDoOutput(job, FALSE);
2097236769Sobrien    }
2098236769Sobrien}
2099236769Sobrien
2100236769Sobrien/*-
2101236769Sobrien *-----------------------------------------------------------------------
2102236769Sobrien * Job_Make --
2103236769Sobrien *	Start the creation of a target. Basically a front-end for
2104236769Sobrien *	JobStart used by the Make module.
2105236769Sobrien *
2106236769Sobrien * Results:
2107236769Sobrien *	None.
2108236769Sobrien *
2109236769Sobrien * Side Effects:
2110236769Sobrien *	Another job is started.
2111236769Sobrien *
2112236769Sobrien *-----------------------------------------------------------------------
2113236769Sobrien */
2114236769Sobrienvoid
2115236769SobrienJob_Make(GNode *gn)
2116236769Sobrien{
2117236769Sobrien    (void)JobStart(gn, 0);
2118236769Sobrien}
2119236769Sobrien
2120236769Sobrienvoid
2121236769SobrienShell_Init(void)
2122236769Sobrien{
2123236769Sobrien    if (shellPath == NULL) {
2124236769Sobrien	/*
2125236769Sobrien	 * We are using the default shell, which may be an absolute
2126236769Sobrien	 * path if DEFSHELL_CUSTOM is defined.
2127236769Sobrien	 */
2128236769Sobrien	shellName = commandShell->name;
2129236769Sobrien#ifdef DEFSHELL_CUSTOM
2130236769Sobrien	if (*shellName == '/') {
2131236769Sobrien	    shellPath = shellName;
2132236769Sobrien	    shellName = strrchr(shellPath, '/');
2133236769Sobrien	    shellName++;
2134236769Sobrien	} else
2135236769Sobrien#endif
2136236769Sobrien	shellPath = str_concat(_PATH_DEFSHELLDIR, shellName, STR_ADDSLASH);
2137236769Sobrien    }
2138236769Sobrien    if (commandShell->exit == NULL) {
2139236769Sobrien	commandShell->exit = "";
2140236769Sobrien    }
2141236769Sobrien    if (commandShell->echo == NULL) {
2142236769Sobrien	commandShell->echo = "";
2143236769Sobrien    }
2144236769Sobrien}
2145236769Sobrien
2146236769Sobrien/*-
2147236769Sobrien * Returns the string literal that is used in the current command shell
2148236769Sobrien * to produce a newline character.
2149236769Sobrien */
2150236769Sobrienconst char *
2151236769SobrienShell_GetNewline(void)
2152236769Sobrien{
2153236769Sobrien
2154236769Sobrien    return commandShell->newline;
2155236769Sobrien}
2156236769Sobrien
2157236769Sobrienvoid
2158236769SobrienJob_SetPrefix(void)
2159236769Sobrien{
2160236769Sobrien
2161236769Sobrien    if (targPrefix) {
2162236769Sobrien	free(targPrefix);
2163236769Sobrien    } else if (!Var_Exists(MAKE_JOB_PREFIX, VAR_GLOBAL)) {
2164236769Sobrien	Var_Set(MAKE_JOB_PREFIX, "---", VAR_GLOBAL, 0);
2165236769Sobrien    }
2166236769Sobrien
2167236769Sobrien    targPrefix = Var_Subst(NULL, "${" MAKE_JOB_PREFIX "}", VAR_GLOBAL, 0);
2168236769Sobrien}
2169236769Sobrien
2170236769Sobrien/*-
2171236769Sobrien *-----------------------------------------------------------------------
2172236769Sobrien * Job_Init --
2173236769Sobrien *	Initialize the process module
2174236769Sobrien *
2175236769Sobrien * Input:
2176236769Sobrien *
2177236769Sobrien * Results:
2178236769Sobrien *	none
2179236769Sobrien *
2180236769Sobrien * Side Effects:
2181236769Sobrien *	lists and counters are initialized
2182236769Sobrien *-----------------------------------------------------------------------
2183236769Sobrien */
2184236769Sobrienvoid
2185236769SobrienJob_Init(void)
2186236769Sobrien{
2187236769Sobrien    GNode         *begin;     /* node for commands to do at the very start */
2188236769Sobrien
2189236769Sobrien    /* Allocate space for all the job info */
2190236769Sobrien    job_table = bmake_malloc(maxJobs * sizeof *job_table);
2191236769Sobrien    memset(job_table, 0, maxJobs * sizeof *job_table);
2192236769Sobrien    job_table_end = job_table + maxJobs;
2193236769Sobrien    wantToken =	0;
2194236769Sobrien
2195236769Sobrien    aborting = 	  0;
2196236769Sobrien    errors = 	  0;
2197236769Sobrien
2198236769Sobrien    lastNode =	  NULL;
2199236769Sobrien
2200236769Sobrien    /*
2201236769Sobrien     * There is a non-zero chance that we already have children.
2202236769Sobrien     * eg after 'make -f- <<EOF'
2203236769Sobrien     * Since their termination causes a 'Child (pid) not in table' message,
2204236769Sobrien     * Collect the status of any that are already dead, and suppress the
2205236769Sobrien     * error message if there are any undead ones.
2206236769Sobrien     */
2207236769Sobrien    for (;;) {
2208236769Sobrien	int rval, status;
2209236769Sobrien	rval = waitpid((pid_t) -1, &status, WNOHANG);
2210236769Sobrien	if (rval > 0)
2211236769Sobrien	    continue;
2212236769Sobrien	if (rval == 0)
2213236769Sobrien	    lurking_children = 1;
2214236769Sobrien	break;
2215236769Sobrien    }
2216236769Sobrien
2217236769Sobrien    Shell_Init();
2218236769Sobrien
2219236769Sobrien    JobCreatePipe(&childExitJob, 3);
2220236769Sobrien
2221236769Sobrien    /* We can only need to wait for tokens, children and output from each job */
2222236769Sobrien    fds = bmake_malloc(sizeof (*fds) * (2 + maxJobs));
2223236769Sobrien    jobfds = bmake_malloc(sizeof (*jobfds) * (2 + maxJobs));
2224236769Sobrien
2225236769Sobrien    /* These are permanent entries and take slots 0 and 1 */
2226236769Sobrien    watchfd(&tokenWaitJob);
2227236769Sobrien    watchfd(&childExitJob);
2228236769Sobrien
2229236769Sobrien    sigemptyset(&caught_signals);
2230236769Sobrien    /*
2231236769Sobrien     * Install a SIGCHLD handler.
2232236769Sobrien     */
2233236769Sobrien    (void)bmake_signal(SIGCHLD, JobChildSig);
2234236769Sobrien    sigaddset(&caught_signals, SIGCHLD);
2235236769Sobrien
2236236769Sobrien#define ADDSIG(s,h)				\
2237236769Sobrien    if (bmake_signal(s, SIG_IGN) != SIG_IGN) {	\
2238236769Sobrien	sigaddset(&caught_signals, s);		\
2239236769Sobrien	(void)bmake_signal(s, h);			\
2240236769Sobrien    }
2241236769Sobrien
2242236769Sobrien    /*
2243236769Sobrien     * Catch the four signals that POSIX specifies if they aren't ignored.
2244236769Sobrien     * JobPassSig will take care of calling JobInterrupt if appropriate.
2245236769Sobrien     */
2246236769Sobrien    ADDSIG(SIGINT, JobPassSig_int)
2247236769Sobrien    ADDSIG(SIGHUP, JobPassSig_term)
2248236769Sobrien    ADDSIG(SIGTERM, JobPassSig_term)
2249236769Sobrien    ADDSIG(SIGQUIT, JobPassSig_term)
2250236769Sobrien
2251236769Sobrien    /*
2252236769Sobrien     * There are additional signals that need to be caught and passed if
2253236769Sobrien     * either the export system wants to be told directly of signals or if
2254236769Sobrien     * we're giving each job its own process group (since then it won't get
2255236769Sobrien     * signals from the terminal driver as we own the terminal)
2256236769Sobrien     */
2257236769Sobrien    ADDSIG(SIGTSTP, JobPassSig_suspend)
2258236769Sobrien    ADDSIG(SIGTTOU, JobPassSig_suspend)
2259236769Sobrien    ADDSIG(SIGTTIN, JobPassSig_suspend)
2260236769Sobrien    ADDSIG(SIGWINCH, JobCondPassSig)
2261236769Sobrien    ADDSIG(SIGCONT, JobContinueSig)
2262236769Sobrien#undef ADDSIG
2263236769Sobrien
2264236769Sobrien    begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2265236769Sobrien
2266236769Sobrien    if (begin != NULL) {
2267236769Sobrien	JobRun(begin);
2268236769Sobrien	if (begin->made == ERROR) {
2269236769Sobrien	    PrintOnError(begin, "\n\nStop.");
2270236769Sobrien	    exit(1);
2271236769Sobrien	}
2272236769Sobrien    }
2273236769Sobrien    postCommands = Targ_FindNode(".END", TARG_CREATE);
2274236769Sobrien}
2275236769Sobrien
2276236769Sobrienstatic void JobSigReset(void)
2277236769Sobrien{
2278236769Sobrien#define DELSIG(s)					\
2279236769Sobrien    if (sigismember(&caught_signals, s)) {		\
2280236769Sobrien	(void)bmake_signal(s, SIG_DFL);			\
2281236769Sobrien    }
2282236769Sobrien
2283236769Sobrien    DELSIG(SIGINT)
2284236769Sobrien    DELSIG(SIGHUP)
2285236769Sobrien    DELSIG(SIGQUIT)
2286236769Sobrien    DELSIG(SIGTERM)
2287236769Sobrien    DELSIG(SIGTSTP)
2288236769Sobrien    DELSIG(SIGTTOU)
2289236769Sobrien    DELSIG(SIGTTIN)
2290236769Sobrien    DELSIG(SIGWINCH)
2291236769Sobrien    DELSIG(SIGCONT)
2292236769Sobrien#undef DELSIG
2293236769Sobrien    (void)bmake_signal(SIGCHLD, SIG_DFL);
2294236769Sobrien}
2295236769Sobrien
2296236769Sobrien/*-
2297236769Sobrien *-----------------------------------------------------------------------
2298236769Sobrien * JobMatchShell --
2299236769Sobrien *	Find a shell in 'shells' given its name.
2300236769Sobrien *
2301236769Sobrien * Results:
2302236769Sobrien *	A pointer to the Shell structure.
2303236769Sobrien *
2304236769Sobrien * Side Effects:
2305236769Sobrien *	None.
2306236769Sobrien *
2307236769Sobrien *-----------------------------------------------------------------------
2308236769Sobrien */
2309236769Sobrienstatic Shell *
2310236769SobrienJobMatchShell(const char *name)
2311236769Sobrien{
2312236769Sobrien    Shell	*sh;
2313236769Sobrien
2314236769Sobrien    for (sh = shells; sh->name != NULL; sh++) {
2315236769Sobrien	if (strcmp(name, sh->name) == 0)
2316236769Sobrien		return (sh);
2317236769Sobrien    }
2318236769Sobrien    return NULL;
2319236769Sobrien}
2320236769Sobrien
2321236769Sobrien/*-
2322236769Sobrien *-----------------------------------------------------------------------
2323236769Sobrien * Job_ParseShell --
2324236769Sobrien *	Parse a shell specification and set up commandShell, shellPath
2325236769Sobrien *	and shellName appropriately.
2326236769Sobrien *
2327236769Sobrien * Input:
2328236769Sobrien *	line		The shell spec
2329236769Sobrien *
2330236769Sobrien * Results:
2331236769Sobrien *	FAILURE if the specification was incorrect.
2332236769Sobrien *
2333236769Sobrien * Side Effects:
2334236769Sobrien *	commandShell points to a Shell structure (either predefined or
2335236769Sobrien *	created from the shell spec), shellPath is the full path of the
2336236769Sobrien *	shell described by commandShell, while shellName is just the
2337236769Sobrien *	final component of shellPath.
2338236769Sobrien *
2339236769Sobrien * Notes:
2340236769Sobrien *	A shell specification consists of a .SHELL target, with dependency
2341236769Sobrien *	operator, followed by a series of blank-separated words. Double
2342236769Sobrien *	quotes can be used to use blanks in words. A backslash escapes
2343236769Sobrien *	anything (most notably a double-quote and a space) and
2344236769Sobrien *	provides the functionality it does in C. Each word consists of
2345236769Sobrien *	keyword and value separated by an equal sign. There should be no
2346236769Sobrien *	unnecessary spaces in the word. The keywords are as follows:
2347236769Sobrien *	    name  	    Name of shell.
2348236769Sobrien *	    path  	    Location of shell.
2349236769Sobrien *	    quiet 	    Command to turn off echoing.
2350236769Sobrien *	    echo  	    Command to turn echoing on
2351236769Sobrien *	    filter	    Result of turning off echoing that shouldn't be
2352236769Sobrien *	    	  	    printed.
2353236769Sobrien *	    echoFlag	    Flag to turn echoing on at the start
2354236769Sobrien *	    errFlag	    Flag to turn error checking on at the start
2355236769Sobrien *	    hasErrCtl	    True if shell has error checking control
2356236769Sobrien *	    newline	    String literal to represent a newline char
2357236769Sobrien *	    check 	    Command to turn on error checking if hasErrCtl
2358236769Sobrien *	    	  	    is TRUE or template of command to echo a command
2359236769Sobrien *	    	  	    for which error checking is off if hasErrCtl is
2360236769Sobrien *	    	  	    FALSE.
2361236769Sobrien *	    ignore	    Command to turn off error checking if hasErrCtl
2362236769Sobrien *	    	  	    is TRUE or template of command to execute a
2363236769Sobrien *	    	  	    command so as to ignore any errors it returns if
2364236769Sobrien *	    	  	    hasErrCtl is FALSE.
2365236769Sobrien *
2366236769Sobrien *-----------------------------------------------------------------------
2367236769Sobrien */
2368236769SobrienReturnStatus
2369236769SobrienJob_ParseShell(char *line)
2370236769Sobrien{
2371236769Sobrien    char	**words;
2372236769Sobrien    char	**argv;
2373236769Sobrien    int		argc;
2374236769Sobrien    char	*path;
2375236769Sobrien    Shell	newShell;
2376236769Sobrien    Boolean	fullSpec = FALSE;
2377236769Sobrien    Shell	*sh;
2378236769Sobrien
2379236769Sobrien    while (isspace((unsigned char)*line)) {
2380236769Sobrien	line++;
2381236769Sobrien    }
2382236769Sobrien
2383236769Sobrien    if (shellArgv)
2384236769Sobrien	free(UNCONST(shellArgv));
2385236769Sobrien
2386236769Sobrien    memset(&newShell, 0, sizeof(newShell));
2387236769Sobrien
2388236769Sobrien    /*
2389236769Sobrien     * Parse the specification by keyword
2390236769Sobrien     */
2391236769Sobrien    words = brk_string(line, &argc, TRUE, &path);
2392236769Sobrien    if (words == NULL) {
2393236769Sobrien	Error("Unterminated quoted string [%s]", line);
2394236769Sobrien	return FAILURE;
2395236769Sobrien    }
2396236769Sobrien    shellArgv = path;
2397236769Sobrien
2398236769Sobrien    for (path = NULL, argv = words; argc != 0; argc--, argv++) {
2399236769Sobrien	    if (strncmp(*argv, "path=", 5) == 0) {
2400236769Sobrien		path = &argv[0][5];
2401236769Sobrien	    } else if (strncmp(*argv, "name=", 5) == 0) {
2402236769Sobrien		newShell.name = &argv[0][5];
2403236769Sobrien	    } else {
2404236769Sobrien		if (strncmp(*argv, "quiet=", 6) == 0) {
2405236769Sobrien		    newShell.echoOff = &argv[0][6];
2406236769Sobrien		} else if (strncmp(*argv, "echo=", 5) == 0) {
2407236769Sobrien		    newShell.echoOn = &argv[0][5];
2408236769Sobrien		} else if (strncmp(*argv, "filter=", 7) == 0) {
2409236769Sobrien		    newShell.noPrint = &argv[0][7];
2410236769Sobrien		    newShell.noPLen = strlen(newShell.noPrint);
2411236769Sobrien		} else if (strncmp(*argv, "echoFlag=", 9) == 0) {
2412236769Sobrien		    newShell.echo = &argv[0][9];
2413236769Sobrien		} else if (strncmp(*argv, "errFlag=", 8) == 0) {
2414236769Sobrien		    newShell.exit = &argv[0][8];
2415236769Sobrien		} else if (strncmp(*argv, "hasErrCtl=", 10) == 0) {
2416236769Sobrien		    char c = argv[0][10];
2417236769Sobrien		    newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
2418236769Sobrien					   (c != 'T') && (c != 't'));
2419236769Sobrien		} else if (strncmp(*argv, "newline=", 8) == 0) {
2420236769Sobrien		    newShell.newline = &argv[0][8];
2421236769Sobrien		} else if (strncmp(*argv, "check=", 6) == 0) {
2422236769Sobrien		    newShell.errCheck = &argv[0][6];
2423236769Sobrien		} else if (strncmp(*argv, "ignore=", 7) == 0) {
2424236769Sobrien		    newShell.ignErr = &argv[0][7];
2425236769Sobrien		} else if (strncmp(*argv, "errout=", 7) == 0) {
2426236769Sobrien		    newShell.errOut = &argv[0][7];
2427236769Sobrien		} else if (strncmp(*argv, "comment=", 8) == 0) {
2428236769Sobrien		    newShell.commentChar = argv[0][8];
2429236769Sobrien		} else {
2430236769Sobrien		    Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"",
2431236769Sobrien				*argv);
2432236769Sobrien		    free(words);
2433236769Sobrien		    return(FAILURE);
2434236769Sobrien		}
2435236769Sobrien		fullSpec = TRUE;
2436236769Sobrien	    }
2437236769Sobrien    }
2438236769Sobrien
2439236769Sobrien    if (path == NULL) {
2440236769Sobrien	/*
2441236769Sobrien	 * If no path was given, the user wants one of the pre-defined shells,
2442236769Sobrien	 * yes? So we find the one s/he wants with the help of JobMatchShell
2443236769Sobrien	 * and set things up the right way. shellPath will be set up by
2444236769Sobrien	 * Job_Init.
2445236769Sobrien	 */
2446236769Sobrien	if (newShell.name == NULL) {
2447236769Sobrien	    Parse_Error(PARSE_FATAL, "Neither path nor name specified");
2448236769Sobrien	    free(words);
2449236769Sobrien	    return(FAILURE);
2450236769Sobrien	} else {
2451236769Sobrien	    if ((sh = JobMatchShell(newShell.name)) == NULL) {
2452236769Sobrien		    Parse_Error(PARSE_WARNING, "%s: No matching shell",
2453236769Sobrien				newShell.name);
2454236769Sobrien		    free(words);
2455236769Sobrien		    return(FAILURE);
2456236769Sobrien	    }
2457236769Sobrien	    commandShell = sh;
2458236769Sobrien	    shellName = newShell.name;
2459236769Sobrien	}
2460236769Sobrien    } else {
2461236769Sobrien	/*
2462236769Sobrien	 * The user provided a path. If s/he gave nothing else (fullSpec is
2463236769Sobrien	 * FALSE), try and find a matching shell in the ones we know of.
2464236769Sobrien	 * Else we just take the specification at its word and copy it
2465236769Sobrien	 * to a new location. In either case, we need to record the
2466236769Sobrien	 * path the user gave for the shell.
2467236769Sobrien	 */
2468236769Sobrien	shellPath = path;
2469236769Sobrien	path = strrchr(path, '/');
2470236769Sobrien	if (path == NULL) {
2471236769Sobrien	    path = UNCONST(shellPath);
2472236769Sobrien	} else {
2473236769Sobrien	    path += 1;
2474236769Sobrien	}
2475236769Sobrien	if (newShell.name != NULL) {
2476236769Sobrien	    shellName = newShell.name;
2477236769Sobrien	} else {
2478236769Sobrien	    shellName = path;
2479236769Sobrien	}
2480236769Sobrien	if (!fullSpec) {
2481236769Sobrien	    if ((sh = JobMatchShell(shellName)) == NULL) {
2482236769Sobrien		    Parse_Error(PARSE_WARNING, "%s: No matching shell",
2483236769Sobrien				shellName);
2484236769Sobrien		    free(words);
2485236769Sobrien		    return(FAILURE);
2486236769Sobrien	    }
2487236769Sobrien	    commandShell = sh;
2488236769Sobrien	} else {
2489236769Sobrien	    commandShell = bmake_malloc(sizeof(Shell));
2490236769Sobrien	    *commandShell = newShell;
2491236769Sobrien	}
2492236769Sobrien    }
2493236769Sobrien
2494236769Sobrien    if (commandShell->echoOn && commandShell->echoOff) {
2495236769Sobrien	commandShell->hasEchoCtl = TRUE;
2496236769Sobrien    }
2497236769Sobrien
2498236769Sobrien    if (!commandShell->hasErrCtl) {
2499236769Sobrien	if (commandShell->errCheck == NULL) {
2500236769Sobrien	    commandShell->errCheck = "";
2501236769Sobrien	}
2502236769Sobrien	if (commandShell->ignErr == NULL) {
2503236769Sobrien	    commandShell->ignErr = "%s\n";
2504236769Sobrien	}
2505236769Sobrien    }
2506236769Sobrien
2507236769Sobrien    /*
2508236769Sobrien     * Do not free up the words themselves, since they might be in use by the
2509236769Sobrien     * shell specification.
2510236769Sobrien     */
2511236769Sobrien    free(words);
2512236769Sobrien    return SUCCESS;
2513236769Sobrien}
2514236769Sobrien
2515236769Sobrien/*-
2516236769Sobrien *-----------------------------------------------------------------------
2517236769Sobrien * JobInterrupt --
2518236769Sobrien *	Handle the receipt of an interrupt.
2519236769Sobrien *
2520236769Sobrien * Input:
2521236769Sobrien *	runINTERRUPT	Non-zero if commands for the .INTERRUPT target
2522236769Sobrien *			should be executed
2523236769Sobrien *	signo		signal received
2524236769Sobrien *
2525236769Sobrien * Results:
2526236769Sobrien *	None
2527236769Sobrien *
2528236769Sobrien * Side Effects:
2529236769Sobrien *	All children are killed. Another job will be started if the
2530236769Sobrien *	.INTERRUPT target was given.
2531236769Sobrien *-----------------------------------------------------------------------
2532236769Sobrien */
2533236769Sobrienstatic void
2534236769SobrienJobInterrupt(int runINTERRUPT, int signo)
2535236769Sobrien{
2536236769Sobrien    Job		*job;		/* job descriptor in that element */
2537236769Sobrien    GNode	*interrupt;	/* the node describing the .INTERRUPT target */
2538236769Sobrien    sigset_t	mask;
2539236769Sobrien    GNode	*gn;
2540236769Sobrien
2541236769Sobrien    aborting = ABORT_INTERRUPT;
2542236769Sobrien
2543236769Sobrien    JobSigLock(&mask);
2544236769Sobrien
2545236769Sobrien    for (job = job_table; job < job_table_end; job++) {
2546236769Sobrien	if (job->job_state != JOB_ST_RUNNING)
2547236769Sobrien	    continue;
2548236769Sobrien
2549236769Sobrien	gn = job->node;
2550236769Sobrien
2551236769Sobrien	if ((gn->type & (OP_JOIN|OP_PHONY)) == 0 && !Targ_Precious(gn)) {
2552236769Sobrien	    char *file = (gn->path == NULL ? gn->name : gn->path);
2553236769Sobrien	    if (!noExecute && eunlink(file) != -1) {
2554236769Sobrien		Error("*** %s removed", file);
2555236769Sobrien	    }
2556236769Sobrien	}
2557236769Sobrien	if (job->pid) {
2558236769Sobrien	    if (DEBUG(JOB)) {
2559236769Sobrien		(void)fprintf(debug_file,
2560236769Sobrien			   "JobInterrupt passing signal %d to child %d.\n",
2561236769Sobrien			   signo, job->pid);
2562236769Sobrien	    }
2563236769Sobrien	    KILLPG(job->pid, signo);
2564236769Sobrien	}
2565236769Sobrien    }
2566236769Sobrien
2567236769Sobrien    JobSigUnlock(&mask);
2568236769Sobrien
2569236769Sobrien    if (runINTERRUPT && !touchFlag) {
2570236769Sobrien	interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2571236769Sobrien	if (interrupt != NULL) {
2572236769Sobrien	    ignoreErrors = FALSE;
2573236769Sobrien	    JobRun(interrupt);
2574236769Sobrien	}
2575236769Sobrien    }
2576236769Sobrien    Trace_Log(MAKEINTR, 0);
2577236769Sobrien    exit(signo);
2578236769Sobrien}
2579236769Sobrien
2580236769Sobrien/*
2581236769Sobrien *-----------------------------------------------------------------------
2582236769Sobrien * Job_Finish --
2583236769Sobrien *	Do final processing such as the running of the commands
2584236769Sobrien *	attached to the .END target.
2585236769Sobrien *
2586236769Sobrien * Results:
2587236769Sobrien *	Number of errors reported.
2588236769Sobrien *
2589236769Sobrien * Side Effects:
2590236769Sobrien *	None.
2591236769Sobrien *-----------------------------------------------------------------------
2592236769Sobrien */
2593236769Sobrienint
2594236769SobrienJob_Finish(void)
2595236769Sobrien{
2596236769Sobrien    if (postCommands != NULL &&
2597236769Sobrien	(!Lst_IsEmpty(postCommands->commands) ||
2598236769Sobrien	 !Lst_IsEmpty(postCommands->children))) {
2599236769Sobrien	if (errors) {
2600236769Sobrien	    Error("Errors reported so .END ignored");
2601236769Sobrien	} else {
2602236769Sobrien	    JobRun(postCommands);
2603236769Sobrien	}
2604236769Sobrien    }
2605236769Sobrien    return(errors);
2606236769Sobrien}
2607236769Sobrien
2608236769Sobrien/*-
2609236769Sobrien *-----------------------------------------------------------------------
2610236769Sobrien * Job_End --
2611236769Sobrien *	Cleanup any memory used by the jobs module
2612236769Sobrien *
2613236769Sobrien * Results:
2614236769Sobrien *	None.
2615236769Sobrien *
2616236769Sobrien * Side Effects:
2617236769Sobrien *	Memory is freed
2618236769Sobrien *-----------------------------------------------------------------------
2619236769Sobrien */
2620236769Sobrienvoid
2621236769SobrienJob_End(void)
2622236769Sobrien{
2623236769Sobrien#ifdef CLEANUP
2624236769Sobrien    if (shellArgv)
2625236769Sobrien	free(shellArgv);
2626236769Sobrien#endif
2627236769Sobrien}
2628236769Sobrien
2629236769Sobrien/*-
2630236769Sobrien *-----------------------------------------------------------------------
2631236769Sobrien * Job_Wait --
2632236769Sobrien *	Waits for all running jobs to finish and returns. Sets 'aborting'
2633236769Sobrien *	to ABORT_WAIT to prevent other jobs from starting.
2634236769Sobrien *
2635236769Sobrien * Results:
2636236769Sobrien *	None.
2637236769Sobrien *
2638236769Sobrien * Side Effects:
2639236769Sobrien *	Currently running jobs finish.
2640236769Sobrien *
2641236769Sobrien *-----------------------------------------------------------------------
2642236769Sobrien */
2643236769Sobrienvoid
2644236769SobrienJob_Wait(void)
2645236769Sobrien{
2646236769Sobrien    aborting = ABORT_WAIT;
2647236769Sobrien    while (jobTokensRunning != 0) {
2648236769Sobrien	Job_CatchOutput();
2649236769Sobrien    }
2650236769Sobrien    aborting = 0;
2651236769Sobrien}
2652236769Sobrien
2653236769Sobrien/*-
2654236769Sobrien *-----------------------------------------------------------------------
2655236769Sobrien * Job_AbortAll --
2656236769Sobrien *	Abort all currently running jobs without handling output or anything.
2657236769Sobrien *	This function is to be called only in the event of a major
2658236769Sobrien *	error. Most definitely NOT to be called from JobInterrupt.
2659236769Sobrien *
2660236769Sobrien * Results:
2661236769Sobrien *	None
2662236769Sobrien *
2663236769Sobrien * Side Effects:
2664236769Sobrien *	All children are killed, not just the firstborn
2665236769Sobrien *-----------------------------------------------------------------------
2666236769Sobrien */
2667236769Sobrienvoid
2668236769SobrienJob_AbortAll(void)
2669236769Sobrien{
2670236769Sobrien    Job		*job;	/* the job descriptor in that element */
2671236769Sobrien    WAIT_T	foo;
2672236769Sobrien
2673236769Sobrien    aborting = ABORT_ERROR;
2674236769Sobrien
2675236769Sobrien    if (jobTokensRunning) {
2676236769Sobrien	for (job = job_table; job < job_table_end; job++) {
2677236769Sobrien	    if (job->job_state != JOB_ST_RUNNING)
2678236769Sobrien		continue;
2679236769Sobrien	    /*
2680236769Sobrien	     * kill the child process with increasingly drastic signals to make
2681236769Sobrien	     * darn sure it's dead.
2682236769Sobrien	     */
2683236769Sobrien	    KILLPG(job->pid, SIGINT);
2684236769Sobrien	    KILLPG(job->pid, SIGKILL);
2685236769Sobrien	}
2686236769Sobrien    }
2687236769Sobrien
2688236769Sobrien    /*
2689236769Sobrien     * Catch as many children as want to report in at first, then give up
2690236769Sobrien     */
2691236769Sobrien    while (waitpid((pid_t) -1, &foo, WNOHANG) > 0)
2692236769Sobrien	continue;
2693236769Sobrien}
2694236769Sobrien
2695236769Sobrien
2696236769Sobrien/*-
2697236769Sobrien *-----------------------------------------------------------------------
2698236769Sobrien * JobRestartJobs --
2699236769Sobrien *	Tries to restart stopped jobs if there are slots available.
2700236769Sobrien *	Called in process context in response to a SIGCONT.
2701236769Sobrien *
2702236769Sobrien * Results:
2703236769Sobrien *	None.
2704236769Sobrien *
2705236769Sobrien * Side Effects:
2706236769Sobrien *	Resumes jobs.
2707236769Sobrien *
2708236769Sobrien *-----------------------------------------------------------------------
2709236769Sobrien */
2710236769Sobrienstatic void
2711236769SobrienJobRestartJobs(void)
2712236769Sobrien{
2713236769Sobrien    Job *job;
2714236769Sobrien
2715236769Sobrien    for (job = job_table; job < job_table_end; job++) {
2716236769Sobrien	if (job->job_state == JOB_ST_RUNNING &&
2717236769Sobrien		(make_suspended || job->job_suspended)) {
2718236769Sobrien	    if (DEBUG(JOB)) {
2719236769Sobrien		(void)fprintf(debug_file, "Restarting stopped job pid %d.\n",
2720236769Sobrien			job->pid);
2721236769Sobrien	    }
2722236769Sobrien	    if (job->job_suspended) {
2723236769Sobrien		    (void)printf("*** [%s] Continued\n", job->node->name);
2724236769Sobrien		    (void)fflush(stdout);
2725236769Sobrien	    }
2726236769Sobrien	    job->job_suspended = 0;
2727236769Sobrien	    if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
2728236769Sobrien		fprintf(debug_file, "Failed to send SIGCONT to %d\n", job->pid);
2729236769Sobrien	    }
2730236769Sobrien	}
2731236769Sobrien	if (job->job_state == JOB_ST_FINISHED)
2732236769Sobrien	    /* Job exit deferred after calling waitpid() in a signal handler */
2733236769Sobrien	    JobFinish(job, job->exit_status);
2734236769Sobrien    }
2735236769Sobrien    make_suspended = 0;
2736236769Sobrien}
2737236769Sobrien
2738236769Sobrienstatic void
2739236769Sobrienwatchfd(Job *job)
2740236769Sobrien{
2741236769Sobrien    if (job->inPollfd != NULL)
2742236769Sobrien	Punt("Watching watched job");
2743236769Sobrien
2744236769Sobrien    fds[nfds].fd = job->inPipe;
2745236769Sobrien    fds[nfds].events = POLLIN;
2746236769Sobrien    jobfds[nfds] = job;
2747236769Sobrien    job->inPollfd = &fds[nfds];
2748236769Sobrien    nfds++;
2749236769Sobrien}
2750236769Sobrien
2751236769Sobrienstatic void
2752236769Sobrienclearfd(Job *job)
2753236769Sobrien{
2754236769Sobrien    int i;
2755236769Sobrien    if (job->inPollfd == NULL)
2756236769Sobrien	Punt("Unwatching unwatched job");
2757236769Sobrien    i = job->inPollfd - fds;
2758236769Sobrien    nfds--;
2759236769Sobrien    /*
2760236769Sobrien     * Move last job in table into hole made by dead job.
2761236769Sobrien     */
2762236769Sobrien    if (nfds != i) {
2763236769Sobrien	fds[i] = fds[nfds];
2764236769Sobrien	jobfds[i] = jobfds[nfds];
2765236769Sobrien	jobfds[i]->inPollfd = &fds[i];
2766236769Sobrien    }
2767236769Sobrien    job->inPollfd = NULL;
2768236769Sobrien}
2769236769Sobrien
2770236769Sobrienstatic int
2771236769Sobrienreadyfd(Job *job)
2772236769Sobrien{
2773236769Sobrien    if (job->inPollfd == NULL)
2774236769Sobrien	Punt("Polling unwatched job");
2775236769Sobrien    return (job->inPollfd->revents & POLLIN) != 0;
2776236769Sobrien}
2777236769Sobrien
2778236769Sobrien/*-
2779236769Sobrien *-----------------------------------------------------------------------
2780236769Sobrien * JobTokenAdd --
2781236769Sobrien *	Put a token into the job pipe so that some make process can start
2782236769Sobrien *	another job.
2783236769Sobrien *
2784236769Sobrien * Side Effects:
2785236769Sobrien *	Allows more build jobs to be spawned somewhere.
2786236769Sobrien *
2787236769Sobrien *-----------------------------------------------------------------------
2788236769Sobrien */
2789236769Sobrien
2790236769Sobrienstatic void
2791236769SobrienJobTokenAdd(void)
2792236769Sobrien{
2793236769Sobrien    char tok = JOB_TOKENS[aborting], tok1;
2794236769Sobrien
2795236769Sobrien    /* If we are depositing an error token flush everything else */
2796236769Sobrien    while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2797236769Sobrien	continue;
2798236769Sobrien
2799236769Sobrien    if (DEBUG(JOB))
2800236769Sobrien	fprintf(debug_file, "(%d) aborting %d, deposit token %c\n",
2801236769Sobrien	    getpid(), aborting, JOB_TOKENS[aborting]);
2802236769Sobrien    write(tokenWaitJob.outPipe, &tok, 1);
2803236769Sobrien}
2804236769Sobrien
2805236769Sobrien/*-
2806236769Sobrien *-----------------------------------------------------------------------
2807236769Sobrien * Job_ServerStartTokenAdd --
2808236769Sobrien *	Prep the job token pipe in the root make process.
2809236769Sobrien *
2810236769Sobrien *-----------------------------------------------------------------------
2811236769Sobrien */
2812236769Sobrien
2813236769Sobrienvoid
2814236769SobrienJob_ServerStart(int max_tokens, int jp_0, int jp_1)
2815236769Sobrien{
2816236769Sobrien    int i;
2817236769Sobrien    char jobarg[64];
2818236769Sobrien
2819236769Sobrien    if (jp_0 >= 0 && jp_1 >= 0) {
2820236769Sobrien	/* Pipe passed in from parent */
2821236769Sobrien	tokenWaitJob.inPipe = jp_0;
2822236769Sobrien	tokenWaitJob.outPipe = jp_1;
2823236769Sobrien	return;
2824236769Sobrien    }
2825236769Sobrien
2826236769Sobrien    JobCreatePipe(&tokenWaitJob, 15);
2827236769Sobrien
2828236769Sobrien    snprintf(jobarg, sizeof(jobarg), "%d,%d",
2829236769Sobrien	    tokenWaitJob.inPipe, tokenWaitJob.outPipe);
2830236769Sobrien
2831236769Sobrien    Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
2832236769Sobrien    Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
2833236769Sobrien
2834236769Sobrien    /*
2835236769Sobrien     * Preload the job pipe with one token per job, save the one
2836236769Sobrien     * "extra" token for the primary job.
2837236769Sobrien     *
2838236769Sobrien     * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
2839236769Sobrien     * larger than the write buffer size of the pipe, we will
2840236769Sobrien     * deadlock here.
2841236769Sobrien     */
2842236769Sobrien    for (i = 1; i < max_tokens; i++)
2843236769Sobrien	JobTokenAdd();
2844236769Sobrien}
2845236769Sobrien
2846236769Sobrien/*-
2847236769Sobrien *-----------------------------------------------------------------------
2848236769Sobrien * Job_TokenReturn --
2849236769Sobrien *	Return a withdrawn token to the pool.
2850236769Sobrien *
2851236769Sobrien *-----------------------------------------------------------------------
2852236769Sobrien */
2853236769Sobrien
2854236769Sobrienvoid
2855236769SobrienJob_TokenReturn(void)
2856236769Sobrien{
2857236769Sobrien    jobTokensRunning--;
2858236769Sobrien    if (jobTokensRunning < 0)
2859236769Sobrien	Punt("token botch");
2860236769Sobrien    if (jobTokensRunning || JOB_TOKENS[aborting] != '+')
2861236769Sobrien	JobTokenAdd();
2862236769Sobrien}
2863236769Sobrien
2864236769Sobrien/*-
2865236769Sobrien *-----------------------------------------------------------------------
2866236769Sobrien * Job_TokenWithdraw --
2867236769Sobrien *	Attempt to withdraw a token from the pool.
2868236769Sobrien *
2869236769Sobrien * Results:
2870236769Sobrien *	Returns TRUE if a token was withdrawn, and FALSE if the pool
2871236769Sobrien *	is currently empty.
2872236769Sobrien *
2873236769Sobrien * Side Effects:
2874236769Sobrien * 	If pool is empty, set wantToken so that we wake up
2875236769Sobrien *	when a token is released.
2876236769Sobrien *
2877236769Sobrien *-----------------------------------------------------------------------
2878236769Sobrien */
2879236769Sobrien
2880236769Sobrien
2881236769SobrienBoolean
2882236769SobrienJob_TokenWithdraw(void)
2883236769Sobrien{
2884236769Sobrien    char tok, tok1;
2885236769Sobrien    int count;
2886236769Sobrien
2887236769Sobrien    wantToken = 0;
2888236769Sobrien    if (DEBUG(JOB))
2889236769Sobrien	fprintf(debug_file, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
2890236769Sobrien		getpid(), aborting, jobTokensRunning);
2891236769Sobrien
2892236769Sobrien    if (aborting || (jobTokensRunning >= maxJobs))
2893236769Sobrien	return FALSE;
2894236769Sobrien
2895236769Sobrien    count = read(tokenWaitJob.inPipe, &tok, 1);
2896236769Sobrien    if (count == 0)
2897236769Sobrien	Fatal("eof on job pipe!");
2898236769Sobrien    if (count < 0 && jobTokensRunning != 0) {
2899236769Sobrien	if (errno != EAGAIN) {
2900236769Sobrien	    Fatal("job pipe read: %s", strerror(errno));
2901236769Sobrien	}
2902236769Sobrien	if (DEBUG(JOB))
2903236769Sobrien	    fprintf(debug_file, "(%d) blocked for token\n", getpid());
2904236769Sobrien	wantToken = 1;
2905236769Sobrien	return FALSE;
2906236769Sobrien    }
2907236769Sobrien
2908236769Sobrien    if (count == 1 && tok != '+') {
2909236769Sobrien	/* make being abvorted - remove any other job tokens */
2910236769Sobrien	if (DEBUG(JOB))
2911236769Sobrien	    fprintf(debug_file, "(%d) aborted by token %c\n", getpid(), tok);
2912236769Sobrien	while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2913236769Sobrien	    continue;
2914236769Sobrien	/* And put the stopper back */
2915236769Sobrien	write(tokenWaitJob.outPipe, &tok, 1);
2916236769Sobrien	Fatal("A failure has been detected in another branch of the parallel make");
2917236769Sobrien    }
2918236769Sobrien
2919236769Sobrien    if (count == 1 && jobTokensRunning == 0)
2920236769Sobrien	/* We didn't want the token really */
2921236769Sobrien	write(tokenWaitJob.outPipe, &tok, 1);
2922236769Sobrien
2923236769Sobrien    jobTokensRunning++;
2924236769Sobrien    if (DEBUG(JOB))
2925236769Sobrien	fprintf(debug_file, "(%d) withdrew token\n", getpid());
2926236769Sobrien    return TRUE;
2927236769Sobrien}
2928236769Sobrien
2929236769Sobrien#ifdef USE_SELECT
2930236769Sobrienint
2931236769Sobrienemul_poll(struct pollfd *fd, int nfd, int timeout)
2932236769Sobrien{
2933236769Sobrien    fd_set rfds, wfds;
2934236769Sobrien    int i, maxfd, nselect, npoll;
2935236769Sobrien    struct timeval tv, *tvp;
2936236769Sobrien    long usecs;
2937236769Sobrien
2938236769Sobrien    FD_ZERO(&rfds);
2939236769Sobrien    FD_ZERO(&wfds);
2940236769Sobrien
2941236769Sobrien    maxfd = -1;
2942236769Sobrien    for (i = 0; i < nfd; i++) {
2943236769Sobrien	fd[i].revents = 0;
2944236769Sobrien
2945236769Sobrien	if (fd[i].events & POLLIN)
2946236769Sobrien	    FD_SET(fd[i].fd, &rfds);
2947236769Sobrien
2948236769Sobrien	if (fd[i].events & POLLOUT)
2949236769Sobrien	    FD_SET(fd[i].fd, &wfds);
2950236769Sobrien
2951236769Sobrien	if (fd[i].fd > maxfd)
2952236769Sobrien	    maxfd = fd[i].fd;
2953236769Sobrien    }
2954236769Sobrien
2955236769Sobrien    if (maxfd >= FD_SETSIZE) {
2956236769Sobrien	Punt("Ran out of fd_set slots; "
2957236769Sobrien	     "recompile with a larger FD_SETSIZE.");
2958236769Sobrien    }
2959236769Sobrien
2960236769Sobrien    if (timeout < 0) {
2961236769Sobrien	tvp = NULL;
2962236769Sobrien    } else {
2963236769Sobrien	usecs = timeout * 1000;
2964236769Sobrien	tv.tv_sec = usecs / 1000000;
2965236769Sobrien	tv.tv_usec = usecs % 1000000;
2966236769Sobrien        tvp = &tv;
2967236769Sobrien    }
2968236769Sobrien
2969236769Sobrien    nselect = select(maxfd + 1, &rfds, &wfds, 0, tvp);
2970236769Sobrien
2971236769Sobrien    if (nselect <= 0)
2972236769Sobrien	return nselect;
2973236769Sobrien
2974236769Sobrien    npoll = 0;
2975236769Sobrien    for (i = 0; i < nfd; i++) {
2976236769Sobrien	if (FD_ISSET(fd[i].fd, &rfds))
2977236769Sobrien	    fd[i].revents |= POLLIN;
2978236769Sobrien
2979236769Sobrien	if (FD_ISSET(fd[i].fd, &wfds))
2980236769Sobrien	    fd[i].revents |= POLLOUT;
2981236769Sobrien
2982236769Sobrien	if (fd[i].revents)
2983236769Sobrien	    npoll++;
2984236769Sobrien    }
2985236769Sobrien
2986236769Sobrien    return npoll;
2987236769Sobrien}
2988236769Sobrien#endif /* USE_SELECT */
2989