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