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