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