]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - usr.bin/make/job.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / usr.bin / make / job.c
1 /*-
2  * Copyright (c) 1988, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1988, 1989 by Adam de Boor
5  * Copyright (c) 1989 by Berkeley Softworks
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Adam de Boor.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *      This product includes software developed by the University of
22  *      California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  *
39  * @(#)job.c    8.2 (Berkeley) 3/19/94
40  */
41
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44
45 /*-
46  * job.c --
47  *      handle the creation etc. of our child processes.
48  *
49  * Interface:
50  *      Job_Make        Start the creation of the given target.
51  *
52  *      Job_CatchChildren
53  *                      Check for and handle the termination of any children.
54  *                      This must be called reasonably frequently to keep the
55  *                      whole make going at a decent clip, since job table
56  *                      entries aren't removed until their process is caught
57  *                      this way. Its single argument is TRUE if the function
58  *                      should block waiting for a child to terminate.
59  *
60  *      Job_CatchOutput Print any output our children have produced. Should
61  *                      also be called fairly frequently to keep the user
62  *                      informed of what's going on. If no output is waiting,
63  *                      it will block for a time given by the SEL_* constants,
64  *                      below, or until output is ready.
65  *
66  *      Job_Init        Called to intialize this module. in addition, any
67  *                      commands attached to the .BEGIN target are executed
68  *                      before this function returns. Hence, the makefile must
69  *                      have been parsed before this function is called.
70  *
71  *      Job_Full        Return TRUE if the job table is filled.
72  *
73  *      Job_Empty       Return TRUE if the job table is completely empty.
74  *
75  *      Job_Finish      Perform any final processing which needs doing. This
76  *                      includes the execution of any commands which have
77  *                      been/were attached to the .END target. It should only
78  *                      be called when the job table is empty.
79  *
80  *      Job_AbortAll    Abort all currently running jobs. It doesn't handle
81  *                      output or do anything for the jobs, just kills them.
82  *                      It should only be called in an emergency, as it were.
83  *
84  *      Job_CheckCommands
85  *                      Verify that the commands for a target are ok. Provide
86  *                      them if necessary and possible.
87  *
88  *      Job_Touch       Update a target without really updating it.
89  *
90  *      Job_Wait        Wait for all currently-running jobs to finish.
91  *
92  * compat.c --
93  *      The routines in this file implement the full-compatibility
94  *      mode of PMake. Most of the special functionality of PMake
95  *      is available in this mode. Things not supported:
96  *          - different shells.
97  *          - friendly variable substitution.
98  *
99  * Interface:
100  *      Compat_Run          Initialize things for this module and recreate
101  *                          thems as need creatin'
102  */
103
104 #include <sys/queue.h>
105 #include <sys/types.h>
106 #include <sys/select.h>
107 #include <sys/stat.h>
108 #ifdef USE_KQUEUE
109 #include <sys/event.h>
110 #endif
111 #include <sys/wait.h>
112 #include <ctype.h>
113 #include <err.h>
114 #include <errno.h>
115 #include <fcntl.h>
116 #include <inttypes.h>
117 #include <string.h>
118 #include <signal.h>
119 #include <stdlib.h>
120 #include <unistd.h>
121 #include <utime.h>
122
123 #include "arch.h"
124 #include "buf.h"
125 #include "config.h"
126 #include "dir.h"
127 #include "globals.h"
128 #include "GNode.h"
129 #include "job.h"
130 #include "make.h"
131 #include "parse.h"
132 #include "proc.h"
133 #include "shell.h"
134 #include "str.h"
135 #include "suff.h"
136 #include "targ.h"
137 #include "util.h"
138 #include "var.h"
139
140 #define TMPPAT  "/tmp/makeXXXXXXXXXX"
141
142 #ifndef USE_KQUEUE
143 /*
144  * The SEL_ constants determine the maximum amount of time spent in select
145  * before coming out to see if a child has finished. SEL_SEC is the number of
146  * seconds and SEL_USEC is the number of micro-seconds
147  */
148 #define SEL_SEC         2
149 #define SEL_USEC        0
150 #endif /* !USE_KQUEUE */
151
152 /*
153  * Job Table definitions.
154  *
155  * The job "table" is kept as a linked Lst in 'jobs', with the number of
156  * active jobs maintained in the 'nJobs' variable. At no time will this
157  * exceed the value of 'maxJobs', initialized by the Job_Init function.
158  *
159  * When a job is finished, the Make_Update function is called on each of the
160  * parents of the node which was just remade. This takes care of the upward
161  * traversal of the dependency graph.
162  */
163 #define JOB_BUFSIZE     1024
164 typedef struct Job {
165         pid_t           pid;    /* The child's process ID */
166
167         struct GNode    *node;  /* The target the child is making */
168
169         /*
170          * A LstNode for the first command to be saved after the job completes.
171          * This is NULL if there was no "..." in the job's commands.
172          */
173         LstNode         *tailCmds;
174
175         /*
176          * An FILE* for writing out the commands. This is only
177          * used before the job is actually started.
178          */
179         FILE            *cmdFILE;
180
181         /*
182          * A word of flags which determine how the module handles errors,
183          * echoing, etc. for the job
184          */
185         short           flags;  /* Flags to control treatment of job */
186 #define JOB_IGNERR      0x001   /* Ignore non-zero exits */
187 #define JOB_SILENT      0x002   /* no output */
188 #define JOB_SPECIAL     0x004   /* Target is a special one. i.e. run it locally
189                                  * if we can't export it and maxLocal is 0 */
190 #define JOB_IGNDOTS     0x008   /* Ignore "..." lines when processing
191                                  * commands */
192 #define JOB_FIRST       0x020   /* Job is first job for the node */
193 #define JOB_RESTART     0x080   /* Job needs to be completely restarted */
194 #define JOB_RESUME      0x100   /* Job needs to be resumed b/c it stopped,
195                                  * for some reason */
196 #define JOB_CONTINUING  0x200   /* We are in the process of resuming this job.
197                                  * Used to avoid infinite recursion between
198                                  * JobFinish and JobRestart */
199
200         /* union for handling shell's output */
201         union {
202                 /*
203                  * This part is used when usePipes is true.
204                  * The output is being caught via a pipe and the descriptors
205                  * of our pipe, an array in which output is line buffered and
206                  * the current position in that buffer are all maintained for
207                  * each job.
208                  */
209                 struct {
210                         /*
211                          * Input side of pipe associated with
212                          * job's output channel
213                          */
214                         int     op_inPipe;
215
216                         /*
217                          * Output side of pipe associated with job's
218                          * output channel
219                          */
220                         int     op_outPipe;
221
222                         /*
223                          * Buffer for storing the output of the
224                          * job, line by line
225                          */
226                         char    op_outBuf[JOB_BUFSIZE + 1];
227
228                         /* Current position in op_outBuf */
229                         int     op_curPos;
230                 }       o_pipe;
231
232                 /*
233                  * If usePipes is false the output is routed to a temporary
234                  * file and all that is kept is the name of the file and the
235                  * descriptor open to the file.
236                  */
237                 struct {
238                         /* Name of file to which shell output was rerouted */
239                         char    of_outFile[sizeof(TMPPAT)];
240
241                         /*
242                          * Stream open to the output file. Used to funnel all
243                          * from a single job to one file while still allowing
244                          * multiple shell invocations
245                          */
246                         int     of_outFd;
247                 }       o_file;
248
249         }       output;     /* Data for tracking a shell's output */
250
251         TAILQ_ENTRY(Job) link;  /* list link */
252 } Job;
253
254 #define outPipe         output.o_pipe.op_outPipe
255 #define inPipe          output.o_pipe.op_inPipe
256 #define outBuf          output.o_pipe.op_outBuf
257 #define curPos          output.o_pipe.op_curPos
258 #define outFile         output.o_file.of_outFile
259 #define outFd           output.o_file.of_outFd
260
261 TAILQ_HEAD(JobList, Job);
262
263 /*
264  * error handling variables
265  */
266 static int      aborting = 0;   /* why is the make aborting? */
267 #define ABORT_ERROR     1       /* Because of an error */
268 #define ABORT_INTERRUPT 2       /* Because it was interrupted */
269 #define ABORT_WAIT      3       /* Waiting for jobs to finish */
270
271 /*
272  * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
273  * is a char! So when we go above 127 we turn negative!
274  */
275 #define FILENO(a) ((unsigned)fileno(a))
276
277 /*
278  * post-make command processing. The node postCommands is really just the
279  * .END target but we keep it around to avoid having to search for it
280  * all the time.
281  */
282 static GNode    *postCommands;
283
284 /*
285  * The number of commands actually printed for a target. Should this
286  * number be 0, no shell will be executed.
287  */
288 static int      numCommands;
289
290 /*
291  * Return values from JobStart.
292  */
293 #define JOB_RUNNING     0       /* Job is running */
294 #define JOB_ERROR       1       /* Error in starting the job */
295 #define JOB_FINISHED    2       /* The job is already finished */
296 #define JOB_STOPPED     3       /* The job is stopped */
297
298 /*
299  * The maximum number of jobs that may run. This is initialize from the
300  * -j argument for the leading make and from the FIFO for sub-makes.
301  */
302 static int      maxJobs;
303
304 static int      nJobs;          /* The number of children currently running */
305
306 /* The structures that describe them */
307 static struct JobList jobs = TAILQ_HEAD_INITIALIZER(jobs);
308
309 static Boolean  jobFull;        /* Flag to tell when the job table is full. It
310                                  * is set TRUE when (1) the total number of
311                                  * running jobs equals the maximum allowed */
312 #ifdef USE_KQUEUE
313 static int      kqfd;           /* File descriptor obtained by kqueue() */
314 #else
315 static fd_set   outputs;        /* Set of descriptors of pipes connected to
316                                  * the output channels of children */
317 #endif
318
319 static GNode    *lastNode;      /* The node for which output was most recently
320                                  * produced. */
321 static const char *targFmt;     /* Format string to use to head output from a
322                                  * job when it's not the most-recent job heard
323                                  * from */
324 static char *targPrefix = NULL; /* What we print at the start of targFmt */
325
326 #define TARG_FMT  "%s %s ---\n" /* Default format */
327 #define MESSAGE(fp, gn) \
328         fprintf(fp, targFmt, targPrefix, gn->name);
329
330 /*
331  * When JobStart attempts to run a job but isn't allowed to
332  * or when Job_CatchChildren detects a job that has
333  * been stopped somehow, the job is placed on the stoppedJobs queue to be run
334  * when the next job finishes.
335  *
336  * Lst of Job structures describing jobs that were stopped due to
337  * concurrency limits or externally
338  */
339 static struct JobList stoppedJobs = TAILQ_HEAD_INITIALIZER(stoppedJobs);
340
341 static int      fifoFd;         /* Fd of our job fifo */
342 static char     fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
343 static int      fifoMaster;
344
345 static sig_atomic_t interrupted;
346
347
348 #if defined(USE_PGRP) && defined(SYSV)
349 # define KILL(pid, sig)         killpg(-(pid), (sig))
350 #else
351 # if defined(USE_PGRP)
352 #  define KILL(pid, sig)        killpg((pid), (sig))
353 # else
354 #  define KILL(pid, sig)        kill((pid), (sig))
355 # endif
356 #endif
357
358 /*
359  * Grmpf... There is no way to set bits of the wait structure
360  * anymore with the stupid W*() macros. I liked the union wait
361  * stuff much more. So, we devise our own macros... This is
362  * really ugly, use dramamine sparingly. You have been warned.
363  */
364 #define W_SETMASKED(st, val, fun)                               \
365         {                                                       \
366                 int sh = (int)~0;                               \
367                 int mask = fun(sh);                             \
368                                                                 \
369                 for (sh = 0; ((mask >> sh) & 1) == 0; sh++)     \
370                         continue;                               \
371                 *(st) = (*(st) & ~mask) | ((val) << sh);        \
372         }
373
374 #define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
375 #define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
376
377 static void JobRestart(Job *);
378 static int JobStart(GNode *, int, Job *);
379 static void JobDoOutput(Job *, Boolean);
380 static void JobInterrupt(int, int);
381 static void JobRestartJobs(void);
382 static int Compat_RunCommand(char *, struct GNode *);
383
384 static GNode        *curTarg = NULL;
385 static GNode        *ENDNode;
386
387 /**
388  * Create a fifo file with a uniq filename, and returns a file
389  * descriptor to that fifo.
390  */
391 static int
392 mkfifotemp(char *template)
393 {
394         char *start;
395         char *pathend;
396         char *ptr;
397         const unsigned char padchar[] =
398             "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
399
400         if (template[0] == '\0') {
401                 errno = EINVAL; /* bad input string */
402                 return (-1);
403         }
404
405         /* Find end of template string. */
406         pathend = strchr(template, '\0');
407         ptr = pathend - 1;
408
409         /*
410          * Starting from the end of the template replace spaces with 'X' in
411          * them with random characters until there are no more 'X'.
412          */
413         while (ptr >= template && *ptr == 'X') {
414                 uint32_t rand_num = arc4random() % (sizeof(padchar) - 1);
415                 *ptr-- = padchar[rand_num];
416         }
417         start = ptr + 1;
418
419         /* Check the target directory. */
420         for (; ptr > template; --ptr) {
421                 if (*ptr == '/') {
422                         struct stat sbuf;
423
424                         *ptr = '\0';
425                         if (stat(template, &sbuf) != 0)
426                                 return (-1);
427
428                         if (!S_ISDIR(sbuf.st_mode)) {
429                                 errno = ENOTDIR;
430                                 return (-1);
431                         }
432                         *ptr = '/';
433                         break;
434                 }
435         }
436
437         for (;;) {
438                 if (mkfifo(template, 0600) == 0) {
439                         int fd;
440
441                         if ((fd = open(template, O_RDWR, 0600)) < 0) {
442                                 unlink(template);
443                                 return (-1);
444                         } else {
445                                 return (fd);
446                         }
447                 } else {
448                         if (errno != EEXIST) {
449                                 return (-1);
450                         }
451                 }
452
453                 /*
454                  * If we have a collision, cycle through the space of
455                  * filenames.
456                  */
457                 for (ptr = start;;) {
458                         char *pad;
459
460                         if (*ptr == '\0' || ptr == pathend)
461                                 return (-1);
462
463                         pad = strchr(padchar, *ptr);
464                         if (pad == NULL || *++pad == '\0') {
465                                 *ptr++ = padchar[0];
466                         } else {
467                                 *ptr++ = *pad;
468                                 break;
469                         }
470                 }
471         }
472         /*NOTREACHED*/
473 }
474
475 static void
476 catch_child(int sig __unused)
477 {
478 }
479
480 /**
481  */
482 void
483 Proc_Init()
484 {
485         /*
486          * Catch SIGCHLD so that we get kicked out of select() when we
487          * need to look at a child.  This is only known to matter for the
488          * -j case (perhaps without -P).
489          *
490          * XXX this is intentionally misplaced.
491          */
492         struct sigaction sa;
493
494         sigemptyset(&sa.sa_mask);
495         sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
496         sa.sa_handler = catch_child;
497         sigaction(SIGCHLD, &sa, NULL);
498 }
499
500 /**
501  * Wait for child process to terminate.
502  */
503 static int
504 ProcWait(ProcStuff *ps)
505 {
506         pid_t   pid;
507         int     status;
508
509         /*
510          * Wait for the process to exit.
511          */
512         for (;;) {
513                 pid = wait(&status);
514                 if (pid == -1 && errno != EINTR) {
515                         Fatal("error in wait: %d", pid);
516                         /* NOTREACHED */
517                 }
518                 if (pid == ps->child_pid) {
519                         break;
520                 }
521                 if (interrupted) {
522                         break;
523                 }
524         }
525
526         return (status);
527 }
528
529 /**
530  * JobCatchSignal
531  *      Got a signal. Set global variables and hope that someone will
532  *      handle it.
533  */
534 static void
535 JobCatchSig(int signo)
536 {
537
538         interrupted = signo;
539 }
540
541 /**
542  * JobPassSig --
543  *      Pass a signal on to all local jobs if
544  *      USE_PGRP is defined, then die ourselves.
545  *
546  * Side Effects:
547  *      We die by the same signal.
548  */
549 static void
550 JobPassSig(int signo)
551 {
552         Job     *job;
553         sigset_t nmask, omask;
554         struct sigaction act;
555
556         sigemptyset(&nmask);
557         sigaddset(&nmask, signo);
558         sigprocmask(SIG_SETMASK, &nmask, &omask);
559
560         DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
561         TAILQ_FOREACH(job, &jobs, link) {
562                 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
563                     signo, (intmax_t)job->pid));
564                 KILL(job->pid, signo);
565         }
566
567         /*
568          * Deal with proper cleanup based on the signal received. We only run
569          * the .INTERRUPT target if the signal was in fact an interrupt.
570          * The other three termination signals are more of a "get out *now*"
571          * command.
572          */
573         if (signo == SIGINT) {
574                 JobInterrupt(TRUE, signo);
575         } else if (signo == SIGHUP || signo == SIGTERM || signo == SIGQUIT) {
576                 JobInterrupt(FALSE, signo);
577         }
578
579         /*
580          * Leave gracefully if SIGQUIT, rather than core dumping.
581          */
582         if (signo == SIGQUIT) {
583                 signo = SIGINT;
584         }
585
586         /*
587          * Send ourselves the signal now we've given the message to everyone
588          * else. Note we block everything else possible while we're getting
589          * the signal. This ensures that all our jobs get continued when we
590          * wake up before we take any other signal.
591          * XXX this comment seems wrong.
592          */
593         act.sa_handler = SIG_DFL;
594         sigemptyset(&act.sa_mask);
595         act.sa_flags = 0;
596         sigaction(signo, &act, NULL);
597
598         DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
599             ~0 & ~(1 << (signo - 1))));
600         signal(signo, SIG_DFL);
601
602         KILL(getpid(), signo);
603
604         signo = SIGCONT;
605         TAILQ_FOREACH(job, &jobs, link) {
606                 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
607                     signo, (intmax_t)job->pid));
608                 KILL(job->pid, signo);
609         }
610
611         sigprocmask(SIG_SETMASK, &omask, NULL);
612         sigprocmask(SIG_SETMASK, &omask, NULL);
613         act.sa_handler = JobPassSig;
614         sigaction(signo, &act, NULL);
615 }
616
617 /**
618  * JobPrintCommand  --
619  *      Put out another command for the given job. If the command starts
620  *      with an @ or a - we process it specially. In the former case,
621  *      so long as the -s and -n flags weren't given to make, we stick
622  *      a shell-specific echoOff command in the script. In the latter,
623  *      we ignore errors for the entire job, unless the shell has error
624  *      control.
625  *      If the command is just "..." we take all future commands for this
626  *      job to be commands to be executed once the entire graph has been
627  *      made and return non-zero to signal that the end of the commands
628  *      was reached. These commands are later attached to the postCommands
629  *      node and executed by Job_Finish when all things are done.
630  *      This function is called from JobStart via LST_FOREACH.
631  *
632  * Results:
633  *      Always 0, unless the command was "..."
634  *
635  * Side Effects:
636  *      If the command begins with a '-' and the shell has no error control,
637  *      the JOB_IGNERR flag is set in the job descriptor.
638  *      If the command is "..." and we're not ignoring such things,
639  *      tailCmds is set to the successor node of the cmd.
640  *      numCommands is incremented if the command is actually printed.
641  */
642 static int
643 JobPrintCommand(char *cmd, Job *job)
644 {
645         Boolean noSpecials;     /* true if we shouldn't worry about
646                                  * inserting special commands into
647                                  * the input stream. */
648         Boolean shutUp = FALSE; /* true if we put a no echo command
649                                  * into the command file */
650         Boolean errOff = FALSE; /* true if we turned error checking
651                                  * off before printing the command
652                                  * and need to turn it back on */
653         const char *cmdTemplate;/* Template to use when printing the command */
654         char    *cmdStart;      /* Start of expanded command */
655         LstNode *cmdNode;       /* Node for replacing the command */
656
657         noSpecials = (noExecute && !(job->node->type & OP_MAKE));
658
659         if (strcmp(cmd, "...") == 0) {
660                 job->node->type |= OP_SAVE_CMDS;
661                 if ((job->flags & JOB_IGNDOTS) == 0) {
662                         job->tailCmds =
663                             Lst_Succ(Lst_Member(&job->node->commands, cmd));
664                         return (1);
665                 }
666                 return (0);
667         }
668
669 #define DBPRINTF(fmt, arg)                      \
670         DEBUGF(JOB, (fmt, arg));                \
671         fprintf(job->cmdFILE, fmt, arg);        \
672         fflush(job->cmdFILE);
673
674         numCommands += 1;
675
676         /*
677          * For debugging, we replace each command with the result of expanding
678          * the variables in the command.
679          */
680         cmdNode = Lst_Member(&job->node->commands, cmd);
681
682         cmd = Buf_Peel(Var_Subst(cmd, job->node, FALSE));
683         cmdStart = cmd;
684
685         Lst_Replace(cmdNode, cmdStart);
686
687         cmdTemplate = "%s\n";
688
689         /*
690          * Check for leading @', -' or +'s to control echoing, error checking,
691          * and execution on -n.
692          */
693         while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
694                 switch (*cmd) {
695
696                   case '@':
697                         shutUp = DEBUG(LOUD) ? FALSE : TRUE;
698                         break;
699
700                   case '-':
701                         errOff = TRUE;
702                         break;
703
704                   case '+':
705                         if (noSpecials) {
706                                 /*
707                                  * We're not actually exececuting anything...
708                                  * but this one needs to be - use compat mode
709                                  * just for it.
710                                  */
711                                 Compat_RunCommand(cmd, job->node);
712                                 return (0);
713                         }
714                         break;
715                 }
716                 cmd++;
717         }
718
719         while (isspace((unsigned char)*cmd))
720                 cmd++;
721
722         if (shutUp) {
723                 if (!(job->flags & JOB_SILENT) && !noSpecials &&
724                     commandShell->hasEchoCtl) {
725                         DBPRINTF("%s\n", commandShell->echoOff);
726                 } else {
727                         shutUp = FALSE;
728                 }
729         }
730
731         if (errOff) {
732                 if (!(job->flags & JOB_IGNERR) && !noSpecials) {
733                         if (commandShell->hasErrCtl) {
734                                 /*
735                                  * We don't want the error-control commands
736                                  * showing up either, so we turn off echoing
737                                  * while executing them. We could put another
738                                  * field in the shell structure to tell
739                                  * JobDoOutput to look for this string too,
740                                  * but why make it any more complex than
741                                  * it already is?
742                                  */
743                                 if (!(job->flags & JOB_SILENT) && !shutUp &&
744                                     commandShell->hasEchoCtl) {
745                                         DBPRINTF("%s\n", commandShell->echoOff);
746                                         DBPRINTF("%s\n", commandShell->ignErr);
747                                         DBPRINTF("%s\n", commandShell->echoOn);
748                                 } else {
749                                         DBPRINTF("%s\n", commandShell->ignErr);
750                                 }
751                         } else if (commandShell->ignErr &&
752                             *commandShell->ignErr != '\0') {
753                                 /*
754                                  * The shell has no error control, so we need to
755                                  * be weird to get it to ignore any errors from
756                                  * the command. If echoing is turned on, we turn
757                                  * it off and use the errCheck template to echo
758                                  * the command. Leave echoing off so the user
759                                  * doesn't see the weirdness we go through to
760                                  * ignore errors. Set cmdTemplate to use the
761                                  * weirdness instead of the simple "%s\n"
762                                  * template.
763                                  */
764                                 if (!(job->flags & JOB_SILENT) && !shutUp &&
765                                     commandShell->hasEchoCtl) {
766                                         DBPRINTF("%s\n", commandShell->echoOff);
767                                         DBPRINTF(commandShell->errCheck, cmd);
768                                         shutUp = TRUE;
769                                 }
770                                 cmdTemplate = commandShell->ignErr;
771                                 /*
772                                  * The error ignoration (hee hee) is already
773                                  * taken care of by the ignErr template, so
774                                  * pretend error checking is still on.
775                                 */
776                                 errOff = FALSE;
777                         } else {
778                                 errOff = FALSE;
779                         }
780                 } else {
781                         errOff = FALSE;
782                 }
783         }
784
785         DBPRINTF(cmdTemplate, cmd);
786
787         if (errOff) {
788                 /*
789                  * If echoing is already off, there's no point in issuing the
790                  * echoOff command. Otherwise we issue it and pretend it was on
791                  * for the whole command...
792                  */
793                 if (!shutUp && !(job->flags & JOB_SILENT) &&
794                     commandShell->hasEchoCtl) {
795                         DBPRINTF("%s\n", commandShell->echoOff);
796                         shutUp = TRUE;
797                 }
798                 DBPRINTF("%s\n", commandShell->errCheck);
799         }
800         if (shutUp) {
801                 DBPRINTF("%s\n", commandShell->echoOn);
802         }
803         return (0);
804 }
805
806 /**
807  * JobClose --
808  *      Called to close both input and output pipes when a job is finished.
809  *
810  * Side Effects:
811  *      The file descriptors associated with the job are closed.
812  */
813 static void
814 JobClose(Job *job)
815 {
816
817         if (usePipes) {
818 #if !defined(USE_KQUEUE)
819                 FD_CLR(job->inPipe, &outputs);
820 #endif
821                 if (job->outPipe != job->inPipe) {
822                         close(job->outPipe);
823                 }
824                 JobDoOutput(job, TRUE);
825                 close(job->inPipe);
826         } else {
827                 close(job->outFd);
828                 JobDoOutput(job, TRUE);
829         }
830 }
831
832 /**
833  * JobFinish  --
834  *      Do final processing for the given job including updating
835  *      parents and starting new jobs as available/necessary. Note
836  *      that we pay no attention to the JOB_IGNERR flag here.
837  *      This is because when we're called because of a noexecute flag
838  *      or something, jstat.w_status is 0 and when called from
839  *      Job_CatchChildren, the status is zeroed if it s/b ignored.
840  *
841  * Side Effects:
842  *      Some nodes may be put on the toBeMade queue.
843  *      Final commands for the job are placed on postCommands.
844  *
845  *      If we got an error and are aborting (aborting == ABORT_ERROR) and
846  *      the job list is now empty, we are done for the day.
847  *      If we recognized an error (makeErrors !=0), we set the aborting flag
848  *      to ABORT_ERROR so no more jobs will be started.
849  */
850 static void
851 JobFinish(Job *job, int *status)
852 {
853         Boolean done;
854         LstNode *ln;
855
856         if (WIFEXITED(*status)) {
857                 int     job_status = WEXITSTATUS(*status);
858
859                 JobClose(job);
860                 /*
861                  * Deal with ignored errors in -B mode. We need to
862                  * print a message telling of the ignored error as
863                  * well as setting status.w_status to 0 so the next
864                  * command gets run. To do this, we set done to be
865                  * TRUE if in -B mode and the job exited non-zero.
866                  */
867                 if (job_status == 0) {
868                         done = FALSE;
869                 } else {
870                         if (job->flags & JOB_IGNERR) {
871                                 done = TRUE;
872                         } else {
873                                 /*
874                                  * If it exited non-zero and either we're
875                                  * doing things our way or we're not ignoring
876                                  * errors, the job is finished. Similarly, if
877                                  * the shell died because of a signal the job
878                                  * is also finished. In these cases, finish
879                                  * out the job's output before printing the
880                                  * exit status...
881                                  */
882                                 done = TRUE;
883                                 if (job->cmdFILE != NULL &&
884                                     job->cmdFILE != stdout) {
885                                         fclose(job->cmdFILE);
886                                 }
887
888                         }
889                 }
890         } else if (WIFSIGNALED(*status)) {
891                 if (WTERMSIG(*status) == SIGCONT) {
892                         /*
893                          * No need to close things down or anything.
894                          */
895                         done = FALSE;
896                 } else {
897                         /*
898                          * If it exited non-zero and either we're
899                          * doing things our way or we're not ignoring
900                          * errors, the job is finished. Similarly, if
901                          * the shell died because of a signal the job
902                          * is also finished. In these cases, finish
903                          * out the job's output before printing the
904                          * exit status...
905                          */
906                         JobClose(job);
907                         if (job->cmdFILE != NULL &&
908                             job->cmdFILE != stdout) {
909                                 fclose(job->cmdFILE);
910                         }
911                         done = TRUE;
912                 }
913         } else {
914                 /*
915                  * No need to close things down or anything.
916                  */
917                 done = FALSE;
918         }
919
920         if (WIFEXITED(*status)) {
921                 if (done || DEBUG(JOB)) {
922                         FILE   *out;
923
924                         if (compatMake &&
925                             !usePipes &&
926                             (job->flags & JOB_IGNERR)) {
927                                 /*
928                                  * If output is going to a file and this job
929                                  * is ignoring errors, arrange to have the
930                                  * exit status sent to the output file as
931                                  * well.
932                                  */
933                                 out = fdopen(job->outFd, "w");
934                                 if (out == NULL)
935                                         Punt("Cannot fdopen");
936                         } else {
937                                 out = stdout;
938                         }
939
940                         DEBUGF(JOB, ("Process %jd exited.\n",
941                             (intmax_t)job->pid));
942
943                         if (WEXITSTATUS(*status) == 0) {
944                                 if (DEBUG(JOB)) {
945                                         if (usePipes && job->node != lastNode) {
946                                                 MESSAGE(out, job->node);
947                                                 lastNode = job->node;
948                                         }
949                                         fprintf(out,
950                                             "*** Completed successfully\n");
951                                 }
952                         } else {
953                                 if (usePipes && job->node != lastNode) {
954                                         MESSAGE(out, job->node);
955                                         lastNode = job->node;
956                                 }
957                                 fprintf(out, "*** Error code %d%s\n",
958                                         WEXITSTATUS(*status),
959                                         (job->flags & JOB_IGNERR) ?
960                                         "(ignored)" : "");
961
962                                 if (job->flags & JOB_IGNERR) {
963                                         *status = 0;
964                                 }
965                         }
966
967                         fflush(out);
968                 }
969         } else if (WIFSIGNALED(*status)) {
970                 if (done || DEBUG(JOB) || (WTERMSIG(*status) == SIGCONT)) {
971                         FILE   *out;
972
973                         if (compatMake &&
974                             !usePipes &&
975                             (job->flags & JOB_IGNERR)) {
976                                 /*
977                                  * If output is going to a file and this job
978                                  * is ignoring errors, arrange to have the
979                                  * exit status sent to the output file as
980                                  * well.
981                                  */
982                                 out = fdopen(job->outFd, "w");
983                                 if (out == NULL)
984                                         Punt("Cannot fdopen");
985                         } else {
986                                 out = stdout;
987                         }
988
989                         if (WTERMSIG(*status) == SIGCONT) {
990                                 /*
991                                  * If the beastie has continued, shift the
992                                  * Job from the stopped list to the running
993                                  * one (or re-stop it if concurrency is
994                                  * exceeded) and go and get another child.
995                                  */
996                                 if (job->flags & (JOB_RESUME | JOB_RESTART)) {
997                                         if (usePipes && job->node != lastNode) {
998                                                 MESSAGE(out, job->node);
999                                                 lastNode = job->node;
1000                                         }
1001                                         fprintf(out, "*** Continued\n");
1002                                 }
1003                                 if (!(job->flags & JOB_CONTINUING)) {
1004                                         DEBUGF(JOB, ("Warning: process %jd was not "
1005                                                      "continuing.\n", (intmax_t) job->pid));
1006 #ifdef notdef
1007                                         /*
1008                                          * We don't really want to restart a
1009                                          * job from scratch just because it
1010                                          * continued, especially not without
1011                                          * killing the continuing process!
1012                                          * That's why this is ifdef'ed out.
1013                                          * FD - 9/17/90
1014                                          */
1015                                         JobRestart(job);
1016 #endif
1017                                 }
1018                                 job->flags &= ~JOB_CONTINUING;
1019                                 TAILQ_INSERT_TAIL(&jobs, job, link);
1020                                 nJobs += 1;
1021                                 DEBUGF(JOB, ("Process %jd is continuing locally.\n",
1022                                              (intmax_t) job->pid));
1023                                 if (nJobs == maxJobs) {
1024                                         jobFull = TRUE;
1025                                         DEBUGF(JOB, ("Job queue is full.\n"));
1026                                 }
1027                                 fflush(out);
1028                                 return;
1029
1030                         } else {
1031                                 if (usePipes && job->node != lastNode) {
1032                                         MESSAGE(out, job->node);
1033                                         lastNode = job->node;
1034                                 }
1035                                 fprintf(out,
1036                                     "*** Signal %d\n", WTERMSIG(*status));
1037                                 fflush(out);
1038                         }
1039                 }
1040         } else {
1041                 /* STOPPED */
1042                 FILE   *out;
1043
1044                 if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
1045                         /*
1046                          * If output is going to a file and this job
1047                          * is ignoring errors, arrange to have the
1048                          * exit status sent to the output file as
1049                          * well.
1050                          */
1051                         out = fdopen(job->outFd, "w");
1052                         if (out == NULL)
1053                                 Punt("Cannot fdopen");
1054                 } else {
1055                         out = stdout;
1056                 }
1057
1058                 DEBUGF(JOB, ("Process %jd stopped.\n", (intmax_t) job->pid));
1059                 if (usePipes && job->node != lastNode) {
1060                         MESSAGE(out, job->node);
1061                         lastNode = job->node;
1062                 }
1063                 fprintf(out, "*** Stopped -- signal %d\n", WSTOPSIG(*status));
1064                 job->flags |= JOB_RESUME;
1065                 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1066                 fflush(out);
1067                 return;
1068         }
1069
1070         /*
1071          * Now handle the -B-mode stuff. If the beast still isn't finished,
1072          * try and restart the job on the next command. If JobStart says it's
1073          * ok, it's ok. If there's an error, this puppy is done.
1074          */
1075         if (compatMake && WIFEXITED(*status) &&
1076             Lst_Succ(job->node->compat_command) != NULL) {
1077                 switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
1078                   case JOB_RUNNING:
1079                         done = FALSE;
1080                         break;
1081                   case JOB_ERROR:
1082                         done = TRUE;
1083                         W_SETEXITSTATUS(status, 1);
1084                         break;
1085                   case JOB_FINISHED:
1086                         /*
1087                          * If we got back a JOB_FINISHED code, JobStart has
1088                          * already called Make_Update and freed the job
1089                          * descriptor. We set done to false here to avoid fake
1090                          * cycles and double frees. JobStart needs to do the
1091                          * update so we can proceed up the graph when given
1092                          * the -n flag..
1093                          */
1094                         done = FALSE;
1095                         break;
1096                   default:
1097                         break;
1098                 }
1099         } else {
1100                 done = TRUE;
1101         }
1102
1103         if (done && aborting != ABORT_ERROR &&
1104             aborting != ABORT_INTERRUPT && *status == 0) {
1105                 /*
1106                  * As long as we aren't aborting and the job didn't return a
1107                  * non-zero status that we shouldn't ignore, we call
1108                  * Make_Update to update the parents. In addition, any saved
1109                  * commands for the node are placed on the .END target.
1110                  */
1111                 for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
1112                         Lst_AtEnd(&postCommands->commands,
1113                             Buf_Peel(
1114                                 Var_Subst(Lst_Datum(ln), job->node, FALSE)));
1115                 }
1116
1117                 job->node->made = MADE;
1118                 Make_Update(job->node);
1119                 free(job);
1120
1121         } else if (*status != 0) {
1122                 makeErrors++;
1123                 free(job);
1124         }
1125
1126         JobRestartJobs();
1127
1128         /*
1129          * Set aborting if any error.
1130          */
1131         if (makeErrors && !keepgoing && aborting != ABORT_INTERRUPT) {
1132                 /*
1133                  * If we found any errors in this batch of children and the -k
1134                  * flag wasn't given, we set the aborting flag so no more jobs
1135                  * get started.
1136                  */
1137                 aborting = ABORT_ERROR;
1138         }
1139
1140         if (aborting == ABORT_ERROR && Job_Empty()) {
1141                 /*
1142                  * If we are aborting and the job table is now empty, we finish.
1143                  */
1144                 Finish(makeErrors);
1145         }
1146 }
1147
1148 /**
1149  * Job_Touch
1150  *      Touch the given target. Called by JobStart when the -t flag was
1151  *      given.  Prints messages unless told to be silent.
1152  *
1153  * Side Effects:
1154  *      The data modification of the file is changed. In addition, if the
1155  *      file did not exist, it is created.
1156  */
1157 void
1158 Job_Touch(GNode *gn, Boolean silent)
1159 {
1160         int     streamID;       /* ID of stream opened to do the touch */
1161         struct utimbuf times;   /* Times for utime() call */
1162
1163         if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
1164                 /*
1165                  * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
1166                  * targets and, as such, shouldn't really be created.
1167                  */
1168                 return;
1169         }
1170
1171         if (!silent) {
1172                 fprintf(stdout, "touch %s\n", gn->name);
1173                 fflush(stdout);
1174         }
1175
1176         if (noExecute) {
1177                 return;
1178         }
1179
1180         if (gn->type & OP_ARCHV) {
1181                 Arch_Touch(gn);
1182         } else if (gn->type & OP_LIB) {
1183                 Arch_TouchLib(gn);
1184         } else {
1185                 char    *file = gn->path ? gn->path : gn->name;
1186
1187                 times.actime = times.modtime = now;
1188                 if (utime(file, &times) < 0) {
1189                         streamID = open(file, O_RDWR | O_CREAT, 0666);
1190
1191                         if (streamID >= 0) {
1192                                 char    c;
1193
1194                                 /*
1195                                  * Read and write a byte to the file to change
1196                                  * the modification time, then close the file.
1197                                  */
1198                                 if (read(streamID, &c, 1) == 1) {
1199                                         lseek(streamID, (off_t)0, SEEK_SET);
1200                                         write(streamID, &c, 1);
1201                                 }
1202
1203                                 close(streamID);
1204                         } else {
1205                                 fprintf(stdout, "*** couldn't touch %s: %s",
1206                                     file, strerror(errno));
1207                                 fflush(stdout);
1208                         }
1209                 }
1210         }
1211 }
1212
1213 /**
1214  * Job_CheckCommands
1215  *      Make sure the given node has all the commands it needs.
1216  *
1217  * Results:
1218  *      TRUE if the commands list is/was ok.
1219  *
1220  * Side Effects:
1221  *      The node will have commands from the .DEFAULT rule added to it
1222  *      if it needs them.
1223  */
1224 Boolean
1225 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1226 {
1227
1228         if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
1229             (gn->type & OP_LIB) == 0) {
1230                 /*
1231                  * No commands. Look for .DEFAULT rule from which we might infer
1232                  * commands.
1233                  */
1234                 if (DEFAULT != NULL && !Lst_IsEmpty(&DEFAULT->commands)) {
1235                         /*
1236                          * Make only looks for a .DEFAULT if the node was
1237                          * never the target of an operator, so that's what we
1238                          * do too. If a .DEFAULT was given, we substitute its
1239                          * commands for gn's commands and set the IMPSRC
1240                          * variable to be the target's name The DEFAULT node
1241                          * acts like a transformation rule, in that gn also
1242                          * inherits any attributes or sources attached to
1243                          * .DEFAULT itself.
1244                          */
1245                         Make_HandleUse(DEFAULT, gn);
1246                         Var_Set(IMPSRC, Var_Value(TARGET, gn), gn);
1247
1248                 } else if (Dir_MTime(gn) == 0) {
1249                         /*
1250                          * The node wasn't the target of an operator we have
1251                          * no .DEFAULT rule to go on and the target doesn't
1252                          * already exist. There's nothing more we can do for
1253                          * this branch. If the -k flag wasn't given, we stop
1254                          * in our tracks, otherwise we just don't update
1255                          * this node's parents so they never get examined.
1256                          */
1257                         static const char msg[] =
1258                             "make: don't know how to make";
1259
1260                         if (gn->type & OP_OPTIONAL) {
1261                                 fprintf(stdout, "%s %s(ignored)\n",
1262                                     msg, gn->name);
1263                                 fflush(stdout);
1264                         } else if (keepgoing) {
1265                                 fprintf(stdout, "%s %s(continuing)\n",
1266                                     msg, gn->name);
1267                                 fflush(stdout);
1268                                 return (FALSE);
1269                         } else {
1270 #ifndef WITHOUT_OLD_JOKE
1271                                 if (strcmp(gn->name,"love") == 0)
1272                                         (*abortProc)("Not war.");
1273                                 else
1274 #endif
1275                                         (*abortProc)("%s %s. Stop",
1276                                             msg, gn->name);
1277                                 return (FALSE);
1278                         }
1279                 }
1280         }
1281         return (TRUE);
1282 }
1283
1284 /**
1285  * JobExec
1286  *      Execute the shell for the given job. Called from JobStart and
1287  *      JobRestart.
1288  *
1289  * Side Effects:
1290  *      A shell is executed, outputs is altered and the Job structure added
1291  *      to the job table.
1292  */
1293 static void
1294 JobExec(Job *job, char **argv)
1295 {
1296         ProcStuff       ps;
1297
1298         if (DEBUG(JOB)) {
1299                 int       i;
1300
1301                 DEBUGF(JOB, ("Running %s\n", job->node->name));
1302                 DEBUGF(JOB, ("\tCommand: "));
1303                 for (i = 0; argv[i] != NULL; i++) {
1304                         DEBUGF(JOB, ("%s ", argv[i]));
1305                 }
1306                 DEBUGF(JOB, ("\n"));
1307         }
1308
1309         /*
1310          * Some jobs produce no output and it's disconcerting to have
1311          * no feedback of their running (since they produce no output, the
1312          * banner with their name in it never appears). This is an attempt to
1313          * provide that feedback, even if nothing follows it.
1314          */
1315         if (lastNode != job->node && (job->flags & JOB_FIRST) &&
1316             !(job->flags & JOB_SILENT)) {
1317                 MESSAGE(stdout, job->node);
1318                 lastNode = job->node;
1319         }
1320
1321         ps.in = FILENO(job->cmdFILE);
1322         if (usePipes) {
1323                 /*
1324                  * Set up the child's output to be routed through the
1325                  * pipe we've created for it.
1326                  */
1327                 ps.out = job->outPipe;
1328         } else {
1329                 /*
1330                  * We're capturing output in a file, so we duplicate
1331                  * the descriptor to the temporary file into the
1332                  * standard output.
1333                  */
1334                 ps.out = job->outFd;
1335         }
1336         ps.err = STDERR_FILENO;
1337
1338         ps.merge_errors = 1;
1339         ps.pgroup = 1;
1340         ps.searchpath = 0;
1341
1342         ps.argv = argv;
1343         ps.argv_free = 0;
1344
1345         /*
1346          * Fork.  Warning since we are doing vfork() instead of fork(),
1347          * do not allocate memory in the child process!
1348          */
1349         if ((ps.child_pid = vfork()) == -1) {
1350                 Punt("Cannot fork");
1351
1352
1353         } else if (ps.child_pid == 0) {
1354                 /*
1355                  * Child
1356                  */
1357                 if (fifoFd >= 0)
1358                         close(fifoFd);
1359
1360                 Proc_Exec(&ps);
1361                 /* NOTREACHED */
1362         }
1363
1364         /*
1365          * Parent
1366          */
1367         job->pid = ps.child_pid;
1368
1369         if (usePipes && (job->flags & JOB_FIRST)) {
1370                 /*
1371                  * The first time a job is run for a node, we set the
1372                  * current position in the buffer to the beginning and
1373                  * mark another stream to watch in the outputs mask.
1374                  */
1375 #ifdef USE_KQUEUE
1376                 struct kevent   kev[2];
1377 #endif
1378                 job->curPos = 0;
1379
1380 #if defined(USE_KQUEUE)
1381                 EV_SET(&kev[0], job->inPipe, EVFILT_READ, EV_ADD, 0, 0, job);
1382                 EV_SET(&kev[1], job->pid, EVFILT_PROC,
1383                     EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
1384                 if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1385                         /*
1386                          * kevent() will fail if the job is already
1387                          * finished
1388                          */
1389                         if (errno != EINTR && errno != EBADF && errno != ESRCH)
1390                                 Punt("kevent: %s", strerror(errno));
1391                 }
1392 #else
1393                 FD_SET(job->inPipe, &outputs);
1394 #endif /* USE_KQUEUE */
1395         }
1396
1397         if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1398                 fclose(job->cmdFILE);
1399                 job->cmdFILE = NULL;
1400         }
1401
1402         /*
1403          * Now the job is actually running, add it to the table.
1404          */
1405         nJobs += 1;
1406         TAILQ_INSERT_TAIL(&jobs, job, link);
1407         if (nJobs == maxJobs) {
1408                 jobFull = TRUE;
1409         }
1410 }
1411
1412 /**
1413  * JobMakeArgv
1414  *      Create the argv needed to execute the shell for a given job.
1415  */
1416 static void
1417 JobMakeArgv(Job *job, char **argv)
1418 {
1419         int             argc;
1420         static char     args[10];       /* For merged arguments */
1421
1422         argv[0] = commandShell->name;
1423         argc = 1;
1424
1425         if ((commandShell->exit && *commandShell->exit != '-') ||
1426             (commandShell->echo && *commandShell->echo != '-')) {
1427                 /*
1428                  * At least one of the flags doesn't have a minus before it, so
1429                  * merge them together. Have to do this because the *(&(@*#*&#$#
1430                  * Bourne shell thinks its second argument is a file to source.
1431                  * Grrrr. Note the ten-character limitation on the combined
1432                  * arguments.
1433                  */
1434                 sprintf(args, "-%s%s", (job->flags & JOB_IGNERR) ? "" :
1435                     commandShell->exit ? commandShell->exit : "",
1436                     (job->flags & JOB_SILENT) ? "" :
1437                     commandShell->echo ? commandShell->echo : "");
1438
1439                 if (args[1]) {
1440                         argv[argc] = args;
1441                         argc++;
1442                 }
1443         } else {
1444                 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1445                         argv[argc] = commandShell->exit;
1446                         argc++;
1447                 }
1448                 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1449                         argv[argc] = commandShell->echo;
1450                         argc++;
1451                 }
1452         }
1453         argv[argc] = NULL;
1454 }
1455
1456 /**
1457  * JobRestart
1458  *      Restart a job that stopped for some reason. The job must be neither
1459  *      on the jobs nor on the stoppedJobs list.
1460  *
1461  * Side Effects:
1462  *      jobFull will be set if the job couldn't be run.
1463  */
1464 static void
1465 JobRestart(Job *job)
1466 {
1467
1468         if (job->flags & JOB_RESTART) {
1469                 /*
1470                  * Set up the control arguments to the shell. This is based on
1471                  * the flags set earlier for this job. If the JOB_IGNERR flag
1472                  * is clear, the 'exit' flag of the commandShell is used to
1473                  * cause it to exit upon receiving an error. If the JOB_SILENT
1474                  * flag is clear, the 'echo' flag of the commandShell is used
1475                  * to get it to start echoing as soon as it starts
1476                  * processing commands.
1477                  */
1478                 char    *argv[4];
1479
1480                 JobMakeArgv(job, argv);
1481
1482                 DEBUGF(JOB, ("Restarting %s...", job->node->name));
1483                 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL)) {
1484                         /*
1485                          * Not allowed to run -- put it back on the hold
1486                          * queue and mark the table full
1487                          */
1488                         DEBUGF(JOB, ("holding\n"));
1489                         TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1490                         jobFull = TRUE;
1491                         DEBUGF(JOB, ("Job queue is full.\n"));
1492                         return;
1493                 } else {
1494                         /*
1495                          * Job may be run locally.
1496                          */
1497                         DEBUGF(JOB, ("running locally\n"));
1498                 }
1499                 JobExec(job, argv);
1500
1501         } else {
1502                 /*
1503                  * The job has stopped and needs to be restarted.
1504                  * Why it stopped, we don't know...
1505                  */
1506                 DEBUGF(JOB, ("Resuming %s...", job->node->name));
1507                 if ((nJobs < maxJobs || ((job->flags & JOB_SPECIAL) &&
1508                     maxJobs == 0)) && nJobs != maxJobs) {
1509                         /*
1510                          * If we haven't reached the concurrency limit already
1511                          * (or the job must be run and maxJobs is 0), it's ok
1512                          * to resume it.
1513                          */
1514                         Boolean error;
1515                         int status;
1516
1517                         error = (KILL(job->pid, SIGCONT) != 0);
1518
1519                         if (!error) {
1520                                 /*
1521                                  * Make sure the user knows we've continued
1522                                  * the beast and actually put the thing in the
1523                                  * job table.
1524                                  */
1525                                 job->flags |= JOB_CONTINUING;
1526                                 status = 0;
1527                                 W_SETTERMSIG(&status, SIGCONT);
1528                                 JobFinish(job, &status);
1529
1530                                 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1531                                 DEBUGF(JOB, ("done\n"));
1532                         } else {
1533                                 Error("couldn't resume %s: %s",
1534                                 job->node->name, strerror(errno));
1535                                 status = 0;
1536                                 W_SETEXITSTATUS(&status, 1);
1537                                 JobFinish(job, &status);
1538                         }
1539                 } else {
1540                         /*
1541                         * Job cannot be restarted. Mark the table as full and
1542                         * place the job back on the list of stopped jobs.
1543                         */
1544                         DEBUGF(JOB, ("table full\n"));
1545                         TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1546                         jobFull = TRUE;
1547                         DEBUGF(JOB, ("Job queue is full.\n"));
1548                 }
1549         }
1550 }
1551
1552 /**
1553  * JobStart
1554  *      Start a target-creation process going for the target described
1555  *      by the graph node gn.
1556  *
1557  * Results:
1558  *      JOB_ERROR if there was an error in the commands, JOB_FINISHED
1559  *      if there isn't actually anything left to do for the job and
1560  *      JOB_RUNNING if the job has been started.
1561  *
1562  * Side Effects:
1563  *      A new Job node is created and added to the list of running
1564  *      jobs. PMake is forked and a child shell created.
1565  */
1566 static int
1567 JobStart(GNode *gn, int flags, Job *previous)
1568 {
1569         Job     *job;           /* new job descriptor */
1570         char    *argv[4];       /* Argument vector to shell */
1571         Boolean cmdsOK;         /* true if the nodes commands were all right */
1572         Boolean noExec;         /* Set true if we decide not to run the job */
1573         int     tfd;            /* File descriptor for temp file */
1574         LstNode *ln;
1575         char    tfile[sizeof(TMPPAT)];
1576
1577         if (interrupted) {
1578                 JobPassSig(interrupted);
1579                 return (JOB_ERROR);
1580         }
1581         if (previous != NULL) {
1582                 previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1583                 job = previous;
1584         } else {
1585                 job = emalloc(sizeof(Job));
1586                 flags |= JOB_FIRST;
1587         }
1588
1589         job->node = gn;
1590         job->tailCmds = NULL;
1591
1592         /*
1593          * Set the initial value of the flags for this job based on the global
1594          * ones and the node's attributes... Any flags supplied by the caller
1595          * are also added to the field.
1596          */
1597         job->flags = 0;
1598         if (Targ_Ignore(gn)) {
1599                 job->flags |= JOB_IGNERR;
1600         }
1601         if (Targ_Silent(gn)) {
1602                 job->flags |= JOB_SILENT;
1603         }
1604         job->flags |= flags;
1605
1606         /*
1607          * Check the commands now so any attributes from .DEFAULT have a chance
1608          * to migrate to the node.
1609          */
1610         if (!compatMake && (job->flags & JOB_FIRST)) {
1611                 cmdsOK = Job_CheckCommands(gn, Error);
1612         } else {
1613                 cmdsOK = TRUE;
1614         }
1615
1616         /*
1617          * If the -n flag wasn't given, we open up OUR (not the child's)
1618          * temporary file to stuff commands in it. The thing is rd/wr so we
1619          * don't need to reopen it to feed it to the shell. If the -n flag
1620          * *was* given, we just set the file to be stdout. Cute, huh?
1621          */
1622         if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1623                 /*
1624                  * We're serious here, but if the commands were bogus, we're
1625                  * also dead...
1626                  */
1627                 if (!cmdsOK) {
1628                         DieHorribly();
1629                 }
1630
1631                 strcpy(tfile, TMPPAT);
1632                 if ((tfd = mkstemp(tfile)) == -1)
1633                         Punt("Cannot create temp file: %s", strerror(errno));
1634                 job->cmdFILE = fdopen(tfd, "w+");
1635                 eunlink(tfile);
1636                 if (job->cmdFILE == NULL) {
1637                         close(tfd);
1638                         Punt("Could not open %s", tfile);
1639                 }
1640                 fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1641                 /*
1642                  * Send the commands to the command file, flush all its
1643                  * buffers then rewind and remove the thing.
1644                  */
1645                 noExec = FALSE;
1646
1647                 /*
1648                  * Used to be backwards; replace when start doing multiple
1649                  * commands per shell.
1650                  */
1651                 if (compatMake) {
1652                         /*
1653                          * Be compatible: If this is the first time for this
1654                          * node, verify its commands are ok and open the
1655                          * commands list for sequential access by later
1656                          * invocations of JobStart. Once that is done, we take
1657                          * the next command off the list and print it to the
1658                          * command file. If the command was an ellipsis, note
1659                          * that there's nothing more to execute.
1660                          */
1661                         if (job->flags & JOB_FIRST)
1662                                 gn->compat_command = Lst_First(&gn->commands);
1663                         else
1664                                 gn->compat_command =
1665                                     Lst_Succ(gn->compat_command);
1666
1667                         if (gn->compat_command == NULL ||
1668                             JobPrintCommand(Lst_Datum(gn->compat_command), job))
1669                                 noExec = TRUE;
1670
1671                         if (noExec && !(job->flags & JOB_FIRST)) {
1672                                 /*
1673                                  * If we're not going to execute anything, the
1674                                  * job is done and we need to close down the
1675                                  * various file descriptors we've opened for
1676                                  * output, then call JobDoOutput to catch the
1677                                  * final characters or send the file to the
1678                                  * screen... Note that the i/o streams are only
1679                                  * open if this isn't the first job. Note also
1680                                  * that this could not be done in
1681                                  * Job_CatchChildren b/c it wasn't clear if
1682                                  * there were more commands to execute or not...
1683                                  */
1684                                 JobClose(job);
1685                         }
1686                 } else {
1687                         /*
1688                          * We can do all the commands at once. hooray for sanity
1689                          */
1690                         numCommands = 0;
1691                         LST_FOREACH(ln, &gn->commands) {
1692                                 if (JobPrintCommand(Lst_Datum(ln), job))
1693                                         break;
1694                         }
1695
1696                         /*
1697                          * If we didn't print out any commands to the shell
1698                          * script, there's not much point in executing the
1699                          * shell, is there?
1700                          */
1701                         if (numCommands == 0) {
1702                                 noExec = TRUE;
1703                         }
1704                 }
1705
1706         } else if (noExecute) {
1707                 /*
1708                  * Not executing anything -- just print all the commands to
1709                  * stdout in one fell swoop. This will still set up
1710                  * job->tailCmds correctly.
1711                  */
1712                 if (lastNode != gn) {
1713                         MESSAGE(stdout, gn);
1714                         lastNode = gn;
1715                 }
1716                 job->cmdFILE = stdout;
1717
1718                 /*
1719                  * Only print the commands if they're ok, but don't die if
1720                  * they're not -- just let the user know they're bad and keep
1721                  * going. It doesn't do any harm in this case and may do
1722                  * some good.
1723                  */
1724                 if (cmdsOK) {
1725                         LST_FOREACH(ln, &gn->commands) {
1726                                 if (JobPrintCommand(Lst_Datum(ln), job))
1727                                         break;
1728                         }
1729                 }
1730                 /*
1731                 * Don't execute the shell, thank you.
1732                 */
1733                 noExec = TRUE;
1734
1735         } else {
1736                 /*
1737                  * Just touch the target and note that no shell should be
1738                  * executed. Set cmdFILE to stdout to make life easier. Check
1739                  * the commands, too, but don't die if they're no good -- it
1740                  * does no harm to keep working up the graph.
1741                  */
1742                 job->cmdFILE = stdout;
1743                 Job_Touch(gn, job->flags & JOB_SILENT);
1744                 noExec = TRUE;
1745         }
1746
1747         /*
1748          * If we're not supposed to execute a shell, don't.
1749          */
1750         if (noExec) {
1751                 /*
1752                  * Unlink and close the command file if we opened one
1753                  */
1754                 if (job->cmdFILE != stdout) {
1755                         if (job->cmdFILE != NULL)
1756                                 fclose(job->cmdFILE);
1757                 } else {
1758                         fflush(stdout);
1759                 }
1760
1761                 /*
1762                  * We only want to work our way up the graph if we aren't here
1763                  * because the commands for the job were no good.
1764                 */
1765                 if (cmdsOK) {
1766                         if (aborting == 0) {
1767                                 for (ln = job->tailCmds; ln != NULL;
1768                                     ln = LST_NEXT(ln)) {
1769                                         Lst_AtEnd(&postCommands->commands,
1770                                             Buf_Peel(Var_Subst(Lst_Datum(ln),
1771                                             job->node, FALSE)));
1772                                 }
1773                                 job->node->made = MADE;
1774                                 Make_Update(job->node);
1775                         }
1776                         free(job);
1777                         return(JOB_FINISHED);
1778                 } else {
1779                         free(job);
1780                         return(JOB_ERROR);
1781                 }
1782         } else {
1783                 fflush(job->cmdFILE);
1784         }
1785
1786         /*
1787          * Set up the control arguments to the shell. This is based on the flags
1788          * set earlier for this job.
1789          */
1790         JobMakeArgv(job, argv);
1791
1792         /*
1793          * If we're using pipes to catch output, create the pipe by which we'll
1794          * get the shell's output. If we're using files, print out that we're
1795          * starting a job and then set up its temporary-file name.
1796          */
1797         if (!compatMake || (job->flags & JOB_FIRST)) {
1798                 if (usePipes) {
1799                         int fd[2];
1800
1801                         if (pipe(fd) == -1)
1802                                 Punt("Cannot create pipe: %s", strerror(errno));
1803                         job->inPipe = fd[0];
1804                         job->outPipe = fd[1];
1805                         fcntl(job->inPipe, F_SETFD, 1);
1806                         fcntl(job->outPipe, F_SETFD, 1);
1807                 } else {
1808                         fprintf(stdout, "Remaking `%s'\n", gn->name);
1809                         fflush(stdout);
1810                         strcpy(job->outFile, TMPPAT);
1811                         if ((job->outFd = mkstemp(job->outFile)) == -1)
1812                                 Punt("cannot create temp file: %s",
1813                                     strerror(errno));
1814                         fcntl(job->outFd, F_SETFD, 1);
1815                 }
1816         }
1817
1818         if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL) && maxJobs != 0) {
1819                 /*
1820                  * We've hit the limit of concurrency, so put the job on hold
1821                  * until some other job finishes. Note that the special jobs
1822                  * (.BEGIN, .INTERRUPT and .END) may be run even when the
1823                  * limit has been reached (e.g. when maxJobs == 0).
1824                  */
1825                 jobFull = TRUE;
1826
1827                 DEBUGF(JOB, ("Can only run job locally.\n"));
1828                 job->flags |= JOB_RESTART;
1829                 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1830         } else {
1831                 if (nJobs >= maxJobs) {
1832                         /*
1833                          * If we're running this job as a special case
1834                          * (see above), at least say the table is full.
1835                          */
1836                         jobFull = TRUE;
1837                         DEBUGF(JOB, ("Local job queue is full.\n"));
1838                 }
1839                 JobExec(job, argv);
1840         }
1841         return (JOB_RUNNING);
1842 }
1843
1844 static char *
1845 JobOutput(Job *job, char *cp, char *endp, int msg)
1846 {
1847         char *ecp;
1848
1849         if (commandShell->noPrint) {
1850                 ecp = strstr(cp, commandShell->noPrint);
1851                 while (ecp != NULL) {
1852                         if (cp != ecp) {
1853                                 *ecp = '\0';
1854                                 if (msg && job->node != lastNode) {
1855                                         MESSAGE(stdout, job->node);
1856                                         lastNode = job->node;
1857                                 }
1858                                 /*
1859                                  * The only way there wouldn't be a newline
1860                                  * after this line is if it were the last in
1861                                  * the buffer. However, since the non-printable
1862                                  * comes after it, there must be a newline, so
1863                                  * we don't print one.
1864                                  */
1865                                 fprintf(stdout, "%s", cp);
1866                                 fflush(stdout);
1867                         }
1868                         cp = ecp + strlen(commandShell->noPrint);
1869                         if (cp != endp) {
1870                                 /*
1871                                  * Still more to print, look again after
1872                                  * skipping the whitespace following the
1873                                  * non-printable command....
1874                                  */
1875                                 cp++;
1876                                 while (*cp == ' ' || *cp == '\t' ||
1877                                     *cp == '\n') {
1878                                         cp++;
1879                                 }
1880                                 ecp = strstr(cp, commandShell->noPrint);
1881                         } else {
1882                                 return (cp);
1883                         }
1884                 }
1885         }
1886         return (cp);
1887 }
1888
1889 /**
1890  * JobDoOutput
1891  *      This function is called at different times depending on
1892  *      whether the user has specified that output is to be collected
1893  *      via pipes or temporary files. In the former case, we are called
1894  *      whenever there is something to read on the pipe. We collect more
1895  *      output from the given job and store it in the job's outBuf. If
1896  *      this makes up a line, we print it tagged by the job's identifier,
1897  *      as necessary.
1898  *      If output has been collected in a temporary file, we open the
1899  *      file and read it line by line, transfering it to our own
1900  *      output channel until the file is empty. At which point we
1901  *      remove the temporary file.
1902  *      In both cases, however, we keep our figurative eye out for the
1903  *      'noPrint' line for the shell from which the output came. If
1904  *      we recognize a line, we don't print it. If the command is not
1905  *      alone on the line (the character after it is not \0 or \n), we
1906  *      do print whatever follows it.
1907  *
1908  * Side Effects:
1909  *      curPos may be shifted as may the contents of outBuf.
1910  */
1911 static void
1912 JobDoOutput(Job *job, Boolean finish)
1913 {
1914         Boolean gotNL = FALSE;  /* true if got a newline */
1915         Boolean fbuf;           /* true if our buffer filled up */
1916         int     nr;             /* number of bytes read */
1917         int     i;              /* auxiliary index into outBuf */
1918         int     max;            /* limit for i (end of current data) */
1919         int     nRead;          /* (Temporary) number of bytes read */
1920         FILE    *oFILE;         /* Stream pointer to shell's output file */
1921         char    inLine[132];
1922
1923         if (usePipes) {
1924                 /*
1925                  * Read as many bytes as will fit in the buffer.
1926                  */
1927   end_loop:
1928                 gotNL = FALSE;
1929                 fbuf = FALSE;
1930
1931                 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1932                     JOB_BUFSIZE - job->curPos);
1933                 /*
1934                  * Check for interrupt here too, because the above read may
1935                  * block when the child process is stopped. In this case the
1936                  * interrupt will unblock it (we don't use SA_RESTART).
1937                  */
1938                 if (interrupted)
1939                         JobPassSig(interrupted);
1940
1941                 if (nRead < 0) {
1942                         DEBUGF(JOB, ("JobDoOutput(piperead)"));
1943                         nr = 0;
1944                 } else {
1945                         nr = nRead;
1946                 }
1947
1948                 /*
1949                  * If we hit the end-of-file (the job is dead), we must flush
1950                  * its remaining output, so pretend we read a newline if
1951                  * there's any output remaining in the buffer.
1952                  * Also clear the 'finish' flag so we stop looping.
1953                  */
1954                 if (nr == 0 && job->curPos != 0) {
1955                         job->outBuf[job->curPos] = '\n';
1956                         nr = 1;
1957                         finish = FALSE;
1958                 } else if (nr == 0) {
1959                         finish = FALSE;
1960                 }
1961
1962                 /*
1963                  * Look for the last newline in the bytes we just got. If there
1964                  * is one, break out of the loop with 'i' as its index and
1965                  * gotNL set TRUE.
1966                 */
1967                 max = job->curPos + nr;
1968                 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1969                         if (job->outBuf[i] == '\n') {
1970                                 gotNL = TRUE;
1971                                 break;
1972                         } else if (job->outBuf[i] == '\0') {
1973                                 /*
1974                                  * Why?
1975                                  */
1976                                 job->outBuf[i] = ' ';
1977                         }
1978                 }
1979
1980                 if (!gotNL) {
1981                         job->curPos += nr;
1982                         if (job->curPos == JOB_BUFSIZE) {
1983                                 /*
1984                                  * If we've run out of buffer space, we have
1985                                  * no choice but to print the stuff. sigh.
1986                                  */
1987                                 fbuf = TRUE;
1988                                 i = job->curPos;
1989                         }
1990                 }
1991                 if (gotNL || fbuf) {
1992                         /*
1993                          * Need to send the output to the screen. Null terminate
1994                          * it first, overwriting the newline character if there
1995                          * was one. So long as the line isn't one we should
1996                          * filter (according to the shell description), we print
1997                          * the line, preceded by a target banner if this target
1998                          * isn't the same as the one for which we last printed
1999                          * something. The rest of the data in the buffer are
2000                          * then shifted down to the start of the buffer and
2001                          * curPos is set accordingly.
2002                          */
2003                         job->outBuf[i] = '\0';
2004                         if (i >= job->curPos) {
2005                                 char *cp;
2006
2007                                 cp = JobOutput(job, job->outBuf,
2008                                     &job->outBuf[i], FALSE);
2009
2010                                 /*
2011                                  * There's still more in that buffer. This time,
2012                                  * though, we know there's no newline at the
2013                                  * end, so we add one of our own free will.
2014                                  */
2015                                 if (*cp != '\0') {
2016                                         if (job->node != lastNode) {
2017                                                 MESSAGE(stdout, job->node);
2018                                                 lastNode = job->node;
2019                                         }
2020                                         fprintf(stdout, "%s%s", cp,
2021                                             gotNL ? "\n" : "");
2022                                         fflush(stdout);
2023                                 }
2024                         }
2025                         if (i < max - 1) {
2026                                 /* shift the remaining characters down */
2027                                 memcpy(job->outBuf, &job->outBuf[i + 1],
2028                                     max - (i + 1));
2029                                 job->curPos = max - (i + 1);
2030
2031                         } else {
2032                                 /*
2033                                  * We have written everything out, so we just
2034                                  * start over from the start of the buffer.
2035                                  * No copying. No nothing.
2036                                  */
2037                                 job->curPos = 0;
2038                         }
2039                 }
2040                 if (finish) {
2041                         /*
2042                          * If the finish flag is true, we must loop until we hit
2043                          * end-of-file on the pipe. This is guaranteed to happen
2044                          * eventually since the other end of the pipe is now
2045                          * closed (we closed it explicitly and the child has
2046                          * exited). When we do get an EOF, finish will be set
2047                          * FALSE and we'll fall through and out.
2048                          */
2049                         goto end_loop;
2050                 }
2051
2052         } else {
2053                 /*
2054                  * We've been called to retrieve the output of the job from the
2055                  * temporary file where it's been squirreled away. This consists
2056                  * of opening the file, reading the output line by line, being
2057                  * sure not to print the noPrint line for the shell we used,
2058                  * then close and remove the temporary file. Very simple.
2059                  *
2060                  * Change to read in blocks and do FindSubString type things
2061                  * as for pipes? That would allow for "@echo -n..."
2062                  */
2063                 oFILE = fopen(job->outFile, "r");
2064                 if (oFILE != NULL) {
2065                         fprintf(stdout, "Results of making %s:\n",
2066                             job->node->name);
2067                         fflush(stdout);
2068
2069                         while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2070                                 char    *cp, *endp, *oendp;
2071
2072                                 cp = inLine;
2073                                 oendp = endp = inLine + strlen(inLine);
2074                                 if (endp[-1] == '\n') {
2075                                         *--endp = '\0';
2076                                 }
2077                                 cp = JobOutput(job, inLine, endp, FALSE);
2078
2079                                 /*
2080                                  * There's still more in that buffer. This time,
2081                                  * though, we know there's no newline at the
2082                                  * end, so we add one of our own free will.
2083                                  */
2084                                 fprintf(stdout, "%s", cp);
2085                                 fflush(stdout);
2086                                 if (endp != oendp) {
2087                                         fprintf(stdout, "\n");
2088                                         fflush(stdout);
2089                                 }
2090                         }
2091                         fclose(oFILE);
2092                         eunlink(job->outFile);
2093                 }
2094         }
2095 }
2096
2097 /**
2098  * Job_CatchChildren
2099  *      Handle the exit of a child. Called from Make_Make.
2100  *
2101  * Side Effects:
2102  *      The job descriptor is removed from the list of children.
2103  *
2104  * Notes:
2105  *      We do waits, blocking or not, according to the wisdom of our
2106  *      caller, until there are no more children to report. For each
2107  *      job, call JobFinish to finish things off. This will take care of
2108  *      putting jobs on the stoppedJobs queue.
2109  */
2110 void
2111 Job_CatchChildren(Boolean block)
2112 {
2113         pid_t   pid;    /* pid of dead child */
2114         Job     *job;   /* job descriptor for dead child */
2115         int     status; /* Exit/termination status */
2116
2117         /*
2118          * Don't even bother if we know there's no one around.
2119          */
2120         if (nJobs == 0) {
2121                 return;
2122         }
2123
2124         for (;;) {
2125                 pid = waitpid((pid_t)-1, &status,
2126                     (block ? 0 : WNOHANG) | WUNTRACED);
2127                 if (pid <= 0)
2128                         break;
2129
2130                 DEBUGF(JOB, ("Process %jd exited or stopped.\n",
2131                     (intmax_t)pid));
2132
2133                 TAILQ_FOREACH(job, &jobs, link) {
2134                         if (job->pid == pid)
2135                                 break;
2136                 }
2137
2138                 if (job == NULL) {
2139                         if (WIFSIGNALED(status) &&
2140                             (WTERMSIG(status) == SIGCONT)) {
2141                                 TAILQ_FOREACH(job, &jobs, link) {
2142                                         if (job->pid == pid)
2143                                                 break;
2144                                 }
2145                                 if (job == NULL) {
2146                                         Error("Resumed child (%jd) "
2147                                             "not in table", (intmax_t)pid);
2148                                         continue;
2149                                 }
2150                                 TAILQ_REMOVE(&stoppedJobs, job, link);
2151                         } else {
2152                                 Error("Child (%jd) not in table?",
2153                                     (intmax_t)pid);
2154                                 continue;
2155                         }
2156                 } else {
2157                         TAILQ_REMOVE(&jobs, job, link);
2158                         nJobs -= 1;
2159                         if (fifoFd >= 0 && maxJobs > 1) {
2160                                 write(fifoFd, "+", 1);
2161                                 maxJobs--;
2162                                 if (nJobs >= maxJobs)
2163                                         jobFull = TRUE;
2164                                 else
2165                                         jobFull = FALSE;
2166                         } else {
2167                                 DEBUGF(JOB, ("Job queue is no longer full.\n"));
2168                                 jobFull = FALSE;
2169                         }
2170                 }
2171
2172                 JobFinish(job, &status);
2173         }
2174         if (interrupted)
2175                 JobPassSig(interrupted);
2176 }
2177
2178 /**
2179  * Job_CatchOutput
2180  *      Catch the output from our children, if we're using
2181  *      pipes do so. Otherwise just block time until we get a
2182  *      signal(most likely a SIGCHLD) since there's no point in
2183  *      just spinning when there's nothing to do and the reaping
2184  *      of a child can wait for a while.
2185  *
2186  * Side Effects:
2187  *      Output is read from pipes if we're piping.
2188  * -----------------------------------------------------------------------
2189  */
2190 void
2191 #ifdef USE_KQUEUE
2192 Job_CatchOutput(int flag __unused)
2193 #else
2194 Job_CatchOutput(int flag)
2195 #endif
2196 {
2197         int             nfds;
2198 #ifdef USE_KQUEUE
2199 #define KEV_SIZE        4
2200         struct kevent   kev[KEV_SIZE];
2201         int             i;
2202 #else
2203         struct timeval  timeout;
2204         fd_set          readfds;
2205         Job             *job;
2206 #endif
2207
2208         fflush(stdout);
2209
2210         if (usePipes) {
2211 #ifdef USE_KQUEUE
2212                 if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
2213                         if (errno != EINTR)
2214                                 Punt("kevent: %s", strerror(errno));
2215                         if (interrupted)
2216                                 JobPassSig(interrupted);
2217                 } else {
2218                         for (i = 0; i < nfds; i++) {
2219                                 if (kev[i].flags & EV_ERROR) {
2220                                         warnc(kev[i].data, "kevent");
2221                                         continue;
2222                                 }
2223                                 switch (kev[i].filter) {
2224                                   case EVFILT_READ:
2225                                         JobDoOutput(kev[i].udata, FALSE);
2226                                         break;
2227                                   case EVFILT_PROC:
2228                                         /*
2229                                          * Just wake up and let
2230                                          * Job_CatchChildren() collect the
2231                                          * terminated job.
2232                                          */
2233                                         break;
2234                                 }
2235                         }
2236                 }
2237 #else
2238                 readfds = outputs;
2239                 timeout.tv_sec = SEL_SEC;
2240                 timeout.tv_usec = SEL_USEC;
2241                 if (flag && jobFull && fifoFd >= 0)
2242                         FD_SET(fifoFd, &readfds);
2243
2244                 nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
2245                     (fd_set *)NULL, &timeout);
2246                 if (nfds <= 0) {
2247                         if (interrupted)
2248                                 JobPassSig(interrupted);
2249                         return;
2250                 }
2251                 if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2252                         if (--nfds <= 0)
2253                                 return;
2254                 }
2255                 job = TAILQ_FIRST(&jobs);
2256                 while (nfds != 0 && job != NULL) {
2257                         if (FD_ISSET(job->inPipe, &readfds)) {
2258                                 JobDoOutput(job, FALSE);
2259                                 nfds--;
2260                         }
2261                         job = TAILQ_NEXT(job, link);
2262                 }
2263 #endif /* !USE_KQUEUE */
2264         }
2265 }
2266
2267 /**
2268  * Job_Make
2269  *      Start the creation of a target. Basically a front-end for
2270  *      JobStart used by the Make module.
2271  *
2272  * Side Effects:
2273  *      Another job is started.
2274  */
2275 void
2276 Job_Make(GNode *gn)
2277 {
2278
2279         JobStart(gn, 0, NULL);
2280 }
2281
2282 void
2283 Job_SetPrefix(void)
2284 {
2285
2286         if (targPrefix) {
2287                 free(targPrefix);
2288         } else if (!Var_Exists(MAKE_JOB_PREFIX, VAR_GLOBAL)) {
2289                 Var_SetGlobal(MAKE_JOB_PREFIX, "---");
2290         }
2291         targPrefix = Var_Subst("${" MAKE_JOB_PREFIX "}", VAR_GLOBAL, 0)->buf;
2292 }
2293
2294 /**
2295  * Job_Init
2296  *      Initialize the process module, given a maximum number of jobs.
2297  *
2298  * Side Effects:
2299  *      lists and counters are initialized
2300  */
2301 void
2302 Job_Init(int maxproc)
2303 {
2304         GNode           *begin; /* node for commands to do at the very start */
2305         const char      *env;
2306         struct sigaction sa;
2307
2308         fifoFd = -1;
2309         env = getenv("MAKE_JOBS_FIFO");
2310
2311         if (env == NULL && maxproc > 1) {
2312                 /*
2313                  * We did not find the environment variable so we are the
2314                  * leader. Create the fifo, open it, write one char per
2315                  * allowed job into the pipe.
2316                  */
2317                 fifoFd = mkfifotemp(fifoName);
2318                 if (fifoFd < 0) {
2319                         env = NULL;
2320                 } else {
2321                         fifoMaster = 1;
2322                         fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2323                         env = fifoName;
2324                         setenv("MAKE_JOBS_FIFO", env, 1);
2325                         while (maxproc-- > 0) {
2326                                 write(fifoFd, "+", 1);
2327                         }
2328                         /* The master make does not get a magic token */
2329                         jobFull = TRUE;
2330                         maxJobs = 0;
2331                 }
2332
2333         } else if (env != NULL) {
2334                 /*
2335                  * We had the environment variable so we are a slave.
2336                  * Open fifo and give ourselves a magic token which represents
2337                  * the token our parent make has grabbed to start his make
2338                  * process. Otherwise the sub-makes would gobble up tokens and
2339                  * the proper number of tokens to specify to -j would depend
2340                  * on the depth of the tree and the order of execution.
2341                  */
2342                 fifoFd = open(env, O_RDWR, 0);
2343                 if (fifoFd >= 0) {
2344                         fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2345                         maxJobs = 1;
2346                         jobFull = FALSE;
2347                 }
2348         }
2349         if (fifoFd < 0) {
2350                 maxJobs = maxproc;
2351                 jobFull = FALSE;
2352         } else {
2353         }
2354         nJobs = 0;
2355
2356         aborting = 0;
2357         makeErrors = 0;
2358
2359         lastNode = NULL;
2360         if ((maxJobs == 1 && fifoFd < 0) || !beVerbose || is_posix || beQuiet) {
2361                 /*
2362                  * If only one job can run at a time, there's no need for a
2363                  * banner, no is there?
2364                  */
2365                 targFmt = "";
2366         } else {
2367                 targFmt = TARG_FMT;
2368         }
2369
2370         /*
2371          * Catch the four signals that POSIX specifies if they aren't ignored.
2372          * JobCatchSignal will just set global variables and hope someone
2373          * else is going to handle the interrupt.
2374          */
2375         sa.sa_handler = JobCatchSig;
2376         sigemptyset(&sa.sa_mask);
2377         sa.sa_flags = 0;
2378
2379         if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2380                 sigaction(SIGINT, &sa, NULL);
2381         }
2382         if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2383                 sigaction(SIGHUP, &sa, NULL);
2384         }
2385         if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2386                 sigaction(SIGQUIT, &sa, NULL);
2387         }
2388         if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2389                 sigaction(SIGTERM, &sa, NULL);
2390         }
2391         /*
2392          * There are additional signals that need to be caught and passed if
2393          * either the export system wants to be told directly of signals or if
2394          * we're giving each job its own process group (since then it won't get
2395          * signals from the terminal driver as we own the terminal)
2396          */
2397 #if defined(USE_PGRP)
2398         if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2399                 sigaction(SIGTSTP, &sa, NULL);
2400         }
2401         if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2402                 sigaction(SIGTTOU, &sa, NULL);
2403         }
2404         if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2405                 sigaction(SIGTTIN, &sa, NULL);
2406         }
2407         if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2408                 sigaction(SIGWINCH, &sa, NULL);
2409         }
2410 #endif
2411
2412 #ifdef USE_KQUEUE
2413         if ((kqfd = kqueue()) == -1) {
2414                 Punt("kqueue: %s", strerror(errno));
2415         }
2416 #endif
2417
2418         begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2419
2420         if (begin != NULL) {
2421                 JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2422                 while (nJobs) {
2423                         Job_CatchOutput(0);
2424                         Job_CatchChildren(!usePipes);
2425                 }
2426         }
2427         postCommands = Targ_FindNode(".END", TARG_CREATE);
2428 }
2429
2430 /**
2431  * Job_Full
2432  *      See if the job table is full. It is considered full if it is OR
2433  *      if we are in the process of aborting OR if we have
2434  *      reached/exceeded our local quota. This prevents any more jobs
2435  *      from starting up.
2436  *
2437  * Results:
2438  *      TRUE if the job table is full, FALSE otherwise
2439  */
2440 Boolean
2441 Job_Full(void)
2442 {
2443         char c;
2444         int i;
2445
2446         if (aborting)
2447                 return (aborting);
2448         if (fifoFd >= 0 && jobFull) {
2449                 i = read(fifoFd, &c, 1);
2450                 if (i > 0) {
2451                         maxJobs++;
2452                         jobFull = FALSE;
2453                 }
2454         }
2455         return (jobFull);
2456 }
2457
2458 /**
2459  * Job_Empty
2460  *      See if the job table is empty.  Because the local concurrency may
2461  *      be set to 0, it is possible for the job table to become empty,
2462  *      while the list of stoppedJobs remains non-empty. In such a case,
2463  *      we want to restart as many jobs as we can.
2464  *
2465  * Results:
2466  *      TRUE if it is. FALSE if it ain't.
2467  */
2468 Boolean
2469 Job_Empty(void)
2470 {
2471         if (nJobs == 0) {
2472                 if (!TAILQ_EMPTY(&stoppedJobs) && !aborting) {
2473                         /*
2474                          * The job table is obviously not full if it has no
2475                          * jobs in it...Try and restart the stopped jobs.
2476                          */
2477                         jobFull = FALSE;
2478                         JobRestartJobs();
2479                         return (FALSE);
2480                 } else {
2481                         return (TRUE);
2482                 }
2483         } else {
2484                 return (FALSE);
2485         }
2486 }
2487
2488 /**
2489  * JobInterrupt
2490  *      Handle the receipt of an interrupt.
2491  *
2492  * Side Effects:
2493  *      All children are killed. Another job will be started if the
2494  *      .INTERRUPT target was given.
2495  */
2496 static void
2497 JobInterrupt(int runINTERRUPT, int signo)
2498 {
2499         Job     *job;           /* job descriptor in that element */
2500         GNode   *interrupt;     /* the node describing the .INTERRUPT target */
2501
2502         aborting = ABORT_INTERRUPT;
2503
2504         TAILQ_FOREACH(job, &jobs, link) {
2505                 if (!Targ_Precious(job->node)) {
2506                         char *file = (job->node->path == NULL ?
2507                             job->node->name : job->node->path);
2508
2509                         if (!noExecute && eunlink(file) != -1) {
2510                                 Error("*** %s removed", file);
2511                         }
2512                 }
2513                 if (job->pid) {
2514                         DEBUGF(JOB, ("JobInterrupt passing signal to child "
2515                             "%jd.\n", (intmax_t)job->pid));
2516                         KILL(job->pid, signo);
2517                 }
2518         }
2519
2520         if (runINTERRUPT && !touchFlag) {
2521                 /*
2522                  * clear the interrupted flag because we would get an
2523                  * infinite loop otherwise.
2524                  */
2525                 interrupted = 0;
2526
2527                 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2528                 if (interrupt != NULL) {
2529                         ignoreErrors = FALSE;
2530
2531                         JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
2532                         while (nJobs) {
2533                                 Job_CatchOutput(0);
2534                                 Job_CatchChildren(!usePipes);
2535                         }
2536                 }
2537         }
2538         if (fifoMaster)
2539                 unlink(fifoName);
2540 }
2541
2542 /**
2543  * Job_Finish
2544  *      Do final processing such as the running of the commands
2545  *      attached to the .END target.
2546  *
2547  * Results:
2548  *      None.
2549  */
2550 void
2551 Job_Finish(void)
2552 {
2553
2554         if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
2555                 if (makeErrors) {
2556                         Error("Errors reported so .END ignored");
2557                 } else {
2558                         JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
2559
2560                         while (nJobs) {
2561                                 Job_CatchOutput(0);
2562                                 Job_CatchChildren(!usePipes);
2563                         }
2564                 }
2565         }
2566         if (fifoFd >= 0) {
2567                 close(fifoFd);
2568                 fifoFd = -1;
2569                 if (fifoMaster)
2570                         unlink(fifoName);
2571         }
2572 }
2573
2574 /**
2575  * Job_Wait
2576  *      Waits for all running jobs to finish and returns. Sets 'aborting'
2577  *      to ABORT_WAIT to prevent other jobs from starting.
2578  *
2579  * Side Effects:
2580  *      Currently running jobs finish.
2581  */
2582 void
2583 Job_Wait(void)
2584 {
2585
2586         aborting = ABORT_WAIT;
2587         while (nJobs != 0) {
2588                 Job_CatchOutput(0);
2589                 Job_CatchChildren(!usePipes);
2590         }
2591         aborting = 0;
2592 }
2593
2594 /**
2595  * Job_AbortAll
2596  *      Abort all currently running jobs without handling output or anything.
2597  *      This function is to be called only in the event of a major
2598  *      error. Most definitely NOT to be called from JobInterrupt.
2599  *
2600  * Side Effects:
2601  *      All children are killed, not just the firstborn
2602  */
2603 void
2604 Job_AbortAll(void)
2605 {
2606         Job     *job;   /* the job descriptor in that element */
2607         int     foo;
2608
2609         aborting = ABORT_ERROR;
2610
2611         if (nJobs) {
2612                 TAILQ_FOREACH(job, &jobs, link) {
2613                         /*
2614                          * kill the child process with increasingly drastic
2615                          * signals to make darn sure it's dead.
2616                          */
2617                         KILL(job->pid, SIGINT);
2618                         KILL(job->pid, SIGKILL);
2619                 }
2620         }
2621
2622         /*
2623          * Catch as many children as want to report in at first, then give up
2624          */
2625         while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2626                 ;
2627 }
2628
2629 /**
2630  * JobRestartJobs
2631  *      Tries to restart stopped jobs if there are slots available.
2632  *      Note that this tries to restart them regardless of pending errors.
2633  *      It's not good to leave stopped jobs lying around!
2634  *
2635  * Side Effects:
2636  *      Resumes(and possibly migrates) jobs.
2637  */
2638 static void
2639 JobRestartJobs(void)
2640 {
2641         Job *job;
2642
2643         while (!jobFull && (job = TAILQ_FIRST(&stoppedJobs)) != NULL) {
2644                 DEBUGF(JOB, ("Job queue is not full. "
2645                     "Restarting a stopped job.\n"));
2646                 TAILQ_REMOVE(&stoppedJobs, job, link);
2647                 JobRestart(job);
2648         }
2649 }
2650
2651 /**
2652  * Cmd_Exec
2653  *      Execute the command in cmd, and return the output of that command
2654  *      in a string.
2655  *
2656  * Results:
2657  *      A string containing the output of the command, or the empty string
2658  *      If error is not NULL, it contains the reason for the command failure
2659  *      Any output sent to stderr in the child process is passed to stderr,
2660  *      and not captured in the string.
2661  *
2662  * Side Effects:
2663  *      The string must be freed by the caller.
2664  */
2665 Buffer *
2666 Cmd_Exec(const char *cmd, const char **error)
2667 {
2668         int     fds[2]; /* Pipe streams */
2669         int     status; /* command exit status */
2670         Buffer  *buf;   /* buffer to store the result */
2671         ssize_t rcnt;
2672         ProcStuff       ps;
2673
2674         *error = NULL;
2675         buf = Buf_Init(0);
2676
2677         /*
2678          * Open a pipe for fetching its output
2679          */
2680         if (pipe(fds) == -1) {
2681                 *error = "Couldn't create pipe for \"%s\"";
2682                 return (buf);
2683         }
2684
2685         /* Set close-on-exec on read side of pipe. */
2686         fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC);
2687
2688         ps.in = STDIN_FILENO;
2689         ps.out = fds[1];
2690         ps.err = STDERR_FILENO;
2691
2692         ps.merge_errors = 0;
2693         ps.pgroup = 0;
2694         ps.searchpath = 0;
2695
2696         /* Set up arguments for shell */
2697         ps.argv = emalloc(4 * sizeof(char *));
2698         ps.argv[0] = strdup(commandShell->name);
2699         ps.argv[1] = strdup("-c");
2700         ps.argv[2] = strdup(cmd);
2701         ps.argv[3] = NULL;
2702         ps.argv_free = 1;
2703
2704         /*
2705          * Fork.  Warning since we are doing vfork() instead of fork(),
2706          * do not allocate memory in the child process!
2707          */
2708         if ((ps.child_pid = vfork()) == -1) {
2709                 *error = "Couldn't exec \"%s\"";
2710                 return (buf);
2711
2712         } else if (ps.child_pid == 0) {
2713                 /*
2714                  * Child
2715                  */
2716                 Proc_Exec(&ps);
2717                 /* NOTREACHED */
2718         }
2719
2720         free(ps.argv[2]);
2721         free(ps.argv[1]);
2722         free(ps.argv[0]);
2723         free(ps.argv);
2724
2725         close(fds[1]); /* No need for the writing half of the pipe. */
2726
2727         do {
2728                 char    result[BUFSIZ];
2729
2730                 rcnt = read(fds[0], result, sizeof(result));
2731                 if (rcnt != -1)
2732                         Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
2733         } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
2734
2735         if (rcnt == -1)
2736                 *error = "Error reading shell's output for \"%s\"";
2737
2738         /*
2739          * Close the input side of the pipe.
2740          */
2741         close(fds[0]);
2742
2743         status = ProcWait(&ps);
2744
2745         if (status)
2746                 *error = "\"%s\" returned non-zero status";
2747
2748         Buf_StripNewlines(buf);
2749
2750         return (buf);
2751 }
2752
2753
2754 /*
2755  * Interrupt handler - set flag and defer handling to the main code
2756  */
2757 static void
2758 CompatCatchSig(int signo)
2759 {
2760
2761         interrupted = signo;
2762 }
2763
2764 /*-
2765  *-----------------------------------------------------------------------
2766  * CompatInterrupt --
2767  *      Interrupt the creation of the current target and remove it if
2768  *      it ain't precious.
2769  *
2770  * Results:
2771  *      None.
2772  *
2773  * Side Effects:
2774  *      The target is removed and the process exits. If .INTERRUPT exists,
2775  *      its commands are run first WITH INTERRUPTS IGNORED..
2776  *
2777  *-----------------------------------------------------------------------
2778  */
2779 static void
2780 CompatInterrupt(int signo)
2781 {
2782         GNode           *gn;
2783         sigset_t        nmask, omask;
2784         LstNode         *ln;
2785
2786         sigemptyset(&nmask);
2787         sigaddset(&nmask, SIGINT);
2788         sigaddset(&nmask, SIGTERM);
2789         sigaddset(&nmask, SIGHUP);
2790         sigaddset(&nmask, SIGQUIT);
2791         sigprocmask(SIG_SETMASK, &nmask, &omask);
2792
2793         /* prevent recursion in evaluation of .INTERRUPT */
2794         interrupted = 0;
2795
2796         if (curTarg != NULL && !Targ_Precious(curTarg)) {
2797                 const char      *file = Var_Value(TARGET, curTarg);
2798
2799                 if (!noExecute && eunlink(file) != -1) {
2800                         printf("*** %s removed\n", file);
2801                 }
2802         }
2803
2804         /*
2805          * Run .INTERRUPT only if hit with interrupt signal
2806          */
2807         if (signo == SIGINT) {
2808                 gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2809                 if (gn != NULL) {
2810                         LST_FOREACH(ln, &gn->commands) {
2811                                 if (Compat_RunCommand(Lst_Datum(ln), gn))
2812                                         break;
2813                         }
2814                 }
2815         }
2816
2817         sigprocmask(SIG_SETMASK, &omask, NULL);
2818
2819         if (signo == SIGQUIT)
2820                 exit(signo);
2821         signal(signo, SIG_DFL);
2822         kill(getpid(), signo);
2823 }
2824
2825 /**
2826  * shellneed
2827  *
2828  * Results:
2829  *      Returns NULL if a specified line must be executed by the shell,
2830  *      and an argument vector if it can be run via execvp().
2831  *
2832  * Side Effects:
2833  *      Uses brk_string so destroys the contents of argv.
2834  */
2835 static char **
2836 shellneed(ArgArray *aa, char *cmd)
2837 {
2838         char    **p;
2839         int     ret;
2840
2841         if (commandShell->meta == NULL || commandShell->builtins.argc <= 1)
2842                 /* use shell */
2843                 return (NULL);
2844
2845         if (strpbrk(cmd, commandShell->meta) != NULL)
2846                 return (NULL);
2847
2848         /*
2849          * Break the command into words to form an argument
2850          * vector we can execute.
2851          */
2852         brk_string(aa, cmd, TRUE);
2853         for (p = commandShell->builtins.argv + 1; *p != 0; p++) {
2854                 if ((ret = strcmp(aa->argv[1], *p)) == 0) {
2855                         /* found - use shell */
2856                         ArgArray_Done(aa);
2857                         return (NULL);
2858                 }
2859                 if (ret < 0) {
2860                         /* not found */
2861                         break;
2862                 }
2863         }
2864         return (aa->argv + 1);
2865 }
2866
2867 /**
2868  * Execute the next command for a target. If the command returns an
2869  * error, the node's made field is set to ERROR and creation stops.
2870  * The node from which the command came is also given. This is used
2871  * to execute the commands in compat mode and when executing commands
2872  * with the '+' flag in non-compat mode. In these modes each command
2873  * line should be executed by its own shell. We do some optimisation here:
2874  * if the shell description defines both a string of meta characters and
2875  * a list of builtins and the command line neither contains a meta character
2876  * nor starts with one of the builtins then we execute the command directly
2877  * without invoking a shell.
2878  *
2879  * Results:
2880  *      0 if the command succeeded, 1 if an error occurred.
2881  *
2882  * Side Effects:
2883  *      The node's 'made' field may be set to ERROR.
2884  */
2885 static int
2886 Compat_RunCommand(char *cmd, GNode *gn)
2887 {
2888         ArgArray        aa;
2889         char            *cmdStart;      /* Start of expanded command */
2890         Boolean         silent;         /* Don't print command */
2891         Boolean         doit;           /* Execute even in -n */
2892         Boolean         errCheck;       /* Check errors */
2893         int             reason;         /* Reason for child's death */
2894         int             status;         /* Description of child's death */
2895         LstNode         *cmdNode;       /* Node where current cmd is located */
2896         char            **av;           /* Argument vector for thing to exec */
2897         ProcStuff       ps;
2898
2899         silent = gn->type & OP_SILENT;
2900         errCheck = !(gn->type & OP_IGNORE);
2901         doit = FALSE;
2902
2903         cmdNode = Lst_Member(&gn->commands, cmd);
2904         cmdStart = Buf_Peel(Var_Subst(cmd, gn, FALSE));
2905
2906         /*
2907          * brk_string will return an argv with a NULL in av[0], thus causing
2908          * execvp() to choke and die horribly. Besides, how can we execute a
2909          * null command? In any case, we warn the user that the command
2910          * expanded to nothing (is this the right thing to do?).
2911          */
2912         if (*cmdStart == '\0') {
2913                 free(cmdStart);
2914                 Error("%s expands to empty string", cmd);
2915                 return (0);
2916         } else {
2917                 cmd = cmdStart;
2918         }
2919         Lst_Replace(cmdNode, cmdStart);
2920
2921         if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
2922                 Lst_AtEnd(&ENDNode->commands, cmdStart);
2923                 return (0);
2924         } else if (strcmp(cmdStart, "...") == 0) {
2925                 gn->type |= OP_SAVE_CMDS;
2926                 return (0);
2927         }
2928
2929         while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
2930                 switch (*cmd) {
2931
2932                   case '@':
2933                         silent = DEBUG(LOUD) ? FALSE : TRUE;
2934                         break;
2935
2936                   case '-':
2937                         errCheck = FALSE;
2938                         break;
2939
2940                   case '+':
2941                         doit = TRUE;
2942                         break;
2943                 }
2944                 cmd++;
2945         }
2946
2947         while (isspace((unsigned char)*cmd))
2948                 cmd++;
2949
2950         /*
2951          * Print the command before echoing if we're not supposed to be quiet
2952          * for this one. We also print the command if -n given, but not if '+'.
2953          */
2954         if (!silent || (noExecute && !doit)) {
2955                 printf("%s\n", cmd);
2956                 fflush(stdout);
2957         }
2958
2959         /*
2960          * If we're not supposed to execute any commands, this is as far as
2961          * we go...
2962          */
2963         if (!doit && noExecute) {
2964                 return (0);
2965         }
2966
2967         ps.in = STDIN_FILENO;
2968         ps.out = STDOUT_FILENO;
2969         ps.err = STDERR_FILENO;
2970
2971         ps.merge_errors = 0;
2972         ps.pgroup = 0;
2973         ps.searchpath = 1;
2974
2975         if ((av = shellneed(&aa, cmd)) == NULL) {
2976                 /*
2977                  * Shell meta character or shell builtin found - pass
2978                  * command to shell. We give the shell the -e flag as
2979                  * well as -c if it is supposed to exit when it hits an error.
2980                  */
2981                 ps.argv = emalloc(4 * sizeof(char *));
2982                 ps.argv[0] = strdup(commandShell->path);
2983                 ps.argv[1] = strdup(errCheck ? "-ec" : "-c");
2984                 ps.argv[2] = strdup(cmd);
2985                 ps.argv[3] = NULL;
2986                 ps.argv_free = 1;
2987         } else {
2988                 ps.argv = av;
2989                 ps.argv_free = 0;
2990         }
2991         ps.errCheck = errCheck;
2992
2993         /*
2994          * Warning since we are doing vfork() instead of fork(),
2995          * do not allocate memory in the child process!
2996          */
2997         if ((ps.child_pid = vfork()) == -1) {
2998                 Fatal("Could not fork");
2999
3000         } else if (ps.child_pid == 0) {
3001                 /*
3002                  * Child
3003                  */
3004                 Proc_Exec(&ps);
3005                 /* NOTREACHED */
3006
3007         } else {
3008                 if (ps.argv_free) {
3009                         free(ps.argv[2]);
3010                         free(ps.argv[1]);
3011                         free(ps.argv[0]);
3012                         free(ps.argv);
3013                 } else {
3014                         ArgArray_Done(&aa);
3015                 }
3016
3017                 /*
3018                  * we need to print out the command associated with this
3019                  * Gnode in Targ_PrintCmd from Targ_PrintGraph when debugging
3020                  * at level g2, in main(), Fatal() and DieHorribly(),
3021                  * therefore do not free it when debugging.
3022                  */
3023                 if (!DEBUG(GRAPH2)) {
3024                         free(cmdStart);
3025                 }
3026
3027                 /*
3028                  * The child is off and running. Now all we can do is wait...
3029                  */
3030                 reason = ProcWait(&ps);
3031
3032                 if (interrupted)
3033                         CompatInterrupt(interrupted);
3034   
3035                 /*
3036                  * Decode and report the reason child exited, then
3037                  * indicate how we handled it.
3038                  */
3039                 if (WIFEXITED(reason)) {
3040                         status = WEXITSTATUS(reason);
3041                         if (status == 0) {
3042                                 return (0);
3043                         } else {
3044                                 printf("*** Error code %d", status);
3045                         }
3046                 } else if (WIFSTOPPED(reason)) {
3047                         status = WSTOPSIG(reason);
3048                 } else {
3049                         status = WTERMSIG(reason);
3050                         printf("*** Signal %d", status);
3051                 }
3052   
3053                 if (ps.errCheck) {
3054                         gn->made = ERROR;
3055                         if (keepgoing) {
3056                                 /*
3057                                  * Abort the current
3058                                  * target, but let
3059                                  * others continue.
3060                                  */
3061                                 printf(" (continuing)\n");
3062                         }
3063                         return (status);
3064                 } else {
3065                         /*
3066                          * Continue executing
3067                          * commands for this target.
3068                          * If we return 0, this will
3069                          * happen...
3070                          */
3071                         printf(" (ignored)\n");
3072                         return (0);
3073                 }
3074         }
3075 }
3076
3077 /*-
3078  *-----------------------------------------------------------------------
3079  * Compat_Make --
3080  *      Make a target, given the parent, to abort if necessary.
3081  *
3082  * Side Effects:
3083  *      If an error is detected and not being ignored, the process exits.
3084  *
3085  *-----------------------------------------------------------------------
3086  */
3087 int
3088 Compat_Make(GNode *gn, GNode *pgn)
3089 {
3090         LstNode *ln;
3091
3092         if (gn->type & OP_USE) {
3093                 Make_HandleUse(gn, pgn);
3094
3095         } else if (gn->made == UNMADE) {
3096                 /*
3097                  * First mark ourselves to be made, then apply whatever
3098                  * transformations the suffix module thinks are necessary.
3099                  * Once that's done, we can descend and make all our children.
3100                  * If any of them has an error but the -k flag was given, our
3101                  * 'make' field will be set FALSE again. This is our signal to
3102                  * not attempt to do anything but abort our parent as well.
3103                  */
3104                 gn->make = TRUE;
3105                 gn->made = BEINGMADE;
3106                 Suff_FindDeps(gn);
3107                 LST_FOREACH(ln, &gn->children)
3108                         Compat_Make(Lst_Datum(ln), gn);
3109                 if (!gn->make) {
3110                         gn->made = ABORTED;
3111                         pgn->make = FALSE;
3112                         return (0);
3113                 }
3114
3115                 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3116                         Var_Set(IMPSRC, Var_Value(TARGET, gn), pgn);
3117                 }
3118
3119                 /*
3120                  * All the children were made ok. Now cmtime contains the
3121                  * modification time of the newest child, we need to find out
3122                  * if we exist and when we were modified last. The criteria for
3123                  * datedness are defined by the Make_OODate function.
3124                  */
3125                 DEBUGF(MAKE, ("Examining %s...", gn->name));
3126                 if (!Make_OODate(gn)) {
3127                         gn->made = UPTODATE;
3128                         DEBUGF(MAKE, ("up-to-date.\n"));
3129                         return (0);
3130                 } else {
3131                         DEBUGF(MAKE, ("out-of-date.\n"));
3132                 }
3133
3134                 /*
3135                  * If the user is just seeing if something is out-of-date,
3136                  * exit now to tell him/her "yes".
3137                  */
3138                 if (queryFlag) {
3139                         exit(1);
3140                 }
3141
3142                 /*
3143                  * We need to be re-made. We also have to make sure we've got
3144                  * a $? variable. To be nice, we also define the $> variable
3145                  * using Make_DoAllVar().
3146                  */
3147                 Make_DoAllVar(gn);
3148
3149                 /*
3150                  * Alter our type to tell if errors should be ignored or things
3151                  * should not be printed so Compat_RunCommand knows what to do.
3152                  */
3153                 if (Targ_Ignore(gn)) {
3154                         gn->type |= OP_IGNORE;
3155                 }
3156                 if (Targ_Silent(gn)) {
3157                         gn->type |= OP_SILENT;
3158                 }
3159
3160                 if (Job_CheckCommands(gn, Fatal)) {
3161                         /*
3162                          * Our commands are ok, but we still have to worry
3163                          * about the -t flag...
3164                          */
3165                         if (!touchFlag) {
3166                                 curTarg = gn;
3167                                 LST_FOREACH(ln, &gn->commands) {
3168                                         if (Compat_RunCommand(Lst_Datum(ln),
3169                                             gn))
3170                                                 break;
3171                                 }
3172                                 curTarg = NULL;
3173                         } else {
3174                                 Job_Touch(gn, gn->type & OP_SILENT);
3175                         }
3176                 } else {
3177                         gn->made = ERROR;
3178                 }
3179
3180                 if (gn->made != ERROR) {
3181                         /*
3182                          * If the node was made successfully, mark it so, update
3183                          * its modification time and timestamp all its parents.
3184                          * Note that for .ZEROTIME targets, the timestamping
3185                          * isn't done. This is to keep its state from affecting
3186                          * that of its parent.
3187                          */
3188                         gn->made = MADE;
3189 #ifndef RECHECK
3190                         /*
3191                          * We can't re-stat the thing, but we can at least take
3192                          * care of rules where a target depends on a source that
3193                          * actually creates the target, but only if it has
3194                          * changed, e.g.
3195                          *
3196                          * parse.h : parse.o
3197                          *
3198                          * parse.o : parse.y
3199                          *      yacc -d parse.y
3200                          *      cc -c y.tab.c
3201                          *      mv y.tab.o parse.o
3202                          *      cmp -s y.tab.h parse.h || mv y.tab.h parse.h
3203                          *
3204                          * In this case, if the definitions produced by yacc
3205                          * haven't changed from before, parse.h won't have been
3206                          * updated and gn->mtime will reflect the current
3207                          * modification time for parse.h. This is something of a
3208                          * kludge, I admit, but it's a useful one..
3209                          *
3210                          * XXX: People like to use a rule like
3211                          *
3212                          * FRC:
3213                          *
3214                          * To force things that depend on FRC to be made, so we
3215                          * have to check for gn->children being empty as well...
3216                          */
3217                         if (!Lst_IsEmpty(&gn->commands) ||
3218                             Lst_IsEmpty(&gn->children)) {
3219                                 gn->mtime = now;
3220                         }
3221 #else
3222                         /*
3223                          * This is what Make does and it's actually a good
3224                          * thing, as it allows rules like
3225                          *
3226                          *      cmp -s y.tab.h parse.h || cp y.tab.h parse.h
3227                          *
3228                          * to function as intended. Unfortunately, thanks to
3229                          * the stateless nature of NFS (and the speed of this
3230                          * program), there are times when the modification time
3231                          * of a file created on a remote machine will not be
3232                          * modified before the stat() implied by the Dir_MTime
3233                          * occurs, thus leading us to believe that the file
3234                          * is unchanged, wreaking havoc with files that depend
3235                          * on this one.
3236                          *
3237                          * I have decided it is better to make too much than to
3238                          * make too little, so this stuff is commented out
3239                          * unless you're sure it's ok.
3240                          * -- ardeb 1/12/88
3241                          */
3242                         if (noExecute || Dir_MTime(gn) == 0) {
3243                                 gn->mtime = now;
3244                         }
3245                         if (gn->cmtime > gn->mtime)
3246                                 gn->mtime = gn->cmtime;
3247                         DEBUGF(MAKE, ("update time: %s\n",
3248                             Targ_FmtTime(gn->mtime)));
3249 #endif
3250                         if (!(gn->type & OP_EXEC)) {
3251                                 pgn->childMade = TRUE;
3252                                 Make_TimeStamp(pgn, gn);
3253                         }
3254
3255                 } else if (keepgoing) {
3256                         pgn->make = FALSE;
3257
3258                 } else {
3259                         printf("\n\nStop in %s.\n", Var_Value(".CURDIR", gn));
3260                         exit(1);
3261                 }
3262         } else if (gn->made == ERROR) {
3263                 /*
3264                  * Already had an error when making this beastie. Tell the
3265                  * parent to abort.
3266                  */
3267                 pgn->make = FALSE;
3268         } else {
3269                 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3270                         Var_Set(IMPSRC, Var_Value(TARGET, gn), pgn);
3271                 }
3272                 switch(gn->made) {
3273                   case BEINGMADE:
3274                         Error("Graph cycles through %s\n", gn->name);
3275                         gn->made = ERROR;
3276                         pgn->make = FALSE;
3277                         break;
3278                   case MADE:
3279                         if ((gn->type & OP_EXEC) == 0) {
3280                             pgn->childMade = TRUE;
3281                             Make_TimeStamp(pgn, gn);
3282                         }
3283                         break;
3284                   case UPTODATE:
3285                         if ((gn->type & OP_EXEC) == 0) {
3286                             Make_TimeStamp(pgn, gn);
3287                         }
3288                         break;
3289                   default:
3290                         break;
3291                 }
3292         }
3293
3294         return (0);
3295 }
3296
3297 /*-
3298  * Install signal handlers for Compat_Run
3299  */
3300 void
3301 Compat_InstallSignalHandlers(void)
3302 {
3303
3304         if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
3305                 signal(SIGINT, CompatCatchSig);
3306         }
3307         if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
3308                 signal(SIGTERM, CompatCatchSig);
3309         }
3310         if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
3311                 signal(SIGHUP, CompatCatchSig);
3312         }
3313         if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
3314                 signal(SIGQUIT, CompatCatchSig);
3315         }
3316 }
3317
3318 /*-
3319  *-----------------------------------------------------------------------
3320  * Compat_Run --
3321  *      Start making again, given a list of target nodes.
3322  *
3323  * Results:
3324  *      None.
3325  *
3326  * Side Effects:
3327  *      Guess what?
3328  *
3329  *-----------------------------------------------------------------------
3330  */
3331 void
3332 Compat_Run(Lst *targs)
3333 {
3334         GNode   *gn = NULL;     /* Current root target */
3335         LstNode *ln;
3336
3337         Compat_InstallSignalHandlers();
3338         ENDNode = Targ_FindNode(".END", TARG_CREATE);
3339         /*
3340          * If the user has defined a .BEGIN target, execute the commands
3341          * attached to it.
3342         */
3343         if (!queryFlag) {
3344                 gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
3345                 if (gn != NULL) {
3346                         LST_FOREACH(ln, &gn->commands) {
3347                                 if (Compat_RunCommand(Lst_Datum(ln), gn))
3348                                         break;
3349                         }
3350                         if (gn->made == ERROR) {
3351                                 printf("\n\nStop.\n");
3352                                 exit(1);
3353                         }
3354                 }
3355         }
3356
3357         /*
3358          * For each entry in the list of targets to create, call Compat_Make on
3359          * it to create the thing. Compat_Make will leave the 'made' field of gn
3360          * in one of several states:
3361          *      UPTODATE  gn was already up-to-date
3362          *      MADE      gn was recreated successfully
3363          *      ERROR     An error occurred while gn was being created
3364          *      ABORTED   gn was not remade because one of its inferiors
3365          *                could not be made due to errors.
3366          */
3367         makeErrors = 0;
3368         while (!Lst_IsEmpty(targs)) {
3369                 gn = Lst_DeQueue(targs);
3370                 Compat_Make(gn, gn);
3371
3372                 if (gn->made == UPTODATE) {
3373                         printf("`%s' is up to date.\n", gn->name);
3374                 } else if (gn->made == ABORTED) {
3375                         printf("`%s' not remade because of errors.\n",
3376                             gn->name);
3377                         makeErrors++;
3378                 }
3379         }
3380
3381         /*
3382          * If the user has defined a .END target, run its commands.
3383          */
3384         if (makeErrors == 0) {
3385                 LST_FOREACH(ln, &ENDNode->commands) {
3386                         if (Compat_RunCommand(Lst_Datum(ln), ENDNode))
3387                                 break;
3388                 }
3389         }
3390 }