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