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