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