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