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