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