xref: /netbsd-src/usr.bin/make/job.c (revision 8b0f9554ff8762542c4defc4f70e1eb76fb508fa)
1 /*	$NetBSD: job.c,v 1.133 2007/10/14 20:22:53 apb Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * Copyright (c) 1988, 1989 by Adam de Boor
37  * Copyright (c) 1989 by Berkeley Softworks
38  * All rights reserved.
39  *
40  * This code is derived from software contributed to Berkeley by
41  * Adam de Boor.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. All advertising materials mentioning features or use of this software
52  *    must display the following acknowledgement:
53  *	This product includes software developed by the University of
54  *	California, Berkeley and its contributors.
55  * 4. Neither the name of the University nor the names of its contributors
56  *    may be used to endorse or promote products derived from this software
57  *    without specific prior written permission.
58  *
59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69  * SUCH DAMAGE.
70  */
71 
72 #ifndef MAKE_NATIVE
73 static char rcsid[] = "$NetBSD: job.c,v 1.133 2007/10/14 20:22:53 apb Exp $";
74 #else
75 #include <sys/cdefs.h>
76 #ifndef lint
77 #if 0
78 static char sccsid[] = "@(#)job.c	8.2 (Berkeley) 3/19/94";
79 #else
80 __RCSID("$NetBSD: job.c,v 1.133 2007/10/14 20:22:53 apb Exp $");
81 #endif
82 #endif /* not lint */
83 #endif
84 
85 /*-
86  * job.c --
87  *	handle the creation etc. of our child processes.
88  *
89  * Interface:
90  *	Job_Make  	    	Start the creation of the given target.
91  *
92  *	Job_CatchChildren   	Check for and handle the termination of any
93  *	    	  	    	children. This must be called reasonably
94  *	    	  	    	frequently to keep the whole make going at
95  *	    	  	    	a decent clip, since job table entries aren't
96  *	    	  	    	removed until their process is caught this way.
97  *
98  *	Job_CatchOutput	    	Print any output our children have produced.
99  *	    	  	    	Should also be called fairly frequently to
100  *	    	  	    	keep the user informed of what's going on.
101  *	    	  	    	If no output is waiting, it will block for
102  *	    	  	    	a time given by the SEL_* constants, below,
103  *	    	  	    	or until output is ready.
104  *
105  *	Job_Init  	    	Called to intialize this module. in addition,
106  *	    	  	    	any commands attached to the .BEGIN target
107  *	    	  	    	are executed before this function returns.
108  *	    	  	    	Hence, the makefile must have been parsed
109  *	    	  	    	before this function is called.
110  *
111  *	Job_End  	    	Cleanup any memory used.
112  *
113  *	Job_ParseShell	    	Given the line following a .SHELL target, parse
114  *	    	  	    	the line as a shell specification. Returns
115  *	    	  	    	FAILURE if the spec was incorrect.
116  *
117  *	Job_Finish	    	Perform any final processing which needs doing.
118  *	    	  	    	This includes the execution of any commands
119  *	    	  	    	which have been/were attached to the .END
120  *	    	  	    	target. It should only be called when the
121  *	    	  	    	job table is empty.
122  *
123  *	Job_AbortAll	    	Abort all currently running jobs. It doesn't
124  *	    	  	    	handle output or do anything for the jobs,
125  *	    	  	    	just kills them. It should only be called in
126  *	    	  	    	an emergency, as it were.
127  *
128  *	Job_CheckCommands   	Verify that the commands for a target are
129  *	    	  	    	ok. Provide them if necessary and possible.
130  *
131  *	Job_Touch 	    	Update a target without really updating it.
132  *
133  *	Job_Wait  	    	Wait for all currently-running jobs to finish.
134  */
135 
136 #include <sys/types.h>
137 #include <sys/stat.h>
138 #include <sys/file.h>
139 #include <sys/time.h>
140 #include <sys/wait.h>
141 
142 #include <errno.h>
143 #include <fcntl.h>
144 #ifndef USE_SELECT
145 #include <poll.h>
146 #endif
147 #include <signal.h>
148 #include <stdio.h>
149 #include <string.h>
150 #include <utime.h>
151 
152 #include "make.h"
153 #include "hash.h"
154 #include "dir.h"
155 #include "job.h"
156 #include "pathnames.h"
157 #include "trace.h"
158 # define STATIC static
159 
160 /*
161  * error handling variables
162  */
163 static int     	errors = 0;	    /* number of errors reported */
164 static int    	aborting = 0;	    /* why is the make aborting? */
165 #define ABORT_ERROR	1   	    /* Because of an error */
166 #define ABORT_INTERRUPT	2   	    /* Because it was interrupted */
167 #define ABORT_WAIT	3   	    /* Waiting for jobs to finish */
168 #define JOB_TOKENS	"+EI+"	    /* Token to requeue for each abort state */
169 
170 /*
171  * this tracks the number of tokens currently "out" to build jobs.
172  */
173 int jobTokensRunning = 0;
174 int not_parallel = 0;		    /* set if .NOT_PARALLEL */
175 
176 /*
177  * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
178  * is a char! So when we go above 127 we turn negative!
179  */
180 #define FILENO(a) ((unsigned) fileno(a))
181 
182 /*
183  * post-make command processing. The node postCommands is really just the
184  * .END target but we keep it around to avoid having to search for it
185  * all the time.
186  */
187 static GNode   	  *postCommands = NILGNODE;
188 				    /* node containing commands to execute when
189 				     * everything else is done */
190 static int     	  numCommands; 	    /* The number of commands actually printed
191 				     * for a target. Should this number be
192 				     * 0, no shell will be executed. */
193 
194 /*
195  * Return values from JobStart.
196  */
197 #define JOB_RUNNING	0   	/* Job is running */
198 #define JOB_ERROR 	1   	/* Error in starting the job */
199 #define JOB_FINISHED	2   	/* The job is already finished */
200 
201 /*
202  * Descriptions for various shells.
203  *
204  * The build environment may set DEFSHELL_INDEX to one of
205  * DEFSHELL_INDEX_SH, DEFSHELL_INDEX_KSH, or DEFSHELL_INDEX_CSH, to
206  * select one of the prefedined shells as the default shell.
207  *
208  * Alternatively, the build environment may set DEFSHELL_CUSTOM to the
209  * name or the full path of a sh-compatible shell, which will be used as
210  * the default shell.
211  *
212  * ".SHELL" lines in Makefiles can choose the default shell from the
213  # set defined here, or add additional shells.
214  */
215 
216 #ifdef DEFSHELL_CUSTOM
217 #define DEFSHELL_INDEX_CUSTOM 0
218 #define DEFSHELL_INDEX_SH     1
219 #define DEFSHELL_INDEX_KSH    2
220 #define DEFSHELL_INDEX_CSH    3
221 #else /* !DEFSHELL_CUSTOM */
222 #define DEFSHELL_INDEX_SH     0
223 #define DEFSHELL_INDEX_KSH    1
224 #define DEFSHELL_INDEX_CSH    2
225 #endif /* !DEFSHELL_CUSTOM */
226 
227 #ifndef DEFSHELL_INDEX
228 #define DEFSHELL_INDEX 0	/* DEFSHELL_INDEX_CUSTOM or DEFSHELL_INDEX_SH */
229 #endif /* !DEFSHELL_INDEX */
230 
231 static Shell    shells[] = {
232 #ifdef DEFSHELL_CUSTOM
233     /*
234      * An sh-compatible shell with a non-standard name.
235      *
236      * Keep this in sync with the "sh" description below, but avoid
237      * non-portable features that might not be supplied by all
238      * sh-compatible shells.
239      */
240 {
241     DEFSHELL_CUSTOM,
242     FALSE, "", "", "", 0,
243     FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
244     "",
245     "",
246 },
247 #endif /* DEFSHELL_CUSTOM */
248     /*
249      * SH description. Echo control is also possible and, under
250      * sun UNIX anyway, one can even control error checking.
251      */
252 {
253     "sh",
254     FALSE, "", "", "", 0,
255     FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
256 #if defined(MAKE_NATIVE) && defined(__NetBSD__)
257     "q",
258 #else
259     "",
260 #endif
261     "",
262 },
263     /*
264      * KSH description.
265      */
266 {
267     "ksh",
268     TRUE, "set +v", "set -v", "set +v", 6,
269     FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
270     "v",
271     "",
272 },
273     /*
274      * CSH description. The csh can do echo control by playing
275      * with the setting of the 'echo' shell variable. Sadly,
276      * however, it is unable to do error control nicely.
277      */
278 {
279     "csh",
280     TRUE, "unset verbose", "set verbose", "unset verbose", 10,
281     FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"\n", "", "'\\\n'", '#',
282     "v", "e",
283 },
284     /*
285      * UNKNOWN.
286      */
287 {
288     NULL,
289     FALSE, NULL, NULL, NULL, 0,
290     FALSE, NULL, NULL, NULL, NULL, 0,
291     NULL, NULL,
292 }
293 };
294 static Shell *commandShell = &shells[DEFSHELL_INDEX]; /* this is the shell to
295 						   * which we pass all
296 						   * commands in the Makefile.
297 						   * It is set by the
298 						   * Job_ParseShell function */
299 const char *shellPath = NULL,		  	  /* full pathname of
300 						   * executable image */
301            *shellName = NULL;		      	  /* last component of shell */
302 static const char *shellArgv = NULL;		  /* Custom shell args */
303 
304 
305 STATIC Job	*job_table;	/* The structures that describe them */
306 STATIC Job	*job_table_end;	/* job_table + maxJobs */
307 static int	wantToken;	/* we want a token */
308 static int lurking_children = 0;
309 static int make_suspended = 0;	/* non-zero if we've seen a SIGTSTP (etc) */
310 
311 /*
312  * Set of descriptors of pipes connected to
313  * the output channels of children
314  */
315 static struct pollfd *fds = NULL;
316 static Job **jobfds = NULL;
317 static int nfds = 0;
318 static void watchfd(Job *);
319 static void clearfd(Job *);
320 static int readyfd(Job *);
321 
322 STATIC GNode   	*lastNode;	/* The node for which output was most recently
323 				 * produced. */
324 STATIC const char *targFmt;   	/* Format string to use to head output from a
325 				 * job when it's not the most-recent job heard
326 				 * from */
327 static char *targPrefix = NULL; /* What we print at the start of targFmt */
328 static Job tokenWaitJob;	/* token wait pseudo-job */
329 
330 static Job childExitJob;	/* child exit pseudo-job */
331 #define	CHILD_EXIT	"."
332 #define	DO_JOB_RESUME	"R"
333 
334 #define TARG_FMT  "%s %s ---\n" /* Default format */
335 #define MESSAGE(fp, gn) \
336 	(void)fprintf(fp, targFmt, targPrefix, gn->name)
337 
338 static sigset_t caught_signals;	/* Set of signals we handle */
339 #if defined(SYSV)
340 #define KILLPG(pid, sig)	kill(-(pid), (sig))
341 #else
342 #define KILLPG(pid, sig)	killpg((pid), (sig))
343 #endif
344 
345 static void JobChildSig(int);
346 static void JobContinueSig(int);
347 static Job *JobFindPid(int, int);
348 static int JobPrintCommand(ClientData, ClientData);
349 static int JobSaveCommand(ClientData, ClientData);
350 static void JobClose(Job *);
351 static void JobExec(Job *, char **);
352 static void JobMakeArgv(Job *, char **);
353 static int JobStart(GNode *, int);
354 static char *JobOutput(Job *, char *, char *, int);
355 static void JobDoOutput(Job *, Boolean);
356 static Shell *JobMatchShell(const char *);
357 static void JobInterrupt(int, int);
358 static void JobRestartJobs(void);
359 static void JobTokenAdd(void);
360 static void JobSigLock(sigset_t *);
361 static void JobSigUnlock(sigset_t *);
362 static void JobSigReset(void);
363 
364 const char *malloc_options="A";
365 
366 static void
367 job_table_dump(const char *where)
368 {
369     Job *job;
370 
371     fprintf(debug_file, "job table @ %s\n", where);
372     for (job = job_table; job < job_table_end; job++) {
373 	fprintf(debug_file, "job %d, status %d, flags %d, pid %d\n",
374 	    (int)(job - job_table), job->job_state, job->flags, job->pid);
375     }
376 }
377 
378 /*
379  * JobSigLock/JobSigUnlock
380  *
381  * Signal lock routines to get exclusive access. Currently used to
382  * protect `jobs' and `stoppedJobs' list manipulations.
383  */
384 static void JobSigLock(sigset_t *omaskp)
385 {
386 	if (sigprocmask(SIG_BLOCK, &caught_signals, omaskp) != 0) {
387 		Punt("JobSigLock: sigprocmask: %s", strerror(errno));
388 		sigemptyset(omaskp);
389 	}
390 }
391 
392 static void JobSigUnlock(sigset_t *omaskp)
393 {
394 	(void)sigprocmask(SIG_SETMASK, omaskp, NULL);
395 }
396 
397 static void
398 JobCreatePipe(Job *job, int minfd)
399 {
400     int i, fd;
401 
402     if (pipe(job->jobPipe) == -1)
403 	Punt("Cannot create pipe: %s", strerror(errno));
404 
405     /* Set close-on-exec flag for both */
406     (void)fcntl(job->jobPipe[0], F_SETFD, 1);
407     (void)fcntl(job->jobPipe[1], F_SETFD, 1);
408 
409     /*
410      * We mark the input side of the pipe non-blocking; we poll(2) the
411      * pipe when we're waiting for a job token, but we might lose the
412      * race for the token when a new one becomes available, so the read
413      * from the pipe should not block.
414      */
415     fcntl(job->jobPipe[0], F_SETFL,
416 	fcntl(job->jobPipe[0], F_GETFL, 0) | O_NONBLOCK);
417 
418     for (i = 0; i < 2; i++) {
419        /* Avoid using low numbered fds */
420        fd = fcntl(job->jobPipe[i], F_DUPFD, minfd);
421        if (fd != -1) {
422 	   close(job->jobPipe[i]);
423 	   job->jobPipe[i] = fd;
424        }
425     }
426 }
427 
428 /*-
429  *-----------------------------------------------------------------------
430  * JobCondPassSig --
431  *	Pass a signal to a job
432  *
433  * Input:
434  *	signop		Signal to send it
435  *
436  * Side Effects:
437  *	None, except the job may bite it.
438  *
439  *-----------------------------------------------------------------------
440  */
441 static void
442 JobCondPassSig(int signo)
443 {
444     Job *job;
445 
446     if (DEBUG(JOB)) {
447 	(void)fprintf(debug_file, "JobCondPassSig(%d) called.\n", signo);
448     }
449 
450     for (job = job_table; job < job_table_end; job++) {
451 	if (job->job_state != JOB_ST_RUNNING)
452 	    continue;
453 	if (DEBUG(JOB)) {
454 	    (void)fprintf(debug_file,
455 			   "JobCondPassSig passing signal %d to child %d.\n",
456 			   signo, job->pid);
457 	}
458 	KILLPG(job->pid, signo);
459     }
460 }
461 
462 /*-
463  *-----------------------------------------------------------------------
464  * JobChldSig --
465  *	SIGCHLD handler.
466  *
467  * Input:
468  *	signo		The signal number we've received
469  *
470  * Results:
471  *	None.
472  *
473  * Side Effects:
474  *	Sends a token on the child exit pipe to wake us up from
475  *	select()/poll().
476  *
477  *-----------------------------------------------------------------------
478  */
479 static void
480 JobChildSig(int signo __unused)
481 {
482     write(childExitJob.outPipe, CHILD_EXIT, 1);
483 }
484 
485 
486 /*-
487  *-----------------------------------------------------------------------
488  * JobContinueSig --
489  *	Resume all stopped jobs.
490  *
491  * Input:
492  *	signo		The signal number we've received
493  *
494  * Results:
495  *	None.
496  *
497  * Side Effects:
498  *	Jobs start running again.
499  *
500  *-----------------------------------------------------------------------
501  */
502 static void
503 JobContinueSig(int signo __unused)
504 {
505     /*
506      * Defer sending to SIGCONT to our stopped children until we return
507      * from the signal handler.
508      */
509     write(childExitJob.outPipe, DO_JOB_RESUME, 1);
510 }
511 
512 /*-
513  *-----------------------------------------------------------------------
514  * JobPassSig --
515  *	Pass a signal on to all jobs, then resend to ourselves.
516  *
517  * Input:
518  *	signo		The signal number we've received
519  *
520  * Results:
521  *	None.
522  *
523  * Side Effects:
524  *	We die by the same signal.
525  *
526  *-----------------------------------------------------------------------
527  */
528 static void
529 JobPassSig_int(int signo)
530 {
531     /* Run .INTERRUPT target then exit */
532     JobInterrupt(TRUE, signo);
533 }
534 
535 static void
536 JobPassSig_term(int signo)
537 {
538     /* Dont run .INTERRUPT target then exit */
539     JobInterrupt(FALSE, signo);
540 }
541 
542 static void
543 JobPassSig_suspend(int signo)
544 {
545     sigset_t nmask, omask;
546     struct sigaction act;
547 
548     /* Suppress job started/continued messages */
549     make_suspended = 1;
550 
551     /* Pass the signal onto every job */
552     JobCondPassSig(signo);
553 
554     /*
555      * Send ourselves the signal now we've given the message to everyone else.
556      * Note we block everything else possible while we're getting the signal.
557      * This ensures that all our jobs get continued when we wake up before
558      * we take any other signal.
559      */
560     sigfillset(&nmask);
561     sigdelset(&nmask, signo);
562     (void)sigprocmask(SIG_SETMASK, &nmask, &omask);
563 
564     act.sa_handler = SIG_DFL;
565     sigemptyset(&act.sa_mask);
566     act.sa_flags = 0;
567     (void)sigaction(signo, &act, NULL);
568 
569     if (DEBUG(JOB)) {
570 	(void)fprintf(debug_file,
571 		       "JobPassSig passing signal %d to self.\n", signo);
572     }
573 
574     (void)kill(getpid(), signo);
575 
576     /*
577      * We've been continued.
578      *
579      * A whole host of signals continue to happen!
580      * SIGCHLD for any processes that actually suspended themselves.
581      * SIGCHLD for any processes that exited while we were alseep.
582      * The SIGCONT that actually caused us to wakeup.
583      *
584      * Since we defer passing the SIGCONT on to our children until
585      * the main processing loop, we can be sure that all the SIGCHLD
586      * events will have happened by then - and that the waitpid() will
587      * collect the child 'suspended' events.
588      * For correct sequencing we just need to ensure we process the
589      * waitpid() before passign on the SIGCONT.
590      *
591      * In any case nothing else is needed here.
592      */
593 
594     /* Restore handler and signal mask */
595     act.sa_handler = JobPassSig_suspend;
596     (void)sigaction(signo, &act, NULL);
597     (void)sigprocmask(SIG_SETMASK, &omask, NULL);
598 }
599 
600 /*-
601  *-----------------------------------------------------------------------
602  * JobFindPid  --
603  *	Compare the pid of the job with the given pid and return 0 if they
604  *	are equal. This function is called from Job_CatchChildren
605  *	to find the job descriptor of the finished job.
606  *
607  * Input:
608  *	job		job to examine
609  *	pid		process id desired
610  *
611  * Results:
612  *	Job with matching pid
613  *
614  * Side Effects:
615  *	None
616  *-----------------------------------------------------------------------
617  */
618 static Job *
619 JobFindPid(int pid, int status)
620 {
621     Job *job;
622 
623     for (job = job_table; job < job_table_end; job++) {
624 	if ((job->job_state == status) && job->pid == pid)
625 	    return job;
626     }
627     if (DEBUG(JOB))
628 	job_table_dump("no pid");
629     return NULL;
630 }
631 
632 /*-
633  *-----------------------------------------------------------------------
634  * JobPrintCommand  --
635  *	Put out another command for the given job. If the command starts
636  *	with an @ or a - we process it specially. In the former case,
637  *	so long as the -s and -n flags weren't given to make, we stick
638  *	a shell-specific echoOff command in the script. In the latter,
639  *	we ignore errors for the entire job, unless the shell has error
640  *	control.
641  *	If the command is just "..." we take all future commands for this
642  *	job to be commands to be executed once the entire graph has been
643  *	made and return non-zero to signal that the end of the commands
644  *	was reached. These commands are later attached to the postCommands
645  *	node and executed by Job_End when all things are done.
646  *	This function is called from JobStart via Lst_ForEach.
647  *
648  * Input:
649  *	cmdp		command string to print
650  *	jobp		job for which to print it
651  *
652  * Results:
653  *	Always 0, unless the command was "..."
654  *
655  * Side Effects:
656  *	If the command begins with a '-' and the shell has no error control,
657  *	the JOB_IGNERR flag is set in the job descriptor.
658  *	If the command is "..." and we're not ignoring such things,
659  *	tailCmds is set to the successor node of the cmd.
660  *	numCommands is incremented if the command is actually printed.
661  *-----------------------------------------------------------------------
662  */
663 static int
664 JobPrintCommand(ClientData cmdp, ClientData jobp)
665 {
666     Boolean	  noSpecials;	    /* true if we shouldn't worry about
667 				     * inserting special commands into
668 				     * the input stream. */
669     Boolean       shutUp = FALSE;   /* true if we put a no echo command
670 				     * into the command file */
671     Boolean	  errOff = FALSE;   /* true if we turned error checking
672 				     * off before printing the command
673 				     * and need to turn it back on */
674     const char    *cmdTemplate;	    /* Template to use when printing the
675 				     * command */
676     char    	  *cmdStart;	    /* Start of expanded command */
677     char	  *escCmd = NULL;    /* Command with quotes/backticks escaped */
678     char     	  *cmd = (char *)cmdp;
679     Job           *job = (Job *)jobp;
680     char	  *cp, *tmp;
681     int           i, j;
682 
683     noSpecials = NoExecute(job->node);
684 
685     if (strcmp(cmd, "...") == 0) {
686 	job->node->type |= OP_SAVE_CMDS;
687 	if ((job->flags & JOB_IGNDOTS) == 0) {
688 	    job->tailCmds = Lst_Succ(Lst_Member(job->node->commands,
689 						cmd));
690 	    return 1;
691 	}
692 	return 0;
693     }
694 
695 #define DBPRINTF(fmt, arg) if (DEBUG(JOB)) {	\
696 	(void)fprintf(debug_file, fmt, arg); 	\
697     }						\
698    (void)fprintf(job->cmdFILE, fmt, arg);	\
699    (void)fflush(job->cmdFILE);
700 
701     numCommands += 1;
702 
703     cmdStart = cmd = Var_Subst(NULL, cmd, job->node, FALSE);
704 
705     cmdTemplate = "%s\n";
706 
707     /*
708      * Check for leading @' and -'s to control echoing and error checking.
709      */
710     while (*cmd == '@' || *cmd == '-' || (*cmd == '+')) {
711 	switch (*cmd) {
712 	case '@':
713 	    shutUp = TRUE;
714 	    break;
715 	case '-':
716 	    errOff = TRUE;
717 	    break;
718 	case '+':
719 	    if (noSpecials) {
720 		/*
721 		 * We're not actually executing anything...
722 		 * but this one needs to be - use compat mode just for it.
723 		 */
724 		CompatRunCommand(cmdp, job->node);
725 		return 0;
726 	    }
727 	    break;
728 	}
729 	cmd++;
730     }
731 
732     while (isspace((unsigned char) *cmd))
733 	cmd++;
734 
735     /*
736      * If the shell doesn't have error control the alternate echo'ing will
737      * be done (to avoid showing additional error checking code)
738      * and this will need the characters '$ ` \ "' escaped
739      */
740 
741     if (!commandShell->hasErrCtl) {
742 	/* Worst that could happen is every char needs escaping. */
743 	escCmd = emalloc((strlen(cmd) * 2) + 1);
744 	for (i = 0, j= 0; cmd[i] != '\0'; i++, j++) {
745 		if (cmd[i] == '$' || cmd[i] == '`' || cmd[i] == '\\' ||
746 			cmd[i] == '"')
747 			escCmd[j++] = '\\';
748 		escCmd[j] = cmd[i];
749 	}
750 	escCmd[j] = 0;
751     }
752 
753     if (shutUp) {
754 	if (!(job->flags & JOB_SILENT) && !noSpecials &&
755 	    commandShell->hasEchoCtl) {
756 		DBPRINTF("%s\n", commandShell->echoOff);
757 	} else {
758 	    if (commandShell->hasErrCtl)
759 		shutUp = FALSE;
760 	}
761     }
762 
763     if (errOff) {
764 	if ( !(job->flags & JOB_IGNERR) && !noSpecials) {
765 	    if (commandShell->hasErrCtl) {
766 		/*
767 		 * we don't want the error-control commands showing
768 		 * up either, so we turn off echoing while executing
769 		 * them. We could put another field in the shell
770 		 * structure to tell JobDoOutput to look for this
771 		 * string too, but why make it any more complex than
772 		 * it already is?
773 		 */
774 		if (!(job->flags & JOB_SILENT) && !shutUp &&
775 		    commandShell->hasEchoCtl) {
776 			DBPRINTF("%s\n", commandShell->echoOff);
777 			DBPRINTF("%s\n", commandShell->ignErr);
778 			DBPRINTF("%s\n", commandShell->echoOn);
779 		} else {
780 			DBPRINTF("%s\n", commandShell->ignErr);
781 		}
782 	    } else if (commandShell->ignErr &&
783 		      (*commandShell->ignErr != '\0'))
784 	    {
785 		/*
786 		 * The shell has no error control, so we need to be
787 		 * weird to get it to ignore any errors from the command.
788 		 * If echoing is turned on, we turn it off and use the
789 		 * errCheck template to echo the command. Leave echoing
790 		 * off so the user doesn't see the weirdness we go through
791 		 * to ignore errors. Set cmdTemplate to use the weirdness
792 		 * instead of the simple "%s\n" template.
793 		 */
794 		if (!(job->flags & JOB_SILENT) && !shutUp) {
795 			if (commandShell->hasEchoCtl) {
796 				DBPRINTF("%s\n", commandShell->echoOff);
797 			}
798 			DBPRINTF(commandShell->errCheck, escCmd);
799 			shutUp = TRUE;
800 		} else {
801 			if (!shutUp) {
802 				DBPRINTF(commandShell->errCheck, escCmd);
803 			}
804 		}
805 		cmdTemplate = commandShell->ignErr;
806 		/*
807 		 * The error ignoration (hee hee) is already taken care
808 		 * of by the ignErr template, so pretend error checking
809 		 * is still on.
810 		 */
811 		errOff = FALSE;
812 	    } else {
813 		errOff = FALSE;
814 	    }
815 	} else {
816 	    errOff = FALSE;
817 	}
818     } else {
819 
820 	/*
821 	 * If errors are being checked and the shell doesn't have error control
822 	 * but does supply an errOut template, then setup commands to run
823 	 * through it.
824 	 */
825 
826 	if (!commandShell->hasErrCtl && commandShell->errOut &&
827 	    (*commandShell->errOut != '\0')) {
828 		if (!(job->flags & JOB_SILENT) && !shutUp) {
829 			if (commandShell->hasEchoCtl) {
830 				DBPRINTF("%s\n", commandShell->echoOff);
831 			}
832 			DBPRINTF(commandShell->errCheck, escCmd);
833 			shutUp = TRUE;
834 		}
835 		/* If it's a comment line or blank, treat as an ignored error */
836 		if ((escCmd[0] == commandShell->commentChar) ||
837 		    (escCmd[0] == 0))
838 			cmdTemplate = commandShell->ignErr;
839 		else
840 			cmdTemplate = commandShell->errOut;
841 		errOff = FALSE;
842 	}
843     }
844 
845     if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0 &&
846 	(job->flags & JOB_TRACED) == 0) {
847 	    DBPRINTF("set -%s\n", "x");
848 	    job->flags |= JOB_TRACED;
849     }
850 
851     if ((cp = Check_Cwd_Cmd(cmd)) != NULL) {
852 	    DBPRINTF("test -d %s && ", cp);
853 	    DBPRINTF("cd %s\n", cp);
854     }
855 
856     DBPRINTF(cmdTemplate, cmd);
857     free(cmdStart);
858     if (escCmd)
859         free(escCmd);
860     if (errOff) {
861 	/*
862 	 * If echoing is already off, there's no point in issuing the
863 	 * echoOff command. Otherwise we issue it and pretend it was on
864 	 * for the whole command...
865 	 */
866 	if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl){
867 	    DBPRINTF("%s\n", commandShell->echoOff);
868 	    shutUp = TRUE;
869 	}
870 	DBPRINTF("%s\n", commandShell->errCheck);
871     }
872     if (shutUp && commandShell->hasEchoCtl) {
873 	DBPRINTF("%s\n", commandShell->echoOn);
874     }
875     if (cp != NULL) {
876 	    DBPRINTF("test -d %s && ", cp);
877 	    DBPRINTF("cd %s\n", Var_Value(".OBJDIR", VAR_GLOBAL, &tmp));
878     }
879     return 0;
880 }
881 
882 /*-
883  *-----------------------------------------------------------------------
884  * JobSaveCommand --
885  *	Save a command to be executed when everything else is done.
886  *	Callback function for JobFinish...
887  *
888  * Results:
889  *	Always returns 0
890  *
891  * Side Effects:
892  *	The command is tacked onto the end of postCommands's commands list.
893  *
894  *-----------------------------------------------------------------------
895  */
896 static int
897 JobSaveCommand(ClientData cmd, ClientData gn)
898 {
899     cmd = Var_Subst(NULL, (char *)cmd, (GNode *)gn, FALSE);
900     (void)Lst_AtEnd(postCommands->commands, cmd);
901     return(0);
902 }
903 
904 
905 /*-
906  *-----------------------------------------------------------------------
907  * JobClose --
908  *	Called to close both input and output pipes when a job is finished.
909  *
910  * Results:
911  *	Nada
912  *
913  * Side Effects:
914  *	The file descriptors associated with the job are closed.
915  *
916  *-----------------------------------------------------------------------
917  */
918 static void
919 JobClose(Job *job)
920 {
921     clearfd(job);
922     (void)close(job->outPipe);
923     job->outPipe = -1;
924 
925     JobDoOutput(job, TRUE);
926     (void)close(job->inPipe);
927     job->inPipe = -1;
928 }
929 
930 /*-
931  *-----------------------------------------------------------------------
932  * JobFinish  --
933  *	Do final processing for the given job including updating
934  *	parents and starting new jobs as available/necessary. Note
935  *	that we pay no attention to the JOB_IGNERR flag here.
936  *	This is because when we're called because of a noexecute flag
937  *	or something, jstat.w_status is 0 and when called from
938  *	Job_CatchChildren, the status is zeroed if it s/b ignored.
939  *
940  * Input:
941  *	job		job to finish
942  *	status		sub-why job went away
943  *
944  * Results:
945  *	None
946  *
947  * Side Effects:
948  *	Final commands for the job are placed on postCommands.
949  *
950  *	If we got an error and are aborting (aborting == ABORT_ERROR) and
951  *	the job list is now empty, we are done for the day.
952  *	If we recognized an error (errors !=0), we set the aborting flag
953  *	to ABORT_ERROR so no more jobs will be started.
954  *-----------------------------------------------------------------------
955  */
956 /*ARGSUSED*/
957 static void
958 JobFinish(Job *job, int status)
959 {
960     Boolean 	 done, return_job_token;
961 
962     if (DEBUG(JOB)) {
963 	fprintf(debug_file, "Jobfinish: %d [%s], status %d\n",
964 				job->pid, job->node->name, status);
965     }
966 
967     if ((WIFEXITED(status) &&
968 	 (((WEXITSTATUS(status) != 0) && !(job->flags & JOB_IGNERR)))) ||
969 	WIFSIGNALED(status))
970     {
971 	/*
972 	 * If it exited non-zero and either we're doing things our
973 	 * way or we're not ignoring errors, the job is finished.
974 	 * Similarly, if the shell died because of a signal
975 	 * the job is also finished. In these
976 	 * cases, finish out the job's output before printing the exit
977 	 * status...
978 	 */
979 	JobClose(job);
980 	if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
981 	   (void)fclose(job->cmdFILE);
982 	   job->cmdFILE = NULL;
983 	}
984 	done = TRUE;
985     } else if (WIFEXITED(status)) {
986 	/*
987 	 * Deal with ignored errors in -B mode. We need to print a message
988 	 * telling of the ignored error as well as setting status.w_status
989 	 * to 0 so the next command gets run. To do this, we set done to be
990 	 * TRUE if in -B mode and the job exited non-zero.
991 	 */
992 	done = WEXITSTATUS(status) != 0;
993 	/*
994 	 * Old comment said: "Note we don't
995 	 * want to close down any of the streams until we know we're at the
996 	 * end."
997 	 * But we do. Otherwise when are we going to print the rest of the
998 	 * stuff?
999 	 */
1000 	JobClose(job);
1001     } else {
1002 	/*
1003 	 * No need to close things down or anything.
1004 	 */
1005 	done = FALSE;
1006     }
1007 
1008     if (done) {
1009 	if (WIFEXITED(status)) {
1010 	    if (DEBUG(JOB)) {
1011 		(void)fprintf(debug_file, "Process %d [%s] exited.\n",
1012 				job->pid, job->node->name);
1013 	    }
1014 	    if (WEXITSTATUS(status) != 0) {
1015 		if (job->node != lastNode) {
1016 		    MESSAGE(stdout, job->node);
1017 		    lastNode = job->node;
1018 		}
1019 		(void)printf("*** [%s] Error code %d%s\n",
1020 				job->node->name,
1021 			       WEXITSTATUS(status),
1022 			       (job->flags & JOB_IGNERR) ? "(ignored)" : "");
1023 		if (job->flags & JOB_IGNERR)
1024 		    status = 0;
1025 	    } else if (DEBUG(JOB)) {
1026 		if (job->node != lastNode) {
1027 		    MESSAGE(stdout, job->node);
1028 		    lastNode = job->node;
1029 		}
1030 		(void)printf("*** [%s] Completed successfully\n",
1031 				job->node->name);
1032 	    }
1033 	} else {
1034 	    if (job->node != lastNode) {
1035 		MESSAGE(stdout, job->node);
1036 		lastNode = job->node;
1037 	    }
1038 	    (void)printf("*** [%s] Signal %d\n",
1039 			job->node->name, WTERMSIG(status));
1040 	}
1041 	(void)fflush(stdout);
1042     }
1043 
1044     return_job_token = FALSE;
1045 
1046     Trace_Log(JOBEND, job);
1047     if (!(job->flags & JOB_SPECIAL)) {
1048 	if ((status != 0) ||
1049 		(aborting == ABORT_ERROR) ||
1050 		(aborting == ABORT_INTERRUPT))
1051 	    return_job_token = TRUE;
1052     }
1053 
1054     if ((aborting != ABORT_ERROR) && (aborting != ABORT_INTERRUPT) && (status == 0)) {
1055 	/*
1056 	 * As long as we aren't aborting and the job didn't return a non-zero
1057 	 * status that we shouldn't ignore, we call Make_Update to update
1058 	 * the parents. In addition, any saved commands for the node are placed
1059 	 * on the .END target.
1060 	 */
1061 	if (job->tailCmds != NILLNODE) {
1062 	    Lst_ForEachFrom(job->node->commands, job->tailCmds,
1063 			     JobSaveCommand,
1064 			    job->node);
1065 	}
1066 	job->node->made = MADE;
1067 	if (!(job->flags & JOB_SPECIAL))
1068 	    return_job_token = TRUE;
1069 	Make_Update(job->node);
1070 	job->job_state = JOB_ST_FREE;
1071     } else if (status != 0) {
1072 	errors += 1;
1073 	job->job_state = JOB_ST_FREE;
1074     }
1075 
1076     /*
1077      * Set aborting if any error.
1078      */
1079     if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
1080 	/*
1081 	 * If we found any errors in this batch of children and the -k flag
1082 	 * wasn't given, we set the aborting flag so no more jobs get
1083 	 * started.
1084 	 */
1085 	aborting = ABORT_ERROR;
1086     }
1087 
1088     if (return_job_token)
1089 	Job_TokenReturn();
1090 
1091     if (aborting == ABORT_ERROR && jobTokensRunning == 0) {
1092 	/*
1093 	 * If we are aborting and the job table is now empty, we finish.
1094 	 */
1095 	Finish(errors);
1096     }
1097 }
1098 
1099 /*-
1100  *-----------------------------------------------------------------------
1101  * Job_Touch --
1102  *	Touch the given target. Called by JobStart when the -t flag was
1103  *	given
1104  *
1105  * Input:
1106  *	gn		the node of the file to touch
1107  *	silent		TRUE if should not print message
1108  *
1109  * Results:
1110  *	None
1111  *
1112  * Side Effects:
1113  *	The data modification of the file is changed. In addition, if the
1114  *	file did not exist, it is created.
1115  *-----------------------------------------------------------------------
1116  */
1117 void
1118 Job_Touch(GNode *gn, Boolean silent)
1119 {
1120     int		  streamID;   	/* ID of stream opened to do the touch */
1121     struct utimbuf times;	/* Times for utime() call */
1122 
1123     if (gn->type & (OP_JOIN|OP_USE|OP_USEBEFORE|OP_EXEC|OP_OPTIONAL|OP_PHONY)) {
1124 	/*
1125 	 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets
1126 	 * and, as such, shouldn't really be created.
1127 	 */
1128 	return;
1129     }
1130 
1131     if (!silent || NoExecute(gn)) {
1132 	(void)fprintf(stdout, "touch %s\n", gn->name);
1133 	(void)fflush(stdout);
1134     }
1135 
1136     if (NoExecute(gn)) {
1137 	return;
1138     }
1139 
1140     if (gn->type & OP_ARCHV) {
1141 	Arch_Touch(gn);
1142     } else if (gn->type & OP_LIB) {
1143 	Arch_TouchLib(gn);
1144     } else {
1145 	char	*file = gn->path ? gn->path : gn->name;
1146 
1147 	times.actime = times.modtime = now;
1148 	if (utime(file, &times) < 0){
1149 	    streamID = open(file, O_RDWR | O_CREAT, 0666);
1150 
1151 	    if (streamID >= 0) {
1152 		char	c;
1153 
1154 		/*
1155 		 * Read and write a byte to the file to change the
1156 		 * modification time, then close the file.
1157 		 */
1158 		if (read(streamID, &c, 1) == 1) {
1159 		    (void)lseek(streamID, (off_t)0, SEEK_SET);
1160 		    (void)write(streamID, &c, 1);
1161 		}
1162 
1163 		(void)close(streamID);
1164 	    } else {
1165 		(void)fprintf(stdout, "*** couldn't touch %s: %s",
1166 			       file, strerror(errno));
1167 		(void)fflush(stdout);
1168 	    }
1169 	}
1170     }
1171 }
1172 
1173 /*-
1174  *-----------------------------------------------------------------------
1175  * Job_CheckCommands --
1176  *	Make sure the given node has all the commands it needs.
1177  *
1178  * Input:
1179  *	gn		The target whose commands need verifying
1180  *	abortProc	Function to abort with message
1181  *
1182  * Results:
1183  *	TRUE if the commands list is/was ok.
1184  *
1185  * Side Effects:
1186  *	The node will have commands from the .DEFAULT rule added to it
1187  *	if it needs them.
1188  *-----------------------------------------------------------------------
1189  */
1190 Boolean
1191 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1192 {
1193     if (OP_NOP(gn->type) && Lst_IsEmpty(gn->commands) &&
1194 	((gn->type & OP_LIB) == 0 || Lst_IsEmpty(gn->children))) {
1195 	/*
1196 	 * No commands. Look for .DEFAULT rule from which we might infer
1197 	 * commands
1198 	 */
1199 	if ((DEFAULT != NILGNODE) && !Lst_IsEmpty(DEFAULT->commands) &&
1200 		(gn->type & OP_SPECIAL) == 0) {
1201 	    char *p1;
1202 	    /*
1203 	     * Make only looks for a .DEFAULT if the node was never the
1204 	     * target of an operator, so that's what we do too. If
1205 	     * a .DEFAULT was given, we substitute its commands for gn's
1206 	     * commands and set the IMPSRC variable to be the target's name
1207 	     * The DEFAULT node acts like a transformation rule, in that
1208 	     * gn also inherits any attributes or sources attached to
1209 	     * .DEFAULT itself.
1210 	     */
1211 	    Make_HandleUse(DEFAULT, gn);
1212 	    Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn, 0);
1213 	    if (p1)
1214 		free(p1);
1215 	} else if (Dir_MTime(gn) == 0 && (gn->type & OP_SPECIAL) == 0) {
1216 	    /*
1217 	     * The node wasn't the target of an operator we have no .DEFAULT
1218 	     * rule to go on and the target doesn't already exist. There's
1219 	     * nothing more we can do for this branch. If the -k flag wasn't
1220 	     * given, we stop in our tracks, otherwise we just don't update
1221 	     * this node's parents so they never get examined.
1222 	     */
1223 	    static const char msg[] = ": don't know how to make";
1224 
1225 	    if (gn->type & OP_OPTIONAL) {
1226 		(void)fprintf(stdout, "%s%s %s(ignored)\n", progname,
1227 		    msg, gn->name);
1228 		(void)fflush(stdout);
1229 	    } else if (keepgoing) {
1230 		(void)fprintf(stdout, "%s%s %s(continuing)\n", progname,
1231 		    msg, gn->name);
1232 		(void)fflush(stdout);
1233   		return FALSE;
1234 	    } else {
1235 		(*abortProc)("%s%s %s. Stop", progname, msg, gn->name);
1236 		return FALSE;
1237 	    }
1238 	}
1239     }
1240     return TRUE;
1241 }
1242 
1243 /*-
1244  *-----------------------------------------------------------------------
1245  * JobExec --
1246  *	Execute the shell for the given job. Called from JobStart
1247  *
1248  * Input:
1249  *	job		Job to execute
1250  *
1251  * Results:
1252  *	None.
1253  *
1254  * Side Effects:
1255  *	A shell is executed, outputs is altered and the Job structure added
1256  *	to the job table.
1257  *
1258  *-----------------------------------------------------------------------
1259  */
1260 static void
1261 JobExec(Job *job, char **argv)
1262 {
1263     int	    	  cpid;	    	/* ID of new child */
1264     sigset_t	  mask;
1265 
1266     job->flags &= ~JOB_TRACED;
1267 
1268     if (DEBUG(JOB)) {
1269 	int 	  i;
1270 
1271 	(void)fprintf(debug_file, "Running %s %sly\n", job->node->name, "local");
1272 	(void)fprintf(debug_file, "\tCommand: ");
1273 	for (i = 0; argv[i] != NULL; i++) {
1274 	    (void)fprintf(debug_file, "%s ", argv[i]);
1275 	}
1276  	(void)fprintf(debug_file, "\n");
1277     }
1278 
1279     /*
1280      * Some jobs produce no output and it's disconcerting to have
1281      * no feedback of their running (since they produce no output, the
1282      * banner with their name in it never appears). This is an attempt to
1283      * provide that feedback, even if nothing follows it.
1284      */
1285     if ((lastNode != job->node) && !(job->flags & JOB_SILENT)) {
1286 	MESSAGE(stdout, job->node);
1287 	lastNode = job->node;
1288     }
1289 
1290     /* No interruptions until this job is on the `jobs' list */
1291     JobSigLock(&mask);
1292 
1293     /* Pre-emptively mark job running, pid still zero though */
1294     job->job_state = JOB_ST_RUNNING;
1295 
1296     cpid = vfork();
1297     if (cpid == -1)
1298 	Punt("Cannot vfork: %s", strerror(errno));
1299 
1300     if (cpid == 0) {
1301 	/* Child */
1302 
1303 	/*
1304 	 * Reset all signal handlers; this is necessary because we also
1305 	 * need to unblock signals before we exec(2).
1306 	 */
1307 	JobSigReset();
1308 
1309 	/* Now unblock signals */
1310 	sigemptyset(&mask);
1311 	JobSigUnlock(&mask);
1312 
1313 	/*
1314 	 * Must duplicate the input stream down to the child's input and
1315 	 * reset it to the beginning (again). Since the stream was marked
1316 	 * close-on-exec, we must clear that bit in the new input.
1317 	 */
1318 	if (dup2(FILENO(job->cmdFILE), 0) == -1) {
1319 	    execError("dup2", "job->cmdFILE");
1320 	    _exit(1);
1321 	}
1322 	(void)fcntl(0, F_SETFD, 0);
1323 	(void)lseek(0, (off_t)0, SEEK_SET);
1324 
1325 	if (job->node->type & OP_MAKE) {
1326 		/*
1327 		 * Pass job token pipe to submakes.
1328 		 */
1329 		fcntl(tokenWaitJob.inPipe, F_SETFD, 0);
1330 		fcntl(tokenWaitJob.outPipe, F_SETFD, 0);
1331 	}
1332 
1333 	/*
1334 	 * Set up the child's output to be routed through the pipe
1335 	 * we've created for it.
1336 	 */
1337 	if (dup2(job->outPipe, 1) == -1) {
1338 	    execError("dup2", "job->outPipe");
1339 	    _exit(1);
1340 	}
1341 	/*
1342 	 * The output channels are marked close on exec. This bit was
1343 	 * duplicated by the dup2(on some systems), so we have to clear
1344 	 * it before routing the shell's error output to the same place as
1345 	 * its standard output.
1346 	 */
1347 	(void)fcntl(1, F_SETFD, 0);
1348 	if (dup2(1, 2) == -1) {
1349 	    execError("dup2", "1, 2");
1350 	    _exit(1);
1351 	}
1352 
1353 	/*
1354 	 * We want to switch the child into a different process family so
1355 	 * we can kill it and all its descendants in one fell swoop,
1356 	 * by killing its process family, but not commit suicide.
1357 	 */
1358 #if defined(SYSV)
1359 	/* XXX: dsl - I'm sure this should be setpgrp()... */
1360 	(void)setsid();
1361 #else
1362 	(void)setpgid(0, getpid());
1363 #endif
1364 
1365 	Var_ExportVars();
1366 
1367 	(void)execv(shellPath, argv);
1368 	execError("exec", shellPath);
1369 	_exit(1);
1370     }
1371 
1372     /* Parent, continuing after the child exec */
1373     job->pid = cpid;
1374 
1375     Trace_Log(JOBSTART, job);
1376 
1377     /*
1378      * Set the current position in the buffer to the beginning
1379      * and mark another stream to watch in the outputs mask
1380      */
1381     job->curPos = 0;
1382 
1383     watchfd(job);
1384 
1385     if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1386 	(void)fclose(job->cmdFILE);
1387 	job->cmdFILE = NULL;
1388     }
1389 
1390     /*
1391      * Now the job is actually running, add it to the table.
1392      */
1393     if (DEBUG(JOB)) {
1394 	fprintf(debug_file, "JobExec(%s): pid %d added to jobs table\n",
1395 		job->node->name, job->pid);
1396 	job_table_dump("job started");
1397     }
1398     JobSigUnlock(&mask);
1399 }
1400 
1401 /*-
1402  *-----------------------------------------------------------------------
1403  * JobMakeArgv --
1404  *	Create the argv needed to execute the shell for a given job.
1405  *
1406  *
1407  * Results:
1408  *
1409  * Side Effects:
1410  *
1411  *-----------------------------------------------------------------------
1412  */
1413 static void
1414 JobMakeArgv(Job *job, char **argv)
1415 {
1416     int	    	  argc;
1417     static char args[10]; 	/* For merged arguments */
1418 
1419     argv[0] = UNCONST(shellName);
1420     argc = 1;
1421 
1422     if ((commandShell->exit && (*commandShell->exit != '-')) ||
1423 	(commandShell->echo && (*commandShell->echo != '-')))
1424     {
1425 	/*
1426 	 * At least one of the flags doesn't have a minus before it, so
1427 	 * merge them together. Have to do this because the *(&(@*#*&#$#
1428 	 * Bourne shell thinks its second argument is a file to source.
1429 	 * Grrrr. Note the ten-character limitation on the combined arguments.
1430 	 */
1431 	(void)snprintf(args, sizeof(args), "-%s%s",
1432 		      ((job->flags & JOB_IGNERR) ? "" :
1433 		       (commandShell->exit ? commandShell->exit : "")),
1434 		      ((job->flags & JOB_SILENT) ? "" :
1435 		       (commandShell->echo ? commandShell->echo : "")));
1436 
1437 	if (args[1]) {
1438 	    argv[argc] = args;
1439 	    argc++;
1440 	}
1441     } else {
1442 	if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1443 	    argv[argc] = UNCONST(commandShell->exit);
1444 	    argc++;
1445 	}
1446 	if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1447 	    argv[argc] = UNCONST(commandShell->echo);
1448 	    argc++;
1449 	}
1450     }
1451     argv[argc] = NULL;
1452 }
1453 
1454 /*-
1455  *-----------------------------------------------------------------------
1456  * JobStart  --
1457  *	Start a target-creation process going for the target described
1458  *	by the graph node gn.
1459  *
1460  * Input:
1461  *	gn		target to create
1462  *	flags		flags for the job to override normal ones.
1463  *			e.g. JOB_SPECIAL or JOB_IGNDOTS
1464  *	previous	The previous Job structure for this node, if any.
1465  *
1466  * Results:
1467  *	JOB_ERROR if there was an error in the commands, JOB_FINISHED
1468  *	if there isn't actually anything left to do for the job and
1469  *	JOB_RUNNING if the job has been started.
1470  *
1471  * Side Effects:
1472  *	A new Job node is created and added to the list of running
1473  *	jobs. PMake is forked and a child shell created.
1474  *
1475  * NB: I'm fairly sure that this code is never called with JOB_SPECIAL set
1476  *     JOB_IGNDOTS is never set (dsl)
1477  *     Also the return value is ignored by everyone.
1478  *-----------------------------------------------------------------------
1479  */
1480 static int
1481 JobStart(GNode *gn, int flags)
1482 {
1483     Job		  *job;       /* new job descriptor */
1484     char	  *argv[10];  /* Argument vector to shell */
1485     Boolean	  cmdsOK;     /* true if the nodes commands were all right */
1486     Boolean 	  noExec;     /* Set true if we decide not to run the job */
1487     int		  tfd;	      /* File descriptor to the temp file */
1488 
1489     for (job = job_table; job < job_table_end; job++) {
1490 	if (job->job_state == JOB_ST_FREE)
1491 	    break;
1492     }
1493     if (job >= job_table_end)
1494 	Punt("JobStart no job slots vacant");
1495 
1496     memset(job, 0, sizeof *job);
1497     job->job_state = JOB_ST_SETUP;
1498     if (gn->type & OP_SPECIAL)
1499 	flags |= JOB_SPECIAL;
1500 
1501     job->node = gn;
1502     job->tailCmds = NILLNODE;
1503 
1504     /*
1505      * Set the initial value of the flags for this job based on the global
1506      * ones and the node's attributes... Any flags supplied by the caller
1507      * are also added to the field.
1508      */
1509     job->flags = 0;
1510     if (Targ_Ignore(gn)) {
1511 	job->flags |= JOB_IGNERR;
1512     }
1513     if (Targ_Silent(gn)) {
1514 	job->flags |= JOB_SILENT;
1515     }
1516     job->flags |= flags;
1517 
1518     /*
1519      * Check the commands now so any attributes from .DEFAULT have a chance
1520      * to migrate to the node
1521      */
1522     cmdsOK = Job_CheckCommands(gn, Error);
1523 
1524     job->inPollfd = NULL;
1525     /*
1526      * If the -n flag wasn't given, we open up OUR (not the child's)
1527      * temporary file to stuff commands in it. The thing is rd/wr so we don't
1528      * need to reopen it to feed it to the shell. If the -n flag *was* given,
1529      * we just set the file to be stdout. Cute, huh?
1530      */
1531     if (((gn->type & OP_MAKE) && !(noRecursiveExecute)) ||
1532 	    (!noExecute && !touchFlag)) {
1533 	/*
1534 	 * tfile is the name of a file into which all shell commands are
1535 	 * put. It is used over by removing it before the child shell is
1536 	 * executed. The XXXXXX in the string are replaced by the pid of
1537 	 * the make process in a 6-character field with leading zeroes.
1538 	 */
1539 	char     tfile[sizeof(TMPPAT)];
1540 	sigset_t mask;
1541 	/*
1542 	 * We're serious here, but if the commands were bogus, we're
1543 	 * also dead...
1544 	 */
1545 	if (!cmdsOK) {
1546 	    DieHorribly();
1547 	}
1548 
1549 	JobSigLock(&mask);
1550 	(void)strcpy(tfile, TMPPAT);
1551 	if ((tfd = mkstemp(tfile)) == -1)
1552 	    Punt("Could not create temporary file %s", strerror(errno));
1553 	if (!DEBUG(SCRIPT))
1554 		(void)eunlink(tfile);
1555 	JobSigUnlock(&mask);
1556 
1557 	job->cmdFILE = fdopen(tfd, "w+");
1558 	if (job->cmdFILE == NULL) {
1559 	    Punt("Could not fdopen %s", tfile);
1560 	}
1561 	(void)fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1562 	/*
1563 	 * Send the commands to the command file, flush all its buffers then
1564 	 * rewind and remove the thing.
1565 	 */
1566 	noExec = FALSE;
1567 
1568 	/*
1569 	 * We can do all the commands at once. hooray for sanity
1570 	 */
1571 	numCommands = 0;
1572 	Lst_ForEach(gn->commands, JobPrintCommand, job);
1573 
1574 	/*
1575 	 * If we didn't print out any commands to the shell script,
1576 	 * there's not much point in executing the shell, is there?
1577 	 */
1578 	if (numCommands == 0) {
1579 	    noExec = TRUE;
1580 	}
1581     } else if (NoExecute(gn)) {
1582 	/*
1583 	 * Not executing anything -- just print all the commands to stdout
1584 	 * in one fell swoop. This will still set up job->tailCmds correctly.
1585 	 */
1586 	if (lastNode != gn) {
1587 	    MESSAGE(stdout, gn);
1588 	    lastNode = gn;
1589 	}
1590 	job->cmdFILE = stdout;
1591 	/*
1592 	 * Only print the commands if they're ok, but don't die if they're
1593 	 * not -- just let the user know they're bad and keep going. It
1594 	 * doesn't do any harm in this case and may do some good.
1595 	 */
1596 	if (cmdsOK) {
1597 	    Lst_ForEach(gn->commands, JobPrintCommand, job);
1598 	}
1599 	/*
1600 	 * Don't execute the shell, thank you.
1601 	 */
1602 	noExec = TRUE;
1603     } else {
1604 	/*
1605 	 * Just touch the target and note that no shell should be executed.
1606 	 * Set cmdFILE to stdout to make life easier. Check the commands, too,
1607 	 * but don't die if they're no good -- it does no harm to keep working
1608 	 * up the graph.
1609 	 */
1610 	job->cmdFILE = stdout;
1611     	Job_Touch(gn, job->flags&JOB_SILENT);
1612 	noExec = TRUE;
1613     }
1614     /* Just in case it isn't already... */
1615     (void)fflush(job->cmdFILE);
1616 
1617     /*
1618      * If we're not supposed to execute a shell, don't.
1619      */
1620     if (noExec) {
1621 	if (!(job->flags & JOB_SPECIAL))
1622 	    Job_TokenReturn();
1623 	/*
1624 	 * Unlink and close the command file if we opened one
1625 	 */
1626 	if (job->cmdFILE != stdout) {
1627 	    if (job->cmdFILE != NULL) {
1628 		(void)fclose(job->cmdFILE);
1629 		job->cmdFILE = NULL;
1630 	    }
1631 	}
1632 
1633 	/*
1634 	 * We only want to work our way up the graph if we aren't here because
1635 	 * the commands for the job were no good.
1636 	 */
1637 	if (cmdsOK && aborting == 0) {
1638 	    if (job->tailCmds != NILLNODE) {
1639 		Lst_ForEachFrom(job->node->commands, job->tailCmds,
1640 				JobSaveCommand,
1641 			       job->node);
1642 	    }
1643 	    job->node->made = MADE;
1644 	    Make_Update(job->node);
1645 	}
1646 	job->job_state = JOB_ST_FREE;
1647 	return cmdsOK ? JOB_FINISHED : JOB_ERROR;
1648     }
1649 
1650     /*
1651      * Set up the control arguments to the shell. This is based on the flags
1652      * set earlier for this job.
1653      */
1654     JobMakeArgv(job, argv);
1655 
1656     /* Create the pipe by which we'll get the shell's output.  */
1657     JobCreatePipe(job, 3);
1658 
1659     JobExec(job, argv);
1660     return(JOB_RUNNING);
1661 }
1662 
1663 static char *
1664 JobOutput(Job *job, char *cp, char *endp, int msg)
1665 {
1666     char *ecp;
1667 
1668     if (commandShell->noPrint) {
1669 	ecp = Str_FindSubstring(cp, commandShell->noPrint);
1670 	while (ecp != NULL) {
1671 	    if (cp != ecp) {
1672 		*ecp = '\0';
1673 		if (!beSilent && msg && job->node != lastNode) {
1674 		    MESSAGE(stdout, job->node);
1675 		    lastNode = job->node;
1676 		}
1677 		/*
1678 		 * The only way there wouldn't be a newline after
1679 		 * this line is if it were the last in the buffer.
1680 		 * however, since the non-printable comes after it,
1681 		 * there must be a newline, so we don't print one.
1682 		 */
1683 		(void)fprintf(stdout, "%s", cp);
1684 		(void)fflush(stdout);
1685 	    }
1686 	    cp = ecp + commandShell->noPLen;
1687 	    if (cp != endp) {
1688 		/*
1689 		 * Still more to print, look again after skipping
1690 		 * the whitespace following the non-printable
1691 		 * command....
1692 		 */
1693 		cp++;
1694 		while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
1695 		    cp++;
1696 		}
1697 		ecp = Str_FindSubstring(cp, commandShell->noPrint);
1698 	    } else {
1699 		return cp;
1700 	    }
1701 	}
1702     }
1703     return cp;
1704 }
1705 
1706 /*-
1707  *-----------------------------------------------------------------------
1708  * JobDoOutput  --
1709  *	This function is called at different times depending on
1710  *	whether the user has specified that output is to be collected
1711  *	via pipes or temporary files. In the former case, we are called
1712  *	whenever there is something to read on the pipe. We collect more
1713  *	output from the given job and store it in the job's outBuf. If
1714  *	this makes up a line, we print it tagged by the job's identifier,
1715  *	as necessary.
1716  *	If output has been collected in a temporary file, we open the
1717  *	file and read it line by line, transfering it to our own
1718  *	output channel until the file is empty. At which point we
1719  *	remove the temporary file.
1720  *	In both cases, however, we keep our figurative eye out for the
1721  *	'noPrint' line for the shell from which the output came. If
1722  *	we recognize a line, we don't print it. If the command is not
1723  *	alone on the line (the character after it is not \0 or \n), we
1724  *	do print whatever follows it.
1725  *
1726  * Input:
1727  *	job		the job whose output needs printing
1728  *	finish		TRUE if this is the last time we'll be called
1729  *			for this job
1730  *
1731  * Results:
1732  *	None
1733  *
1734  * Side Effects:
1735  *	curPos may be shifted as may the contents of outBuf.
1736  *-----------------------------------------------------------------------
1737  */
1738 STATIC void
1739 JobDoOutput(Job *job, Boolean finish)
1740 {
1741     Boolean       gotNL = FALSE;  /* true if got a newline */
1742     Boolean       fbuf;  	  /* true if our buffer filled up */
1743     int		  nr;	      	  /* number of bytes read */
1744     int		  i;	      	  /* auxiliary index into outBuf */
1745     int		  max;	      	  /* limit for i (end of current data) */
1746     int		  nRead;      	  /* (Temporary) number of bytes read */
1747 
1748     /*
1749      * Read as many bytes as will fit in the buffer.
1750      */
1751 end_loop:
1752     gotNL = FALSE;
1753     fbuf = FALSE;
1754 
1755     nRead = read(job->inPipe, &job->outBuf[job->curPos],
1756 		     JOB_BUFSIZE - job->curPos);
1757     if (nRead < 0) {
1758 	if (errno == EAGAIN)
1759 	    return;
1760 	if (DEBUG(JOB)) {
1761 	    perror("JobDoOutput(piperead)");
1762 	}
1763 	nr = 0;
1764     } else {
1765 	nr = nRead;
1766     }
1767 
1768     /*
1769      * If we hit the end-of-file (the job is dead), we must flush its
1770      * remaining output, so pretend we read a newline if there's any
1771      * output remaining in the buffer.
1772      * Also clear the 'finish' flag so we stop looping.
1773      */
1774     if ((nr == 0) && (job->curPos != 0)) {
1775 	job->outBuf[job->curPos] = '\n';
1776 	nr = 1;
1777 	finish = FALSE;
1778     } else if (nr == 0) {
1779 	finish = FALSE;
1780     }
1781 
1782     /*
1783      * Look for the last newline in the bytes we just got. If there is
1784      * one, break out of the loop with 'i' as its index and gotNL set
1785      * TRUE.
1786      */
1787     max = job->curPos + nr;
1788     for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1789 	if (job->outBuf[i] == '\n') {
1790 	    gotNL = TRUE;
1791 	    break;
1792 	} else if (job->outBuf[i] == '\0') {
1793 	    /*
1794 	     * Why?
1795 	     */
1796 	    job->outBuf[i] = ' ';
1797 	}
1798     }
1799 
1800     if (!gotNL) {
1801 	job->curPos += nr;
1802 	if (job->curPos == JOB_BUFSIZE) {
1803 	    /*
1804 	     * If we've run out of buffer space, we have no choice
1805 	     * but to print the stuff. sigh.
1806 	     */
1807 	    fbuf = TRUE;
1808 	    i = job->curPos;
1809 	}
1810     }
1811     if (gotNL || fbuf) {
1812 	/*
1813 	 * Need to send the output to the screen. Null terminate it
1814 	 * first, overwriting the newline character if there was one.
1815 	 * So long as the line isn't one we should filter (according
1816 	 * to the shell description), we print the line, preceded
1817 	 * by a target banner if this target isn't the same as the
1818 	 * one for which we last printed something.
1819 	 * The rest of the data in the buffer are then shifted down
1820 	 * to the start of the buffer and curPos is set accordingly.
1821 	 */
1822 	job->outBuf[i] = '\0';
1823 	if (i >= job->curPos) {
1824 	    char *cp;
1825 
1826 	    cp = JobOutput(job, job->outBuf, &job->outBuf[i], FALSE);
1827 
1828 	    /*
1829 	     * There's still more in that thar buffer. This time, though,
1830 	     * we know there's no newline at the end, so we add one of
1831 	     * our own free will.
1832 	     */
1833 	    if (*cp != '\0') {
1834 		if (!beSilent && job->node != lastNode) {
1835 		    MESSAGE(stdout, job->node);
1836 		    lastNode = job->node;
1837 		}
1838 		(void)fprintf(stdout, "%s%s", cp, gotNL ? "\n" : "");
1839 		(void)fflush(stdout);
1840 	    }
1841 	}
1842 	if (i < max - 1) {
1843 	    /* shift the remaining characters down */
1844 	    (void)memcpy(job->outBuf, &job->outBuf[i + 1], max - (i + 1));
1845 	    job->curPos = max - (i + 1);
1846 
1847 	} else {
1848 	    /*
1849 	     * We have written everything out, so we just start over
1850 	     * from the start of the buffer. No copying. No nothing.
1851 	     */
1852 	    job->curPos = 0;
1853 	}
1854     }
1855     if (finish) {
1856 	/*
1857 	 * If the finish flag is true, we must loop until we hit
1858 	 * end-of-file on the pipe. This is guaranteed to happen
1859 	 * eventually since the other end of the pipe is now closed
1860 	 * (we closed it explicitly and the child has exited). When
1861 	 * we do get an EOF, finish will be set FALSE and we'll fall
1862 	 * through and out.
1863 	 */
1864 	goto end_loop;
1865     }
1866 }
1867 
1868 static void
1869 JobRun(GNode *targ)
1870 {
1871 #ifdef notyet
1872     /*
1873      * Unfortunately it is too complicated to run .BEGIN, .END,
1874      * and .INTERRUPT job in the parallel job module. This has
1875      * the nice side effect that it avoids a lot of other problems.
1876      */
1877     Lst lst = Lst_Init(FALSE);
1878     Lst_AtEnd(lst, targ);
1879     (void)Make_Run(lst);
1880     Lst_Destroy(lst, NOFREE);
1881     JobStart(targ, JOB_SPECIAL);
1882     while (jobTokensRunning) {
1883 	Job_CatchOutput();
1884     }
1885 #else
1886     Compat_Make(targ, targ);
1887     if (targ->made == ERROR) {
1888 	PrintOnError("\n\nStop.");
1889 	exit(1);
1890     }
1891 #endif
1892 }
1893 
1894 /*-
1895  *-----------------------------------------------------------------------
1896  * Job_CatchChildren --
1897  *	Handle the exit of a child. Called from Make_Make.
1898  *
1899  * Input:
1900  *	block		TRUE if should block on the wait
1901  *
1902  * Results:
1903  *	none.
1904  *
1905  * Side Effects:
1906  *	The job descriptor is removed from the list of children.
1907  *
1908  * Notes:
1909  *	We do waits, blocking or not, according to the wisdom of our
1910  *	caller, until there are no more children to report. For each
1911  *	job, call JobFinish to finish things off.
1912  *
1913  *-----------------------------------------------------------------------
1914  */
1915 
1916 void
1917 Job_CatchChildren(void)
1918 {
1919     int    	  pid;	    	/* pid of dead child */
1920     Job		  *job;	    	/* job descriptor for dead child */
1921     int	  	  status;   	/* Exit/termination status */
1922 
1923     /*
1924      * Don't even bother if we know there's no one around.
1925      */
1926     if (jobTokensRunning == 0)
1927 	return;
1928 
1929     while ((pid = waitpid((pid_t) -1, &status, WNOHANG | WUNTRACED)) > 0) {
1930 	if (DEBUG(JOB)) {
1931 	    (void)fprintf(debug_file, "Process %d exited/stopped status %x.\n", pid,
1932 	      status);
1933 	}
1934 
1935 	job = JobFindPid(pid, JOB_ST_RUNNING);
1936 	if (job == NULL) {
1937 	    if (!lurking_children)
1938 		Error("Child (%d) status %x not in table?", pid, status);
1939 	    continue;
1940 	}
1941 	if (WIFSTOPPED(status)) {
1942 	    if (DEBUG(JOB)) {
1943 		(void)fprintf(debug_file, "Process %d (%s) stopped.\n",
1944 				job->pid, job->node->name);
1945 	    }
1946 	    if (!make_suspended) {
1947 		    switch (WSTOPSIG(status)) {
1948 		    case SIGTSTP:
1949 			(void)printf("*** [%s] Suspended\n", job->node->name);
1950 			break;
1951 		    case SIGSTOP:
1952 			(void)printf("*** [%s] Stopped\n", job->node->name);
1953 			break;
1954 		    default:
1955 			(void)printf("*** [%s] Stopped -- signal %d\n",
1956 			    job->node->name, WSTOPSIG(status));
1957 		    }
1958 		    job->job_suspended = 1;
1959 	    }
1960 	    (void)fflush(stdout);
1961 	    continue;
1962 	}
1963 
1964 	job->job_state = JOB_ST_FINISHED;
1965 	job->exit_status = status;
1966 
1967 	JobFinish(job, status);
1968     }
1969 }
1970 
1971 /*-
1972  *-----------------------------------------------------------------------
1973  * Job_CatchOutput --
1974  *	Catch the output from our children, if we're using
1975  *	pipes do so. Otherwise just block time until we get a
1976  *	signal(most likely a SIGCHLD) since there's no point in
1977  *	just spinning when there's nothing to do and the reaping
1978  *	of a child can wait for a while.
1979  *
1980  * Results:
1981  *	None
1982  *
1983  * Side Effects:
1984  *	Output is read from pipes if we're piping.
1985  * -----------------------------------------------------------------------
1986  */
1987 void
1988 Job_CatchOutput(void)
1989 {
1990     int nready;
1991     Job *job;
1992     int i;
1993 
1994     (void)fflush(stdout);
1995 
1996     /* The first fd in the list is the job token pipe */
1997     nready = poll(fds + 1 - wantToken, nfds - 1 + wantToken, POLL_MSEC);
1998 
1999     if (nready < 0 || readyfd(&childExitJob)) {
2000 	char token = 0;
2001 	nready -= 1;
2002 	(void)read(childExitJob.inPipe, &token, 1);
2003 	if (token == DO_JOB_RESUME[0])
2004 	    /* Complete relay requested from our SIGCONT handler */
2005 	    JobRestartJobs();
2006 	Job_CatchChildren();
2007     }
2008 
2009     if (nready <= 0)
2010 	return;
2011 
2012     if (wantToken && readyfd(&tokenWaitJob))
2013 	nready--;
2014 
2015     for (i = 2; i < nfds; i++) {
2016 	if (!fds[i].revents)
2017 	    continue;
2018 	job = jobfds[i];
2019 	if (job->job_state != JOB_ST_RUNNING)
2020 	    continue;
2021 	JobDoOutput(job, FALSE);
2022     }
2023 }
2024 
2025 /*-
2026  *-----------------------------------------------------------------------
2027  * Job_Make --
2028  *	Start the creation of a target. Basically a front-end for
2029  *	JobStart used by the Make module.
2030  *
2031  * Results:
2032  *	None.
2033  *
2034  * Side Effects:
2035  *	Another job is started.
2036  *
2037  *-----------------------------------------------------------------------
2038  */
2039 void
2040 Job_Make(GNode *gn)
2041 {
2042     (void)JobStart(gn, 0);
2043 }
2044 
2045 void
2046 Shell_Init(void)
2047 {
2048     if (shellPath == NULL) {
2049 	/*
2050 	 * We are using the default shell, which may be an absolute
2051 	 * path if DEFSHELL_CUSTOM is defined.
2052 	 */
2053 	shellName = commandShell->name;
2054 #ifdef DEFSHELL_CUSTOM
2055 	if (*shellName == '/') {
2056 	    shellPath = shellName;
2057 	    shellName = strrchr(shellPath, '/');
2058 	    shellName++;
2059 	} else
2060 #endif
2061 	shellPath = str_concat(_PATH_DEFSHELLDIR, shellName, STR_ADDSLASH);
2062     }
2063     if (commandShell->exit == NULL) {
2064 	commandShell->exit = "";
2065     }
2066     if (commandShell->echo == NULL) {
2067 	commandShell->echo = "";
2068     }
2069 }
2070 
2071 /*-
2072  * Returns the string literal that is used in the current command shell
2073  * to produce a newline character.
2074  */
2075 const char *
2076 Shell_GetNewline(void)
2077 {
2078 
2079     return commandShell->newline;
2080 }
2081 
2082 void
2083 Job_SetPrefix(void)
2084 {
2085 
2086     if (targPrefix) {
2087 	free(targPrefix);
2088     } else if (!Var_Exists(MAKE_JOB_PREFIX, VAR_GLOBAL)) {
2089 	Var_Set(MAKE_JOB_PREFIX, "---", VAR_GLOBAL, 0);
2090     }
2091 
2092     targPrefix = Var_Subst(NULL, "${" MAKE_JOB_PREFIX "}", VAR_GLOBAL, 0);
2093 }
2094 
2095 /*-
2096  *-----------------------------------------------------------------------
2097  * Job_Init --
2098  *	Initialize the process module
2099  *
2100  * Input:
2101  *
2102  * Results:
2103  *	none
2104  *
2105  * Side Effects:
2106  *	lists and counters are initialized
2107  *-----------------------------------------------------------------------
2108  */
2109 void
2110 Job_Init(void)
2111 {
2112     GNode         *begin;     /* node for commands to do at the very start */
2113 
2114     /* Allocate space for all the job info */
2115     job_table = emalloc(maxJobs * sizeof *job_table);
2116     memset(job_table, 0, maxJobs * sizeof *job_table);
2117     job_table_end = job_table + maxJobs;
2118     wantToken =	0;
2119 
2120     aborting = 	  0;
2121     errors = 	  0;
2122 
2123     lastNode =	  NILGNODE;
2124 
2125     if (maxJobs == 1) {
2126 	/*
2127 	 * If only one job can run at a time, there's no need for a banner,
2128 	 * is there?
2129 	 */
2130 	targFmt = "";
2131     } else {
2132 	targFmt = TARG_FMT;
2133     }
2134 
2135     /*
2136      * There is a non-zero chance that we already have children.
2137      * eg after 'make -f- <<EOF'
2138      * Since their termination causes a 'Child (pid) not in table' message,
2139      * Collect the status of any that are already dead, and suppress the
2140      * error message if there are any undead ones.
2141      */
2142     for (;;) {
2143 	int rval, status;
2144 	rval = waitpid((pid_t) -1, &status, WNOHANG);
2145 	if (rval > 0)
2146 	    continue;
2147 	if (rval == 0)
2148 	    lurking_children = 1;
2149 	break;
2150     }
2151 
2152     Shell_Init();
2153 
2154     JobCreatePipe(&childExitJob, 3);
2155 
2156     /* We can only need to wait for tokens, children and output from each job */
2157     fds = emalloc(sizeof (*fds) * (2 + maxJobs));
2158     jobfds = emalloc(sizeof (*jobfds) * (2 + maxJobs));
2159 
2160     /* These are permanent entries and take slots 0 and 1 */
2161     watchfd(&tokenWaitJob);
2162     watchfd(&childExitJob);
2163 
2164     sigemptyset(&caught_signals);
2165     /*
2166      * Install a SIGCHLD handler.
2167      */
2168     (void)signal(SIGCHLD, JobChildSig);
2169     sigaddset(&caught_signals, SIGCHLD);
2170 
2171 #define ADDSIG(s,h)				\
2172     if (signal(s, SIG_IGN) != SIG_IGN) {	\
2173 	sigaddset(&caught_signals, s);		\
2174 	(void)signal(s, h);			\
2175     }
2176 
2177     /*
2178      * Catch the four signals that POSIX specifies if they aren't ignored.
2179      * JobPassSig will take care of calling JobInterrupt if appropriate.
2180      */
2181     ADDSIG(SIGINT, JobPassSig_int)
2182     ADDSIG(SIGHUP, JobPassSig_term)
2183     ADDSIG(SIGTERM, JobPassSig_term)
2184     ADDSIG(SIGQUIT, JobPassSig_term)
2185 
2186     /*
2187      * There are additional signals that need to be caught and passed if
2188      * either the export system wants to be told directly of signals or if
2189      * we're giving each job its own process group (since then it won't get
2190      * signals from the terminal driver as we own the terminal)
2191      */
2192     ADDSIG(SIGTSTP, JobPassSig_suspend)
2193     ADDSIG(SIGTTOU, JobPassSig_suspend)
2194     ADDSIG(SIGTTIN, JobPassSig_suspend)
2195     ADDSIG(SIGWINCH, JobCondPassSig)
2196     ADDSIG(SIGCONT, JobContinueSig)
2197 #undef ADDSIG
2198 
2199     begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2200 
2201     if (begin != NILGNODE) {
2202 	JobRun(begin);
2203 	if (begin->made == ERROR) {
2204 	    PrintOnError("\n\nStop.");
2205 	    exit(1);
2206 	}
2207     }
2208     postCommands = Targ_FindNode(".END", TARG_CREATE);
2209 }
2210 
2211 static void JobSigReset(void)
2212 {
2213 #define DELSIG(s)					\
2214     if (sigismember(&caught_signals, s)) {		\
2215 	(void)signal(s, SIG_DFL);			\
2216     }
2217 
2218     DELSIG(SIGINT)
2219     DELSIG(SIGHUP)
2220     DELSIG(SIGQUIT)
2221     DELSIG(SIGTERM)
2222     DELSIG(SIGTSTP)
2223     DELSIG(SIGTTOU)
2224     DELSIG(SIGTTIN)
2225     DELSIG(SIGWINCH)
2226     DELSIG(SIGCONT)
2227 #undef DELSIG
2228     (void)signal(SIGCHLD, SIG_DFL);
2229 }
2230 
2231 /*-
2232  *-----------------------------------------------------------------------
2233  * JobMatchShell --
2234  *	Find a shell in 'shells' given its name.
2235  *
2236  * Results:
2237  *	A pointer to the Shell structure.
2238  *
2239  * Side Effects:
2240  *	None.
2241  *
2242  *-----------------------------------------------------------------------
2243  */
2244 static Shell *
2245 JobMatchShell(const char *name)
2246 {
2247     Shell	*sh;
2248 
2249     for (sh = shells; sh->name != NULL; sh++) {
2250 	if (strcmp(name, sh->name) == 0)
2251 		return (sh);
2252     }
2253     return (NULL);
2254 }
2255 
2256 /*-
2257  *-----------------------------------------------------------------------
2258  * Job_ParseShell --
2259  *	Parse a shell specification and set up commandShell, shellPath
2260  *	and shellName appropriately.
2261  *
2262  * Input:
2263  *	line		The shell spec
2264  *
2265  * Results:
2266  *	FAILURE if the specification was incorrect.
2267  *
2268  * Side Effects:
2269  *	commandShell points to a Shell structure (either predefined or
2270  *	created from the shell spec), shellPath is the full path of the
2271  *	shell described by commandShell, while shellName is just the
2272  *	final component of shellPath.
2273  *
2274  * Notes:
2275  *	A shell specification consists of a .SHELL target, with dependency
2276  *	operator, followed by a series of blank-separated words. Double
2277  *	quotes can be used to use blanks in words. A backslash escapes
2278  *	anything (most notably a double-quote and a space) and
2279  *	provides the functionality it does in C. Each word consists of
2280  *	keyword and value separated by an equal sign. There should be no
2281  *	unnecessary spaces in the word. The keywords are as follows:
2282  *	    name  	    Name of shell.
2283  *	    path  	    Location of shell.
2284  *	    quiet 	    Command to turn off echoing.
2285  *	    echo  	    Command to turn echoing on
2286  *	    filter	    Result of turning off echoing that shouldn't be
2287  *	    	  	    printed.
2288  *	    echoFlag	    Flag to turn echoing on at the start
2289  *	    errFlag	    Flag to turn error checking on at the start
2290  *	    hasErrCtl	    True if shell has error checking control
2291  *	    newline	    String literal to represent a newline char
2292  *	    check 	    Command to turn on error checking if hasErrCtl
2293  *	    	  	    is TRUE or template of command to echo a command
2294  *	    	  	    for which error checking is off if hasErrCtl is
2295  *	    	  	    FALSE.
2296  *	    ignore	    Command to turn off error checking if hasErrCtl
2297  *	    	  	    is TRUE or template of command to execute a
2298  *	    	  	    command so as to ignore any errors it returns if
2299  *	    	  	    hasErrCtl is FALSE.
2300  *
2301  *-----------------------------------------------------------------------
2302  */
2303 ReturnStatus
2304 Job_ParseShell(char *line)
2305 {
2306     char	**words;
2307     char	**argv;
2308     int		argc;
2309     char	*path;
2310     Shell	newShell;
2311     Boolean	fullSpec = FALSE;
2312     Shell	*sh;
2313 
2314     while (isspace((unsigned char)*line)) {
2315 	line++;
2316     }
2317 
2318     if (shellArgv)
2319 	free(UNCONST(shellArgv));
2320 
2321     memset(&newShell, 0, sizeof(newShell));
2322 
2323     /*
2324      * Parse the specification by keyword
2325      */
2326     words = brk_string(line, &argc, TRUE, &path);
2327     shellArgv = path;
2328 
2329     for (path = NULL, argv = words; argc != 0; argc--, argv++) {
2330 	    if (strncmp(*argv, "path=", 5) == 0) {
2331 		path = &argv[0][5];
2332 	    } else if (strncmp(*argv, "name=", 5) == 0) {
2333 		newShell.name = &argv[0][5];
2334 	    } else {
2335 		if (strncmp(*argv, "quiet=", 6) == 0) {
2336 		    newShell.echoOff = &argv[0][6];
2337 		} else if (strncmp(*argv, "echo=", 5) == 0) {
2338 		    newShell.echoOn = &argv[0][5];
2339 		} else if (strncmp(*argv, "filter=", 7) == 0) {
2340 		    newShell.noPrint = &argv[0][7];
2341 		    newShell.noPLen = strlen(newShell.noPrint);
2342 		} else if (strncmp(*argv, "echoFlag=", 9) == 0) {
2343 		    newShell.echo = &argv[0][9];
2344 		} else if (strncmp(*argv, "errFlag=", 8) == 0) {
2345 		    newShell.exit = &argv[0][8];
2346 		} else if (strncmp(*argv, "hasErrCtl=", 10) == 0) {
2347 		    char c = argv[0][10];
2348 		    newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
2349 					   (c != 'T') && (c != 't'));
2350 		} else if (strncmp(*argv, "newline=", 8) == 0) {
2351 		    newShell.newline = &argv[0][8];
2352 		} else if (strncmp(*argv, "check=", 6) == 0) {
2353 		    newShell.errCheck = &argv[0][6];
2354 		} else if (strncmp(*argv, "ignore=", 7) == 0) {
2355 		    newShell.ignErr = &argv[0][7];
2356 		} else if (strncmp(*argv, "errout=", 7) == 0) {
2357 		    newShell.errOut = &argv[0][7];
2358 		} else if (strncmp(*argv, "comment=", 8) == 0) {
2359 		    newShell.commentChar = argv[0][8];
2360 		} else {
2361 		    Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"",
2362 				*argv);
2363 		    free(words);
2364 		    return(FAILURE);
2365 		}
2366 		fullSpec = TRUE;
2367 	    }
2368     }
2369 
2370     if (path == NULL) {
2371 	/*
2372 	 * If no path was given, the user wants one of the pre-defined shells,
2373 	 * yes? So we find the one s/he wants with the help of JobMatchShell
2374 	 * and set things up the right way. shellPath will be set up by
2375 	 * Job_Init.
2376 	 */
2377 	if (newShell.name == NULL) {
2378 	    Parse_Error(PARSE_FATAL, "Neither path nor name specified");
2379 	    free(words);
2380 	    return(FAILURE);
2381 	} else {
2382 	    if ((sh = JobMatchShell(newShell.name)) == NULL) {
2383 		    Parse_Error(PARSE_WARNING, "%s: No matching shell",
2384 				newShell.name);
2385 		    free(words);
2386 		    return(FAILURE);
2387 	    }
2388 	    commandShell = sh;
2389 	    shellName = newShell.name;
2390 	}
2391     } else {
2392 	/*
2393 	 * The user provided a path. If s/he gave nothing else (fullSpec is
2394 	 * FALSE), try and find a matching shell in the ones we know of.
2395 	 * Else we just take the specification at its word and copy it
2396 	 * to a new location. In either case, we need to record the
2397 	 * path the user gave for the shell.
2398 	 */
2399 	shellPath = path;
2400 	path = strrchr(path, '/');
2401 	if (path == NULL) {
2402 	    path = UNCONST(shellPath);
2403 	} else {
2404 	    path += 1;
2405 	}
2406 	if (newShell.name != NULL) {
2407 	    shellName = newShell.name;
2408 	} else {
2409 	    shellName = path;
2410 	}
2411 	if (!fullSpec) {
2412 	    if ((sh = JobMatchShell(shellName)) == NULL) {
2413 		    Parse_Error(PARSE_WARNING, "%s: No matching shell",
2414 				shellName);
2415 		    free(words);
2416 		    return(FAILURE);
2417 	    }
2418 	    commandShell = sh;
2419 	} else {
2420 	    commandShell = emalloc(sizeof(Shell));
2421 	    *commandShell = newShell;
2422 	}
2423     }
2424 
2425     if (commandShell->echoOn && commandShell->echoOff) {
2426 	commandShell->hasEchoCtl = TRUE;
2427     }
2428 
2429     if (!commandShell->hasErrCtl) {
2430 	if (commandShell->errCheck == NULL) {
2431 	    commandShell->errCheck = "";
2432 	}
2433 	if (commandShell->ignErr == NULL) {
2434 	    commandShell->ignErr = "%s\n";
2435 	}
2436     }
2437 
2438     /*
2439      * Do not free up the words themselves, since they might be in use by the
2440      * shell specification.
2441      */
2442     free(words);
2443     return SUCCESS;
2444 }
2445 
2446 /*-
2447  *-----------------------------------------------------------------------
2448  * JobInterrupt --
2449  *	Handle the receipt of an interrupt.
2450  *
2451  * Input:
2452  *	runINTERRUPT	Non-zero if commands for the .INTERRUPT target
2453  *			should be executed
2454  *	signo		signal received
2455  *
2456  * Results:
2457  *	None
2458  *
2459  * Side Effects:
2460  *	All children are killed. Another job will be started if the
2461  *	.INTERRUPT target was given.
2462  *-----------------------------------------------------------------------
2463  */
2464 static void
2465 JobInterrupt(int runINTERRUPT, int signo)
2466 {
2467     Job		*job;		/* job descriptor in that element */
2468     GNode	*interrupt;	/* the node describing the .INTERRUPT target */
2469     sigset_t	mask;
2470     GNode	*gn;
2471 
2472     aborting = ABORT_INTERRUPT;
2473 
2474     JobSigLock(&mask);
2475 
2476     for (job = job_table; job < job_table_end; job++) {
2477 	if (job->job_state != JOB_ST_RUNNING)
2478 	    continue;
2479 
2480 	gn = job->node;
2481 
2482 	if ((gn->type & (OP_JOIN|OP_PHONY)) == 0 && !Targ_Precious(gn)) {
2483 	    char *file = (gn->path == NULL ? gn->name : gn->path);
2484 	    if (!noExecute && eunlink(file) != -1) {
2485 		Error("*** %s removed", file);
2486 	    }
2487 	}
2488 	if (job->pid) {
2489 	    if (DEBUG(JOB)) {
2490 		(void)fprintf(debug_file,
2491 			   "JobInterrupt passing signal %d to child %d.\n",
2492 			   signo, job->pid);
2493 	    }
2494 	    KILLPG(job->pid, signo);
2495 	}
2496     }
2497 
2498     JobSigUnlock(&mask);
2499 
2500     if (runINTERRUPT && !touchFlag) {
2501 	interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2502 	if (interrupt != NILGNODE) {
2503 	    ignoreErrors = FALSE;
2504 	    JobRun(interrupt);
2505 	}
2506     }
2507     Trace_Log(MAKEINTR, 0);
2508     exit(signo);
2509 }
2510 
2511 /*
2512  *-----------------------------------------------------------------------
2513  * Job_Finish --
2514  *	Do final processing such as the running of the commands
2515  *	attached to the .END target.
2516  *
2517  * Results:
2518  *	Number of errors reported.
2519  *
2520  * Side Effects:
2521  *	None.
2522  *-----------------------------------------------------------------------
2523  */
2524 int
2525 Job_Finish(void)
2526 {
2527     if (postCommands != NILGNODE && !Lst_IsEmpty(postCommands->commands)) {
2528 	if (errors) {
2529 	    Error("Errors reported so .END ignored");
2530 	} else {
2531 	    JobRun(postCommands);
2532 	}
2533     }
2534     return(errors);
2535 }
2536 
2537 /*-
2538  *-----------------------------------------------------------------------
2539  * Job_End --
2540  *	Cleanup any memory used by the jobs module
2541  *
2542  * Results:
2543  *	None.
2544  *
2545  * Side Effects:
2546  *	Memory is freed
2547  *-----------------------------------------------------------------------
2548  */
2549 void
2550 Job_End(void)
2551 {
2552 #ifdef CLEANUP
2553     if (shellArgv)
2554 	free(shellArgv);
2555 #endif
2556 }
2557 
2558 /*-
2559  *-----------------------------------------------------------------------
2560  * Job_Wait --
2561  *	Waits for all running jobs to finish and returns. Sets 'aborting'
2562  *	to ABORT_WAIT to prevent other jobs from starting.
2563  *
2564  * Results:
2565  *	None.
2566  *
2567  * Side Effects:
2568  *	Currently running jobs finish.
2569  *
2570  *-----------------------------------------------------------------------
2571  */
2572 void
2573 Job_Wait(void)
2574 {
2575     aborting = ABORT_WAIT;
2576     while (jobTokensRunning != 0) {
2577 	Job_CatchOutput();
2578     }
2579     aborting = 0;
2580 }
2581 
2582 /*-
2583  *-----------------------------------------------------------------------
2584  * Job_AbortAll --
2585  *	Abort all currently running jobs without handling output or anything.
2586  *	This function is to be called only in the event of a major
2587  *	error. Most definitely NOT to be called from JobInterrupt.
2588  *
2589  * Results:
2590  *	None
2591  *
2592  * Side Effects:
2593  *	All children are killed, not just the firstborn
2594  *-----------------------------------------------------------------------
2595  */
2596 void
2597 Job_AbortAll(void)
2598 {
2599     Job		*job;	/* the job descriptor in that element */
2600     int		foo;
2601 
2602     aborting = ABORT_ERROR;
2603 
2604     if (jobTokensRunning) {
2605 	for (job = job_table; job < job_table_end; job++) {
2606 	    if (job->job_state != JOB_ST_RUNNING)
2607 		continue;
2608 	    /*
2609 	     * kill the child process with increasingly drastic signals to make
2610 	     * darn sure it's dead.
2611 	     */
2612 	    KILLPG(job->pid, SIGINT);
2613 	    KILLPG(job->pid, SIGKILL);
2614 	}
2615     }
2616 
2617     /*
2618      * Catch as many children as want to report in at first, then give up
2619      */
2620     while (waitpid((pid_t) -1, &foo, WNOHANG) > 0)
2621 	continue;
2622 }
2623 
2624 
2625 /*-
2626  *-----------------------------------------------------------------------
2627  * JobRestartJobs --
2628  *	Tries to restart stopped jobs if there are slots available.
2629  *	Called in process context in response to a SIGCONT.
2630  *
2631  * Results:
2632  *	None.
2633  *
2634  * Side Effects:
2635  *	Resumes jobs.
2636  *
2637  *-----------------------------------------------------------------------
2638  */
2639 static void
2640 JobRestartJobs(void)
2641 {
2642     Job *job;
2643 
2644     for (job = job_table; job < job_table_end; job++) {
2645 	if (job->job_state == JOB_ST_RUNNING &&
2646 		(make_suspended || job->job_suspended)) {
2647 	    if (DEBUG(JOB)) {
2648 		(void)fprintf(debug_file, "Restarting stopped job pid %d.\n",
2649 			job->pid);
2650 	    }
2651 	    if (job->job_suspended) {
2652 		    (void)printf("*** [%s] Continued\n", job->node->name);
2653 		    (void)fflush(stdout);
2654 	    }
2655 	    job->job_suspended = 0;
2656 	    if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
2657 		fprintf(debug_file, "Failed to send SIGCONT to %d\n", job->pid);
2658 	    }
2659 	}
2660 	if (job->job_state == JOB_ST_FINISHED)
2661 	    /* Job exit deferred after calling waitpid() in a signal handler */
2662 	    JobFinish(job, job->exit_status);
2663     }
2664     make_suspended = 0;
2665 }
2666 
2667 static void
2668 watchfd(Job *job)
2669 {
2670     if (job->inPollfd != NULL)
2671 	Punt("Watching watched job");
2672 
2673     fds[nfds].fd = job->inPipe;
2674     fds[nfds].events = POLLIN;
2675     jobfds[nfds] = job;
2676     job->inPollfd = &fds[nfds];
2677     nfds++;
2678 }
2679 
2680 static void
2681 clearfd(Job *job)
2682 {
2683     int i;
2684     if (job->inPollfd == NULL)
2685 	Punt("Unwatching unwatched job");
2686     i = job->inPollfd - fds;
2687     nfds--;
2688     /*
2689      * Move last job in table into hole made by dead job.
2690      */
2691     if (nfds != i) {
2692 	fds[i] = fds[nfds];
2693 	jobfds[i] = jobfds[nfds];
2694 	jobfds[i]->inPollfd = &fds[i];
2695     }
2696     job->inPollfd = NULL;
2697 }
2698 
2699 static int
2700 readyfd(Job *job)
2701 {
2702     if (job->inPollfd == NULL)
2703 	Punt("Polling unwatched job");
2704     return (job->inPollfd->revents & POLLIN) != 0;
2705 }
2706 
2707 /*-
2708  *-----------------------------------------------------------------------
2709  * JobTokenAdd --
2710  *	Put a token into the job pipe so that some make process can start
2711  *	another job.
2712  *
2713  * Side Effects:
2714  *	Allows more build jobs to be spawned somewhere.
2715  *
2716  *-----------------------------------------------------------------------
2717  */
2718 
2719 static void
2720 JobTokenAdd(void)
2721 {
2722     char tok = JOB_TOKENS[aborting], tok1;
2723 
2724     /* If we are depositing an error token flush everything else */
2725     while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2726 	continue;
2727 
2728     if (DEBUG(JOB))
2729 	fprintf(debug_file, "(%d) aborting %d, deposit token %c\n",
2730 	    getpid(), aborting, JOB_TOKENS[aborting]);
2731     write(tokenWaitJob.outPipe, &tok, 1);
2732 }
2733 
2734 /*-
2735  *-----------------------------------------------------------------------
2736  * Job_ServerStartTokenAdd --
2737  *	Prep the job token pipe in the root make process.
2738  *
2739  *-----------------------------------------------------------------------
2740  */
2741 
2742 void
2743 Job_ServerStart(int max_tokens, int jp_0, int jp_1)
2744 {
2745     int i;
2746     char jobarg[64];
2747 
2748     if (jp_0 >= 0 && jp_1 >= 0) {
2749 	/* Pipe passed in from parent */
2750 	tokenWaitJob.inPipe = jp_0;
2751 	tokenWaitJob.outPipe = jp_1;
2752 	return;
2753     }
2754 
2755     JobCreatePipe(&tokenWaitJob, 15);
2756 
2757     snprintf(jobarg, sizeof(jobarg), "%d,%d",
2758 	    tokenWaitJob.inPipe, tokenWaitJob.outPipe);
2759 
2760     Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
2761     Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
2762 
2763     /*
2764      * Preload the job pipe with one token per job, save the one
2765      * "extra" token for the primary job.
2766      *
2767      * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
2768      * larger than the write buffer size of the pipe, we will
2769      * deadlock here.
2770      */
2771     for (i = 1; i < max_tokens; i++)
2772 	JobTokenAdd();
2773 }
2774 
2775 /*-
2776  *-----------------------------------------------------------------------
2777  * Job_TokenReturn --
2778  *	Return a withdrawn token to the pool.
2779  *
2780  *-----------------------------------------------------------------------
2781  */
2782 
2783 void
2784 Job_TokenReturn(void)
2785 {
2786     jobTokensRunning--;
2787     if (jobTokensRunning < 0)
2788 	Punt("token botch");
2789     if (jobTokensRunning || JOB_TOKENS[aborting] != '+')
2790 	JobTokenAdd();
2791 }
2792 
2793 /*-
2794  *-----------------------------------------------------------------------
2795  * Job_TokenWithdraw --
2796  *	Attempt to withdraw a token from the pool.
2797  *
2798  * Results:
2799  *	Returns TRUE if a token was withdrawn, and FALSE if the pool
2800  *	is currently empty.
2801  *
2802  * Side Effects:
2803  * 	If pool is empty, set wantToken so that we wake up
2804  *	when a token is released.
2805  *
2806  *-----------------------------------------------------------------------
2807  */
2808 
2809 
2810 Boolean
2811 Job_TokenWithdraw(void)
2812 {
2813     char tok, tok1;
2814     int count;
2815 
2816     wantToken = 0;
2817     if (DEBUG(JOB))
2818 	fprintf(debug_file, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
2819 		getpid(), aborting, jobTokensRunning);
2820 
2821     if (aborting || (jobTokensRunning >= maxJobs))
2822 	return FALSE;
2823 
2824     count = read(tokenWaitJob.inPipe, &tok, 1);
2825     if (count == 0)
2826 	Fatal("eof on job pipe!");
2827     if (count < 0 && jobTokensRunning != 0) {
2828 	if (errno != EAGAIN) {
2829 	    Fatal("job pipe read: %s", strerror(errno));
2830 	}
2831 	if (DEBUG(JOB))
2832 	    fprintf(debug_file, "(%d) blocked for token\n", getpid());
2833 	wantToken = 1;
2834 	return FALSE;
2835     }
2836 
2837     if (count == 1 && tok != '+') {
2838 	/* make being abvorted - remove any other job tokens */
2839 	if (DEBUG(JOB))
2840 	    fprintf(debug_file, "(%d) aborted by token %c\n", getpid(), tok);
2841 	while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2842 	    continue;
2843 	/* And put the stopper back */
2844 	write(tokenWaitJob.outPipe, &tok, 1);
2845 	Fatal("A failure has been detected in another branch of the parallel make");
2846     }
2847 
2848     if (count == 1 && jobTokensRunning == 0)
2849 	/* We didn't want the token really */
2850 	write(tokenWaitJob.outPipe, &tok, 1);
2851 
2852     jobTokensRunning++;
2853     if (DEBUG(JOB))
2854 	fprintf(debug_file, "(%d) withdrew token\n", getpid());
2855     return TRUE;
2856 }
2857 
2858 #ifdef USE_SELECT
2859 int
2860 emul_poll(struct pollfd *fd, int nfd, int timeout)
2861 {
2862     fd_set rfds, wfds;
2863     int i, maxfd, nselect, npoll;
2864     struct timeval tv, *tvp;
2865     long usecs;
2866 
2867     FD_ZERO(&rfds);
2868     FD_ZERO(&wfds);
2869 
2870     maxfd = -1;
2871     for (i = 0; i < nfd; i++) {
2872 	fd[i].revents = 0;
2873 
2874 	if (fd[i].events & POLLIN)
2875 	    FD_SET(fd[i].fd, &rfds);
2876 
2877 	if (fd[i].events & POLLOUT)
2878 	    FD_SET(fd[i].fd, &wfds);
2879 
2880 	if (fd[i].fd > maxfd)
2881 	    maxfd = fd[i].fd;
2882     }
2883 
2884     if (maxfd >= FD_SETSIZE) {
2885 	Punt("Ran out of fd_set slots; "
2886 	     "recompile with a larger FD_SETSIZE.");
2887     }
2888 
2889     if (timeout < 0) {
2890 	tvp = NULL;
2891     } else {
2892 	usecs = timeout * 1000;
2893 	tv.tv_sec = usecs / 1000000;
2894 	tv.tv_usec = usecs % 1000000;
2895         tvp = &tv;
2896     }
2897 
2898     nselect = select(maxfd + 1, &rfds, &wfds, 0, tvp);
2899 
2900     if (nselect <= 0)
2901 	return nselect;
2902 
2903     npoll = 0;
2904     for (i = 0; i < nfd; i++) {
2905 	if (FD_ISSET(fd[i].fd, &rfds))
2906 	    fd[i].revents |= POLLIN;
2907 
2908 	if (FD_ISSET(fd[i].fd, &wfds))
2909 	    fd[i].revents |= POLLOUT;
2910 
2911 	if (fd[i].revents)
2912 	    npoll++;
2913     }
2914 
2915     return npoll;
2916 }
2917 #endif /* USE_SELECT */
2918