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