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