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