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