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