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