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