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