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