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