Use __arysize() to cal size of array.
[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.17.2.2 2001/02/13 03:13:57 will Exp $
41  * $DragonFly: src/usr.bin/make/job.c,v 1.29 2004/12/16 21:38:04 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       Check for and handle the termination of any
56  *                              children. This must be called reasonably
57  *                              frequently to keep the whole make going at
58  *                              a decent clip, since job table entries aren't
59  *                              removed until their process is caught this way.
60  *                              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.
64  *                              Should also be called fairly frequently to
65  *                              keep the user informed of what's going on.
66  *                              If no output is waiting, it will block for
67  *                              a time given by the SEL_* constants, below,
68  *                              or until output is ready.
69  *
70  *      Job_Init                Called to intialize this module. in addition,
71  *                              any commands attached to the .BEGIN target
72  *                              are executed before this function returns.
73  *                              Hence, the makefile must have been parsed
74  *                              before this function is called.
75  *
76  *      Job_Full                Return TRUE if the job table is filled.
77  *
78  *      Job_Empty               Return TRUE if the job table is completely
79  *                              empty.
80  *
81  *      Job_ParseShell          Given the line following a .SHELL target, parse
82  *                              the line as a shell specification. Returns
83  *                              FAILURE if the spec was incorrect.
84  *
85  *      Job_Finish                      Perform any final processing which needs doing.
86  *                              This includes the execution of any commands
87  *                              which have been/were attached to the .END
88  *                              target. It should only be called when the
89  *                              job table is empty.
90  *
91  *      Job_AbortAll            Abort all currently running jobs. It doesn't
92  *                              handle output or do anything for the jobs,
93  *                              just kills them. It should only be called in
94  *                              an emergency, as it were.
95  *
96  *      Job_CheckCommands       Verify that the commands for a target are
97  *                              ok. Provide them if necessary and possible.
98  *
99  *      Job_Touch               Update a target without really updating it.
100  *
101  *      Job_Wait                Wait for all currently-running jobs to finish.
102  */
103
104 #include <sys/types.h>
105 #include <sys/stat.h>
106 #include <sys/file.h>
107 #include <sys/time.h>
108 #ifdef USE_KQUEUE
109 #include <sys/event.h>
110 #endif
111 #include <sys/wait.h>
112 #include <err.h>
113 #include <errno.h>
114 #include <fcntl.h>
115 #include <stdio.h>
116 #include <string.h>
117 #include <signal.h>
118 #include <unistd.h>
119 #include <utime.h>
120 #include "make.h"
121 #include "hash.h"
122 #include "dir.h"
123 #include "job.h"
124 #include "pathnames.h"
125
126 #define STATIC static
127
128 /*
129  * error handling variables
130  */
131 static int      errors = 0;         /* number of errors reported */
132 static int      aborting = 0;       /* why is the make aborting? */
133 #define ABORT_ERROR     1           /* Because of an error */
134 #define ABORT_INTERRUPT 2           /* Because it was interrupted */
135 #define ABORT_WAIT      3           /* Waiting for jobs to finish */
136
137 /*
138  * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
139  * is a char! So when we go above 127 we turn negative!
140  */
141 #define FILENO(a) ((unsigned)fileno(a))
142
143 /*
144  * post-make command processing. The node postCommands is really just the
145  * .END target but we keep it around to avoid having to search for it
146  * all the time.
147  */
148 static GNode      *postCommands;    /* node containing commands to execute when
149                                      * everything else is done */
150 static int        numCommands;      /* The number of commands actually printed
151                                      * for a target. Should this number be
152                                      * 0, no shell will be executed. */
153
154 /*
155  * Return values from JobStart.
156  */
157 #define JOB_RUNNING     0       /* Job is running */
158 #define JOB_ERROR       1       /* Error in starting the job */
159 #define JOB_FINISHED    2       /* The job is already finished */
160 #define JOB_STOPPED     3       /* The job is stopped */
161
162 /*
163  * tfile is used to build temp file names to store shell commands to
164  * execute.
165  */
166 static char     tfile[sizeof(TMPPAT)];
167
168 /*
169  * Descriptions for various shells.
170  */
171 static const DEF_SHELL_STRUCT(CShell, const) shells[] = {
172     /*
173      * CSH description. The csh can do echo control by playing
174      * with the setting of the 'echo' shell variable. Sadly,
175      * however, it is unable to do error control nicely.
176      */
177 {
178     "csh",
179     TRUE, "unset verbose", "set verbose", "unset verbose", 13,
180     FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"",
181     "v", "e",
182 },
183     /*
184      * SH description. Echo control is also possible and, under
185      * sun UNIX anyway, one can even control error checking.
186      */
187 {
188     "sh",
189     TRUE, "set -", "set -v", "set -", 5,
190     TRUE, "set -e", "set +e",
191 #ifdef OLDBOURNESHELL
192     FALSE, "echo \"%s\"\n", "sh -c '%s || exit 0'\n",
193 #endif
194     "v", "e",
195 },
196     /*
197      * KSH description. The Korn shell has a superset of
198      * the Bourne shell's functionality.
199      */
200 {
201     "ksh",
202     TRUE, "set -", "set -v", "set -", 5,
203     TRUE, "set -e", "set +e",
204     "v", "e",
205 },
206 };
207 static Shell    *commandShell = NULL;   /* this is the shell to which we pass
208                                          * all commands in the Makefile. It is
209                                          * set by the Job_ParseShell function */
210 char            *shellPath = NULL,      /* full pathname of executable image */
211                 *shellName = NULL;      /* last component of shell */
212
213
214 static int      maxJobs;        /* The most children we can run at once */
215 STATIC int      nJobs;          /* The number of children currently running */
216 STATIC Lst      jobs;           /* The structures that describe them */
217 STATIC Boolean  jobFull;        /* Flag to tell when the job table is full. It
218                                  * is set TRUE when (1) the total number of
219                                  * running jobs equals the maximum allowed */
220 #ifdef USE_KQUEUE
221 static int      kqfd;           /* File descriptor obtained by kqueue() */
222 #else
223 static fd_set   outputs;        /* Set of descriptors of pipes connected to
224                                  * the output channels of children */
225 #endif
226
227 STATIC GNode    *lastNode;      /* The node for which output was most recently
228                                  * produced. */
229 STATIC char     *targFmt;       /* Format string to use to head output from a
230                                  * job when it's not the most-recent job heard
231                                  * from */
232
233 #define TARG_FMT  "--- %s ---\n" /* Default format */
234 #define MESSAGE(fp, gn) \
235          fprintf(fp, targFmt, gn->name);
236
237 /*
238  * When JobStart attempts to run a job but isn't allowed to
239  * or when Job_CatchChildren detects a job that has
240  * been stopped somehow, the job is placed on the stoppedJobs queue to be run
241  * when the next job finishes.
242  */
243 STATIC Lst      stoppedJobs;    /* Lst of Job structures describing
244                                  * jobs that were stopped due to concurrency
245                                  * limits or externally */
246
247 STATIC int      fifoFd;         /* Fd of our job fifo */
248 STATIC char     fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
249 STATIC int      fifoMaster;
250
251 static sig_atomic_t interrupted;
252
253
254 #if defined(USE_PGRP) && defined(SYSV)
255 # define KILL(pid, sig)         killpg(-(pid), (sig))
256 #else
257 # if defined(USE_PGRP)
258 #  define KILL(pid, sig)        killpg((pid), (sig))
259 # else
260 #  define KILL(pid, sig)        kill((pid), (sig))
261 # endif
262 #endif
263
264 /*
265  * Grmpf... There is no way to set bits of the wait structure
266  * anymore with the stupid W*() macros. I liked the union wait
267  * stuff much more. So, we devise our own macros... This is
268  * really ugly, use dramamine sparingly. You have been warned.
269  */
270 #define W_SETMASKED(st, val, fun)                               \
271         {                                                       \
272                 int sh = (int)~0;                               \
273                 int mask = fun(sh);                             \
274                                                                 \
275                 for (sh = 0; ((mask >> sh) & 1) == 0; sh++)     \
276                         continue;                               \
277                 *(st) = (*(st) & ~mask) | ((val) << sh);        \
278         }
279
280 #define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
281 #define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
282
283
284 static int JobCondPassSig(void *, void *);
285 static void JobPassSig(int);
286 static int JobCmpPid(void *, void *);
287 static int JobPrintCommand(void *, void *);
288 static int JobSaveCommand(void *, void *);
289 static void JobClose(Job *);
290 static void JobFinish(Job *, int *);
291 static void JobExec(Job *, char **);
292 static void JobMakeArgv(Job *, char **);
293 static void JobRestart(Job *);
294 static int JobStart(GNode *, int, Job *);
295 static char *JobOutput(Job *, char *, char *, int);
296 static void JobDoOutput(Job *, Boolean);
297 static Shell *JobMatchShell(const char *);
298 static void JobInterrupt(int, int);
299 static void JobRestartJobs(void);
300
301 /*
302  * JobCatchSignal
303  *
304  * Got a signal. Set global variables and hope that someone will
305  * handle it.
306  */
307 static void
308 JobCatchSig(int signo)
309 {
310
311         interrupted = signo;
312 }
313
314 /*-
315  *-----------------------------------------------------------------------
316  * JobCondPassSig --
317  *      Pass a signal to a job if USE_PGRP is defined.
318  *
319  * Results:
320  *      === 0
321  *
322  * Side Effects:
323  *      None, except the job may bite it.
324  *
325  *-----------------------------------------------------------------------
326  */
327 static int
328 JobCondPassSig(void *jobp, void *signop)
329 {
330     Job *job = jobp;
331     int signo = *(int *)signop;
332
333     DEBUGF(JOB, ("JobCondPassSig passing signal %d to child %d.\n",
334         signo, job->pid));
335     KILL(job->pid, signo);
336     return (0);
337 }
338
339 /*-
340  *-----------------------------------------------------------------------
341  * JobPassSig --
342  *      Pass a signal on to all local jobs if
343  *      USE_PGRP is defined, then die ourselves.
344  *
345  * Results:
346  *      None.
347  *
348  * Side Effects:
349  *      We die by the same signal.
350  *
351  *-----------------------------------------------------------------------
352  */
353 static void
354 JobPassSig(int signo)
355 {
356     sigset_t nmask, omask;
357     struct sigaction act;
358
359     sigemptyset(&nmask);
360     sigaddset(&nmask, signo);
361     sigprocmask(SIG_SETMASK, &nmask, &omask);
362
363     DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
364     Lst_ForEach(jobs, JobCondPassSig, &signo);
365
366     /*
367      * Deal with proper cleanup based on the signal received. We only run
368      * the .INTERRUPT target if the signal was in fact an interrupt. The other
369      * three termination signals are more of a "get out *now*" command.
370      */
371     if (signo == SIGINT) {
372         JobInterrupt(TRUE, signo);
373     } else if ((signo == SIGHUP) || (signo == SIGTERM) || (signo == SIGQUIT)) {
374         JobInterrupt(FALSE, signo);
375     }
376
377     /*
378      * Leave gracefully if SIGQUIT, rather than core dumping.
379      */
380     if (signo == SIGQUIT) {
381         signo = SIGINT;
382     }
383
384     /*
385      * Send ourselves the signal now we've given the message to everyone else.
386      * Note we block everything else possible while we're getting the signal.
387      * This ensures that all our jobs get continued when we wake up before
388      * we take any other signal.
389      * XXX this comment seems wrong.
390      */
391     act.sa_handler = SIG_DFL;
392     sigemptyset(&act.sa_mask);
393     act.sa_flags = 0;
394     sigaction(signo, &act, NULL);
395
396     DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
397         ~0 & ~(1 << (signo - 1))));
398     signal(signo, SIG_DFL);
399
400     KILL(getpid(), signo);
401
402     signo = SIGCONT;
403     Lst_ForEach(jobs, JobCondPassSig, &signo);
404
405     sigprocmask(SIG_SETMASK, &omask, NULL);
406     sigprocmask(SIG_SETMASK, &omask, NULL);
407     act.sa_handler = JobPassSig;
408     sigaction(signo, &act, NULL);
409 }
410
411 /*-
412  *-----------------------------------------------------------------------
413  * JobCmpPid  --
414  *      Compare the pid of the job with the given pid and return 0 if they
415  *      are equal. This function is called from Job_CatchChildren via
416  *      Lst_Find to find the job descriptor of the finished job.
417  *
418  * Results:
419  *      0 if the pid's match
420  *
421  * Side Effects:
422  *      None
423  *-----------------------------------------------------------------------
424  */
425 static int
426 JobCmpPid(void *job, void *pid)
427 {
428
429     return (*(int *)pid - ((Job *)job)->pid);
430 }
431
432 /*-
433  *-----------------------------------------------------------------------
434  * JobPrintCommand  --
435  *      Put out another command for the given job. If the command starts
436  *      with an @ or a - we process it specially. In the former case,
437  *      so long as the -s and -n flags weren't given to make, we stick
438  *      a shell-specific echoOff command in the script. In the latter,
439  *      we ignore errors for the entire job, unless the shell has error
440  *      control.
441  *      If the command is just "..." we take all future commands for this
442  *      job to be commands to be executed once the entire graph has been
443  *      made and return non-zero to signal that the end of the commands
444  *      was reached. These commands are later attached to the postCommands
445  *      node and executed by Job_Finish when all things are done.
446  *      This function is called from JobStart via Lst_ForEach.
447  *
448  * Results:
449  *      Always 0, unless the command was "..."
450  *
451  * Side Effects:
452  *      If the command begins with a '-' and the shell has no error control,
453  *      the JOB_IGNERR flag is set in the job descriptor.
454  *      If the command is "..." and we're not ignoring such things,
455  *      tailCmds is set to the successor node of the cmd.
456  *      numCommands is incremented if the command is actually printed.
457  *-----------------------------------------------------------------------
458  */
459 static int
460 JobPrintCommand(void *cmdp, void *jobp)
461 {
462     Boolean       noSpecials;       /* true if we shouldn't worry about
463                                      * inserting special commands into
464                                      * the input stream. */
465     Boolean       shutUp = FALSE;   /* true if we put a no echo command
466                                      * into the command file */
467     Boolean       errOff = FALSE;   /* true if we turned error checking
468                                      * off before printing the command
469                                      * and need to turn it back on */
470     char          *cmdTemplate;     /* Template to use when printing the
471                                      * command */
472     char          *cmdStart;        /* Start of expanded command */
473     LstNode       cmdNode;          /* Node for replacing the command */
474     char          *cmd = cmdp;
475     Job           *job = jobp;
476
477     noSpecials = (noExecute && !(job->node->type & OP_MAKE));
478
479     if (strcmp(cmd, "...") == 0) {
480         job->node->type |= OP_SAVE_CMDS;
481         if ((job->flags & JOB_IGNDOTS) == 0) {
482             job->tailCmds = Lst_Succ(Lst_Member(job->node->commands, cmd));
483             return (1);
484         }
485         return (0);
486     }
487
488 #define DBPRINTF(fmt, arg)                      \
489    DEBUGF(JOB, (fmt, arg));                     \
490     fprintf(job->cmdFILE, fmt, arg);    \
491     fflush(job->cmdFILE);
492
493     numCommands += 1;
494
495     /*
496      * For debugging, we replace each command with the result of expanding
497      * the variables in the command.
498      */
499     cmdNode = Lst_Member(job->node->commands, cmd);
500     cmdStart = cmd = Var_Subst(NULL, cmd, job->node, FALSE);
501     Lst_Replace(cmdNode, cmdStart);
502
503     cmdTemplate = "%s\n";
504
505     /*
506      * Check for leading @', -' or +'s to control echoing, error checking,
507      * and execution on -n.
508      */
509     while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
510         switch (*cmd) {
511
512           case '@':
513             shutUp = DEBUG(LOUD) ? FALSE : TRUE;
514             break;
515
516           case '-':
517             errOff = TRUE;
518             break;
519
520           case '+':
521             if (noSpecials) {
522                 /*
523                  * We're not actually exececuting anything...
524                  * but this one needs to be - use compat mode just for it.
525                  */
526                 Compat_RunCommand(cmdp, job->node);
527                 return (0);
528             }
529             break;
530         }
531         cmd++;
532     }
533
534     while (isspace((unsigned char)*cmd))
535         cmd++;
536
537     if (shutUp) {
538         if (!(job->flags & JOB_SILENT) && !noSpecials &&
539             commandShell->hasEchoCtl) {
540                 DBPRINTF("%s\n", commandShell->echoOff);
541         } else {
542             shutUp = FALSE;
543         }
544     }
545
546     if (errOff) {
547         if ( !(job->flags & JOB_IGNERR) && !noSpecials) {
548             if (commandShell->hasErrCtl) {
549                 /*
550                  * we don't want the error-control commands showing
551                  * up either, so we turn off echoing while executing
552                  * them. We could put another field in the shell
553                  * structure to tell JobDoOutput to look for this
554                  * string too, but why make it any more complex than
555                  * it already is?
556                  */
557                 if (!(job->flags & JOB_SILENT) && !shutUp &&
558                     commandShell->hasEchoCtl) {
559                         DBPRINTF("%s\n", commandShell->echoOff);
560                         DBPRINTF("%s\n", commandShell->ignErr);
561                         DBPRINTF("%s\n", commandShell->echoOn);
562                 } else {
563                     DBPRINTF("%s\n", commandShell->ignErr);
564                 }
565             } else if (commandShell->ignErr &&
566                       (*commandShell->ignErr != '\0'))
567             {
568                 /*
569                  * The shell has no error control, so we need to be
570                  * weird to get it to ignore any errors from the command.
571                  * If echoing is turned on, we turn it off and use the
572                  * errCheck template to echo the command. Leave echoing
573                  * off so the user doesn't see the weirdness we go through
574                  * to ignore errors. Set cmdTemplate to use the weirdness
575                  * instead of the simple "%s\n" template.
576                  */
577                 if (!(job->flags & JOB_SILENT) && !shutUp &&
578                     commandShell->hasEchoCtl) {
579                         DBPRINTF("%s\n", commandShell->echoOff);
580                         DBPRINTF(commandShell->errCheck, cmd);
581                         shutUp = TRUE;
582                 }
583                 cmdTemplate = commandShell->ignErr;
584                 /*
585                  * The error ignoration (hee hee) is already taken care
586                  * of by the ignErr template, so pretend error checking
587                  * is still on.
588                  */
589                 errOff = FALSE;
590             } else {
591                 errOff = FALSE;
592             }
593         } else {
594             errOff = FALSE;
595         }
596     }
597
598     DBPRINTF(cmdTemplate, cmd);
599
600     if (errOff) {
601         /*
602          * If echoing is already off, there's no point in issuing the
603          * echoOff command. Otherwise we issue it and pretend it was on
604          * for the whole command...
605          */
606         if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl) {
607             DBPRINTF("%s\n", commandShell->echoOff);
608             shutUp = TRUE;
609         }
610         DBPRINTF("%s\n", commandShell->errCheck);
611     }
612     if (shutUp) {
613         DBPRINTF("%s\n", commandShell->echoOn);
614     }
615     return (0);
616 }
617
618 /*-
619  *-----------------------------------------------------------------------
620  * JobSaveCommand --
621  *      Save a command to be executed when everything else is done.
622  *      Callback function for JobFinish...
623  *
624  * Results:
625  *      Always returns 0
626  *
627  * Side Effects:
628  *      The command is tacked onto the end of postCommands's commands list.
629  *
630  *-----------------------------------------------------------------------
631  */
632 static int
633 JobSaveCommand(void *cmd, void *gn)
634 {
635
636     cmd = Var_Subst(NULL, cmd, gn, FALSE);
637     Lst_AtEnd(postCommands->commands, cmd);
638     return (0);
639 }
640
641
642 /*-
643  *-----------------------------------------------------------------------
644  * JobClose --
645  *      Called to close both input and output pipes when a job is finished.
646  *
647  * Results:
648  *      Nada
649  *
650  * Side Effects:
651  *      The file descriptors associated with the job are closed.
652  *
653  *-----------------------------------------------------------------------
654  */
655 static void
656 JobClose(Job *job)
657 {
658
659     if (usePipes) {
660 #if !defined(USE_KQUEUE)
661         FD_CLR(job->inPipe, &outputs);
662 #endif
663         if (job->outPipe != job->inPipe) {
664            close(job->outPipe);
665         }
666         JobDoOutput(job, TRUE);
667         close(job->inPipe);
668     } else {
669         close(job->outFd);
670         JobDoOutput(job, TRUE);
671     }
672 }
673
674 /*-
675  *-----------------------------------------------------------------------
676  * JobFinish  --
677  *      Do final processing for the given job including updating
678  *      parents and starting new jobs as available/necessary. Note
679  *      that we pay no attention to the JOB_IGNERR flag here.
680  *      This is because when we're called because of a noexecute flag
681  *      or something, jstat.w_status is 0 and when called from
682  *      Job_CatchChildren, the status is zeroed if it s/b ignored.
683  *
684  * Results:
685  *      None
686  *
687  * Side Effects:
688  *      Some nodes may be put on the toBeMade queue.
689  *      Final commands for the job are placed on postCommands.
690  *
691  *      If we got an error and are aborting (aborting == ABORT_ERROR) and
692  *      the job list is now empty, we are done for the day.
693  *      If we recognized an error (errors !=0), we set the aborting flag
694  *      to ABORT_ERROR so no more jobs will be started.
695  *-----------------------------------------------------------------------
696  */
697 /*ARGSUSED*/
698 static void
699 JobFinish(Job *job, int *status)
700 {
701     Boolean      done;
702
703     if ((WIFEXITED(*status) &&
704          (((WEXITSTATUS(*status) != 0) && !(job->flags & JOB_IGNERR)))) ||
705         (WIFSIGNALED(*status) && (WTERMSIG(*status) != SIGCONT)))
706     {
707         /*
708          * If it exited non-zero and either we're doing things our
709          * way or we're not ignoring errors, the job is finished.
710          * Similarly, if the shell died because of a signal
711          * the job is also finished. In these
712          * cases, finish out the job's output before printing the exit
713          * status...
714          */
715         JobClose(job);
716         if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
717             fclose(job->cmdFILE);
718         }
719         done = TRUE;
720     } else if (WIFEXITED(*status)) {
721         /*
722          * Deal with ignored errors in -B mode. We need to print a message
723          * telling of the ignored error as well as setting status.w_status
724          * to 0 so the next command gets run. To do this, we set done to be
725          * TRUE if in -B mode and the job exited non-zero.
726          */
727         done = WEXITSTATUS(*status) != 0;
728         /*
729          * Old comment said: "Note we don't
730          * want to close down any of the streams until we know we're at the
731          * end."
732          * But we do. Otherwise when are we going to print the rest of the
733          * stuff?
734          */
735         JobClose(job);
736     } else {
737         /*
738          * No need to close things down or anything.
739          */
740         done = FALSE;
741     }
742
743     if (done ||
744         WIFSTOPPED(*status) ||
745         (WIFSIGNALED(*status) && (WTERMSIG(*status) == SIGCONT)) ||
746         DEBUG(JOB))
747     {
748         FILE      *out;
749
750         if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
751             /*
752              * If output is going to a file and this job is ignoring
753              * errors, arrange to have the exit status sent to the
754              * output file as well.
755              */
756             out = fdopen(job->outFd, "w");
757             if (out == NULL)
758                 Punt("Cannot fdopen");
759         } else {
760             out = stdout;
761         }
762
763         if (WIFEXITED(*status)) {
764             DEBUGF(JOB, ("Process %d exited.\n", job->pid));
765             if (WEXITSTATUS(*status) != 0) {
766                 if (usePipes && job->node != lastNode) {
767                     MESSAGE(out, job->node);
768                     lastNode = job->node;
769                 }
770                  fprintf(out, "*** Error code %d%s\n",
771                                WEXITSTATUS(*status),
772                                (job->flags & JOB_IGNERR) ? "(ignored)" : "");
773
774                 if (job->flags & JOB_IGNERR) {
775                     *status = 0;
776                 }
777             } else if (DEBUG(JOB)) {
778                 if (usePipes && job->node != lastNode) {
779                     MESSAGE(out, job->node);
780                     lastNode = job->node;
781                 }
782                 fprintf(out, "*** Completed successfully\n");
783             }
784         } else if (WIFSTOPPED(*status)) {
785             DEBUGF(JOB, ("Process %d stopped.\n", job->pid));
786             if (usePipes && job->node != lastNode) {
787                 MESSAGE(out, job->node);
788                 lastNode = job->node;
789             }
790             fprintf(out, "*** Stopped -- signal %d\n",
791                 WSTOPSIG(*status));
792             job->flags |= JOB_RESUME;
793             Lst_AtEnd(stoppedJobs, job);
794             fflush(out);
795             return;
796         } else if (WTERMSIG(*status) == SIGCONT) {
797             /*
798              * If the beastie has continued, shift the Job from the stopped
799              * list to the running one (or re-stop it if concurrency is
800              * exceeded) and go and get another child.
801              */
802             if (job->flags & (JOB_RESUME|JOB_RESTART)) {
803                 if (usePipes && job->node != lastNode) {
804                     MESSAGE(out, job->node);
805                     lastNode = job->node;
806                 }
807                  fprintf(out, "*** Continued\n");
808             }
809             if (!(job->flags & JOB_CONTINUING)) {
810                 DEBUGF(JOB, ("Warning: process %d was not continuing.\n", job->pid));
811 #ifdef notdef
812                 /*
813                  * We don't really want to restart a job from scratch just
814                  * because it continued, especially not without killing the
815                  * continuing process!  That's why this is ifdef'ed out.
816                  * FD - 9/17/90
817                  */
818                 JobRestart(job);
819 #endif
820             }
821             job->flags &= ~JOB_CONTINUING;
822             Lst_AtEnd(jobs, job);
823             nJobs += 1;
824             DEBUGF(JOB, ("Process %d is continuing locally.\n", job->pid));
825             if (nJobs == maxJobs) {
826                 jobFull = TRUE;
827                 DEBUGF(JOB, ("Job queue is full.\n"));
828             }
829             fflush(out);
830             return;
831         } else {
832             if (usePipes && job->node != lastNode) {
833                 MESSAGE(out, job->node);
834                 lastNode = job->node;
835             }
836             fprintf(out, "*** Signal %d\n", WTERMSIG(*status));
837         }
838
839         fflush(out);
840     }
841
842     /*
843      * Now handle the -B-mode stuff. If the beast still isn't finished,
844      * try and restart the job on the next command. If JobStart says it's
845      * ok, it's ok. If there's an error, this puppy is done.
846      */
847     if (compatMake && (WIFEXITED(*status) &&
848         !Lst_IsAtEnd(job->node->commands))) {
849         switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
850         case JOB_RUNNING:
851             done = FALSE;
852             break;
853         case JOB_ERROR:
854             done = TRUE;
855             W_SETEXITSTATUS(status, 1);
856             break;
857         case JOB_FINISHED:
858             /*
859              * If we got back a JOB_FINISHED code, JobStart has already
860              * called Make_Update and freed the job descriptor. We set
861              * done to false here to avoid fake cycles and double frees.
862              * JobStart needs to do the update so we can proceed up the
863              * graph when given the -n flag..
864              */
865             done = FALSE;
866             break;
867         default:
868             break;
869         }
870     } else {
871         done = TRUE;
872     }
873
874
875     if (done &&
876         (aborting != ABORT_ERROR) &&
877         (aborting != ABORT_INTERRUPT) &&
878         (*status == 0))
879     {
880         /*
881          * As long as we aren't aborting and the job didn't return a non-zero
882          * status that we shouldn't ignore, we call Make_Update to update
883          * the parents. In addition, any saved commands for the node are placed
884          * on the .END target.
885          */
886         if (job->tailCmds != NULL) {
887             Lst_ForEachFrom(job->node->commands, job->tailCmds,
888                 JobSaveCommand, job->node);
889         }
890         job->node->made = MADE;
891         Make_Update(job->node);
892         free(job);
893     } else if (*status != 0) {
894         errors += 1;
895         free(job);
896     }
897
898     JobRestartJobs();
899
900     /*
901      * Set aborting if any error.
902      */
903     if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
904         /*
905          * If we found any errors in this batch of children and the -k flag
906          * wasn't given, we set the aborting flag so no more jobs get
907          * started.
908          */
909         aborting = ABORT_ERROR;
910     }
911
912     if ((aborting == ABORT_ERROR) && Job_Empty())
913         /*
914          * If we are aborting and the job table is now empty, we finish.
915          */
916         Finish(errors);
917 }
918
919 /*-
920  *-----------------------------------------------------------------------
921  * Job_Touch --
922  *      Touch the given target. Called by JobStart when the -t flag was
923  *      given.  Prints messages unless told to be silent.
924  *
925  * Results:
926  *      None
927  *
928  * Side Effects:
929  *      The data modification of the file is changed. In addition, if the
930  *      file did not exist, it is created.
931  *-----------------------------------------------------------------------
932  */
933 void
934 Job_Touch(GNode *gn, Boolean silent)
935 {
936     int           streamID;     /* ID of stream opened to do the touch */
937     struct utimbuf times;       /* Times for utime() call */
938
939     if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
940         /*
941          * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets
942          * and, as such, shouldn't really be created.
943          */
944         return;
945     }
946
947     if (!silent) {
948          fprintf(stdout, "touch %s\n", gn->name);
949          fflush(stdout);
950     }
951
952     if (noExecute) {
953         return;
954     }
955
956     if (gn->type & OP_ARCHV) {
957         Arch_Touch(gn);
958     } else if (gn->type & OP_LIB) {
959         Arch_TouchLib(gn);
960     } else {
961         char    *file = gn->path ? gn->path : gn->name;
962
963         times.actime = times.modtime = now;
964         if (utime(file, &times) < 0){
965             streamID = open(file, O_RDWR | O_CREAT, 0666);
966
967             if (streamID >= 0) {
968                 char    c;
969
970                 /*
971                  * Read and write a byte to the file to change the
972                  * modification time, then close the file.
973                  */
974                 if (read(streamID, &c, 1) == 1) {
975                      lseek(streamID, (off_t)0, SEEK_SET);
976                     write(streamID, &c, 1);
977                 }
978
979                 close(streamID);
980             } else {
981                  fprintf(stdout, "*** couldn't touch %s: %s",
982                                file, strerror(errno));
983                  fflush(stdout);
984             }
985         }
986     }
987 }
988
989 /*-
990  *-----------------------------------------------------------------------
991  * Job_CheckCommands --
992  *      Make sure the given node has all the commands it needs.
993  *
994  * Results:
995  *      TRUE if the commands list is/was ok.
996  *
997  * Side Effects:
998  *      The node will have commands from the .DEFAULT rule added to it
999  *      if it needs them.
1000  *-----------------------------------------------------------------------
1001  */
1002 Boolean
1003 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1004 {
1005
1006     if (OP_NOP(gn->type) && Lst_IsEmpty(gn->commands) &&
1007         (gn->type & OP_LIB) == 0) {
1008         /*
1009          * No commands. Look for .DEFAULT rule from which we might infer
1010          * commands
1011          */
1012         if ((DEFAULT != NULL) && !Lst_IsEmpty(DEFAULT->commands)) {
1013             char *p1;
1014             /*
1015              * Make only looks for a .DEFAULT if the node was never the
1016              * target of an operator, so that's what we do too. If
1017              * a .DEFAULT was given, we substitute its commands for gn's
1018              * commands and set the IMPSRC variable to be the target's name
1019              * The DEFAULT node acts like a transformation rule, in that
1020              * gn also inherits any attributes or sources attached to
1021              * .DEFAULT itself.
1022              */
1023             Make_HandleUse(DEFAULT, gn);
1024             Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn);
1025             free(p1);
1026         } else if (Dir_MTime(gn) == 0) {
1027             /*
1028              * The node wasn't the target of an operator we have no .DEFAULT
1029              * rule to go on and the target doesn't already exist. There's
1030              * nothing more we can do for this branch. If the -k flag wasn't
1031              * given, we stop in our tracks, otherwise we just don't update
1032              * this node's parents so they never get examined.
1033              */
1034             static const char msg[] = "make: don't know how to make";
1035
1036             if (gn->type & OP_OPTIONAL) {
1037                  fprintf(stdout, "%s %s(ignored)\n", msg, gn->name);
1038                  fflush(stdout);
1039             } else if (keepgoing) {
1040                  fprintf(stdout, "%s %s(continuing)\n", msg, gn->name);
1041                  fflush(stdout);
1042                  return (FALSE);
1043             } else {
1044 #if OLD_JOKE
1045                 if (strcmp(gn->name,"love") == 0)
1046                     (*abortProc)("Not war.");
1047                 else
1048 #endif
1049                     (*abortProc)("%s %s. Stop", msg, gn->name);
1050                 return (FALSE);
1051             }
1052         }
1053     }
1054     return (TRUE);
1055 }
1056
1057 /*-
1058  *-----------------------------------------------------------------------
1059  * JobExec --
1060  *      Execute the shell for the given job. Called from JobStart and
1061  *      JobRestart.
1062  *
1063  * Results:
1064  *      None.
1065  *
1066  * Side Effects:
1067  *      A shell is executed, outputs is altered and the Job structure added
1068  *      to the job table.
1069  *
1070  *-----------------------------------------------------------------------
1071  */
1072 static void
1073 JobExec(Job *job, char **argv)
1074 {
1075     int           cpid;         /* ID of new child */
1076
1077     if (DEBUG(JOB)) {
1078         int       i;
1079
1080         DEBUGF(JOB, ("Running %s\n", job->node->name));
1081         DEBUGF(JOB, ("\tCommand: "));
1082         for (i = 0; argv[i] != NULL; i++) {
1083             DEBUGF(JOB, ("%s ", argv[i]));
1084         }
1085         DEBUGF(JOB, ("\n"));
1086     }
1087
1088     /*
1089      * Some jobs produce no output and it's disconcerting to have
1090      * no feedback of their running (since they produce no output, the
1091      * banner with their name in it never appears). This is an attempt to
1092      * provide that feedback, even if nothing follows it.
1093      */
1094     if ((lastNode != job->node) && (job->flags & JOB_FIRST) &&
1095         !(job->flags & JOB_SILENT)) {
1096         MESSAGE(stdout, job->node);
1097         lastNode = job->node;
1098     }
1099
1100     if ((cpid = vfork()) == -1) {
1101         Punt("Cannot fork");
1102     } else if (cpid == 0) {
1103
1104         if (fifoFd >= 0)
1105             close(fifoFd);
1106         /*
1107          * Must duplicate the input stream down to the child's input and
1108          * reset it to the beginning (again). Since the stream was marked
1109          * close-on-exec, we must clear that bit in the new input.
1110          */
1111         if (dup2(FILENO(job->cmdFILE), 0) == -1)
1112             Punt("Cannot dup2: %s", strerror(errno));
1113         fcntl(0, F_SETFD, 0);
1114         lseek(0, (off_t)0, SEEK_SET);
1115
1116         if (usePipes) {
1117             /*
1118              * Set up the child's output to be routed through the pipe
1119              * we've created for it.
1120              */
1121             if (dup2(job->outPipe, 1) == -1)
1122                 Punt("Cannot dup2: %s", strerror(errno));
1123         } else {
1124             /*
1125              * We're capturing output in a file, so we duplicate the
1126              * descriptor to the temporary file into the standard
1127              * output.
1128              */
1129             if (dup2(job->outFd, 1) == -1)
1130                 Punt("Cannot dup2: %s", strerror(errno));
1131         }
1132         /*
1133          * The output channels are marked close on exec. This bit was
1134          * duplicated by the dup2 (on some systems), so we have to clear
1135          * it before routing the shell's error output to the same place as
1136          * its standard output.
1137          */
1138         fcntl(1, F_SETFD, 0);
1139         if (dup2(1, 2) == -1)
1140             Punt("Cannot dup2: %s", strerror(errno));
1141
1142 #ifdef USE_PGRP
1143         /*
1144          * We want to switch the child into a different process family so
1145          * we can kill it and all its descendants in one fell swoop,
1146          * by killing its process family, but not commit suicide.
1147          */
1148 # if defined(SYSV)
1149         setsid();
1150 # else
1151         setpgid(0, getpid());
1152 # endif
1153 #endif /* USE_PGRP */
1154
1155         execv(shellPath, argv);
1156
1157         write(STDERR_FILENO, "Could not execute shell\n",
1158                      sizeof("Could not execute shell"));
1159         _exit(1);
1160     } else {
1161         job->pid = cpid;
1162
1163         if (usePipes && (job->flags & JOB_FIRST) ) {
1164             /*
1165              * The first time a job is run for a node, we set the current
1166              * position in the buffer to the beginning and mark another
1167              * stream to watch in the outputs mask
1168              */
1169 #ifdef USE_KQUEUE
1170             struct kevent       kev[2];
1171 #endif
1172             job->curPos = 0;
1173
1174 #if defined(USE_KQUEUE)
1175             EV_SET(&kev[0], job->inPipe, EVFILT_READ, EV_ADD, 0, 0, job);
1176             EV_SET(&kev[1], job->pid, EVFILT_PROC, EV_ADD | EV_ONESHOT,
1177                 NOTE_EXIT, 0, NULL);
1178             if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1179                 /* kevent() will fail if the job is already finished */
1180                 if (errno != EINTR && errno != EBADF && errno != ESRCH)
1181                     Punt("kevent: %s", strerror(errno));
1182             }
1183 #else
1184             FD_SET(job->inPipe, &outputs);
1185 #endif /* USE_KQUEUE */
1186         }
1187
1188         if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1189             fclose(job->cmdFILE);
1190             job->cmdFILE = NULL;
1191         }
1192     }
1193
1194     /*
1195      * Now the job is actually running, add it to the table.
1196      */
1197     nJobs += 1;
1198     Lst_AtEnd(jobs, job);
1199     if (nJobs == maxJobs) {
1200         jobFull = TRUE;
1201     }
1202 }
1203
1204 /*-
1205  *-----------------------------------------------------------------------
1206  * JobMakeArgv --
1207  *      Create the argv needed to execute the shell for a given job.
1208  *
1209  *
1210  * Results:
1211  *
1212  * Side Effects:
1213  *
1214  *-----------------------------------------------------------------------
1215  */
1216 static void
1217 JobMakeArgv(Job *job, char **argv)
1218 {
1219     int           argc;
1220     static char   args[10];     /* For merged arguments */
1221
1222     argv[0] = shellName;
1223     argc = 1;
1224
1225     if ((commandShell->exit && (*commandShell->exit != '-')) ||
1226         (commandShell->echo && (*commandShell->echo != '-')))
1227     {
1228         /*
1229          * At least one of the flags doesn't have a minus before it, so
1230          * merge them together. Have to do this because the *(&(@*#*&#$#
1231          * Bourne shell thinks its second argument is a file to source.
1232          * Grrrr. Note the ten-character limitation on the combined arguments.
1233          */
1234         sprintf(args, "-%s%s",
1235                       ((job->flags & JOB_IGNERR) ? "" :
1236                        (commandShell->exit ? commandShell->exit : "")),
1237                       ((job->flags & JOB_SILENT) ? "" :
1238                        (commandShell->echo ? commandShell->echo : "")));
1239
1240         if (args[1]) {
1241             argv[argc] = args;
1242             argc++;
1243         }
1244     } else {
1245         if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1246             argv[argc] = commandShell->exit;
1247             argc++;
1248         }
1249         if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1250             argv[argc] = commandShell->echo;
1251             argc++;
1252         }
1253     }
1254     argv[argc] = NULL;
1255 }
1256
1257 /*-
1258  *-----------------------------------------------------------------------
1259  * JobRestart --
1260  *      Restart a job that stopped for some reason.
1261  *
1262  * Results:
1263  *      None.
1264  *
1265  * Side Effects:
1266  *      jobFull will be set if the job couldn't be run.
1267  *
1268  *-----------------------------------------------------------------------
1269  */
1270 static void
1271 JobRestart(Job *job)
1272 {
1273
1274     if (job->flags & JOB_RESTART) {
1275         /*
1276          * Set up the control arguments to the shell. This is based on the
1277          * flags set earlier for this job. If the JOB_IGNERR flag is clear,
1278          * the 'exit' flag of the commandShell is used to cause it to exit
1279          * upon receiving an error. If the JOB_SILENT flag is clear, the
1280          * 'echo' flag of the commandShell is used to get it to start echoing
1281          * as soon as it starts processing commands.
1282          */
1283         char      *argv[4];
1284
1285         JobMakeArgv(job, argv);
1286
1287         DEBUGF(JOB, ("Restarting %s...", job->node->name));
1288         if (((nJobs >= maxJobs) && !(job->flags & JOB_SPECIAL))) {
1289             /*
1290              * Can't be exported and not allowed to run locally -- put it
1291              * back on the hold queue and mark the table full
1292              */
1293             DEBUGF(JOB, ("holding\n"));
1294             Lst_AtFront(stoppedJobs, (void *)job);
1295             jobFull = TRUE;
1296             DEBUGF(JOB, ("Job queue is full.\n"));
1297             return;
1298         } else {
1299             /*
1300              * Job may be run locally.
1301              */
1302             DEBUGF(JOB, ("running locally\n"));
1303         }
1304         JobExec(job, argv);
1305     } else {
1306         /*
1307          * The job has stopped and needs to be restarted. Why it stopped,
1308          * we don't know...
1309          */
1310         DEBUGF(JOB, ("Resuming %s...", job->node->name));
1311         if (((nJobs < maxJobs) ||
1312             ((job->flags & JOB_SPECIAL) &&
1313              (maxJobs == 0))) &&
1314            (nJobs != maxJobs))
1315         {
1316             /*
1317              * If we haven't reached the concurrency limit already (or the
1318              * job must be run and maxJobs is 0), it's ok to resume it.
1319              */
1320             Boolean error;
1321             int status;
1322
1323             error = (KILL(job->pid, SIGCONT) != 0);
1324
1325             if (!error) {
1326                 /*
1327                  * Make sure the user knows we've continued the beast and
1328                  * actually put the thing in the job table.
1329                  */
1330                 job->flags |= JOB_CONTINUING;
1331                 W_SETTERMSIG(&status, SIGCONT);
1332                 JobFinish(job, &status);
1333
1334                 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1335                 DEBUGF(JOB, ("done\n"));
1336             } else {
1337                 Error("couldn't resume %s: %s",
1338                     job->node->name, strerror(errno));
1339                 status = 0;
1340                 W_SETEXITSTATUS(&status, 1);
1341                 JobFinish(job, &status);
1342             }
1343         } else {
1344             /*
1345              * Job cannot be restarted. Mark the table as full and
1346              * place the job back on the list of stopped jobs.
1347              */
1348             DEBUGF(JOB, ("table full\n"));
1349             Lst_AtFront(stoppedJobs, (void *)job);
1350             jobFull = TRUE;
1351             DEBUGF(JOB, ("Job queue is full.\n"));
1352         }
1353     }
1354 }
1355
1356 /*-
1357  *-----------------------------------------------------------------------
1358  * JobStart  --
1359  *      Start a target-creation process going for the target described
1360  *      by the graph node gn.
1361  *
1362  * Results:
1363  *      JOB_ERROR if there was an error in the commands, JOB_FINISHED
1364  *      if there isn't actually anything left to do for the job and
1365  *      JOB_RUNNING if the job has been started.
1366  *
1367  * Side Effects:
1368  *      A new Job node is created and added to the list of running
1369  *      jobs. PMake is forked and a child shell created.
1370  *-----------------------------------------------------------------------
1371  */
1372 static int
1373 JobStart(GNode *gn, int flags, Job *previous)
1374 {
1375     Job           *job;       /* new job descriptor */
1376     char          *argv[4];   /* Argument vector to shell */
1377     Boolean       cmdsOK;     /* true if the nodes commands were all right */
1378     Boolean       noExec;     /* Set true if we decide not to run the job */
1379     int           tfd;        /* File descriptor for temp file */
1380
1381     if (interrupted) {
1382         JobPassSig(interrupted);
1383         return (JOB_ERROR);
1384     }
1385     if (previous != NULL) {
1386         previous->flags &= ~(JOB_FIRST|JOB_IGNERR|JOB_SILENT);
1387         job = previous;
1388     } else {
1389         job = emalloc(sizeof(Job));
1390         flags |= JOB_FIRST;
1391     }
1392
1393     job->node = gn;
1394     job->tailCmds = NULL;
1395
1396     /*
1397      * Set the initial value of the flags for this job based on the global
1398      * ones and the node's attributes... Any flags supplied by the caller
1399      * are also added to the field.
1400      */
1401     job->flags = 0;
1402     if (Targ_Ignore(gn)) {
1403         job->flags |= JOB_IGNERR;
1404     }
1405     if (Targ_Silent(gn)) {
1406         job->flags |= JOB_SILENT;
1407     }
1408     job->flags |= flags;
1409
1410     /*
1411      * Check the commands now so any attributes from .DEFAULT have a chance
1412      * to migrate to the node
1413      */
1414     if (!compatMake && job->flags & JOB_FIRST) {
1415         cmdsOK = Job_CheckCommands(gn, Error);
1416     } else {
1417         cmdsOK = TRUE;
1418     }
1419
1420     /*
1421      * If the -n flag wasn't given, we open up OUR (not the child's)
1422      * temporary file to stuff commands in it. The thing is rd/wr so we don't
1423      * need to reopen it to feed it to the shell. If the -n flag *was* given,
1424      * we just set the file to be stdout. Cute, huh?
1425      */
1426     if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1427         /*
1428          * We're serious here, but if the commands were bogus, we're
1429          * also dead...
1430          */
1431         if (!cmdsOK) {
1432             DieHorribly();
1433         }
1434
1435         strcpy(tfile, TMPPAT);
1436         if ((tfd = mkstemp(tfile)) == -1)
1437             Punt("Cannot create temp file: %s", strerror(errno));
1438         job->cmdFILE = fdopen(tfd, "w+");
1439         eunlink(tfile);
1440         if (job->cmdFILE == NULL) {
1441             close(tfd);
1442             Punt("Could not open %s", tfile);
1443         }
1444         fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1445         /*
1446          * Send the commands to the command file, flush all its buffers then
1447          * rewind and remove the thing.
1448          */
1449         noExec = FALSE;
1450
1451         /*
1452          * used to be backwards; replace when start doing multiple commands
1453          * per shell.
1454          */
1455         if (compatMake) {
1456             /*
1457              * Be compatible: If this is the first time for this node,
1458              * verify its commands are ok and open the commands list for
1459              * sequential access by later invocations of JobStart.
1460              * Once that is done, we take the next command off the list
1461              * and print it to the command file. If the command was an
1462              * ellipsis, note that there's nothing more to execute.
1463              */
1464             if ((job->flags&JOB_FIRST) && (Lst_Open(gn->commands) != SUCCESS)){
1465                 cmdsOK = FALSE;
1466             } else {
1467                 LstNode ln = Lst_Next(gn->commands);
1468
1469                 if ((ln == NULL) ||
1470                     JobPrintCommand(Lst_Datum(ln), job))
1471                 {
1472                     noExec = TRUE;
1473                     Lst_Close(gn->commands);
1474                 }
1475                 if (noExec && !(job->flags & JOB_FIRST)) {
1476                     /*
1477                      * If we're not going to execute anything, the job
1478                      * is done and we need to close down the various
1479                      * file descriptors we've opened for output, then
1480                      * call JobDoOutput to catch the final characters or
1481                      * send the file to the screen... Note that the i/o streams
1482                      * are only open if this isn't the first job.
1483                      * Note also that this could not be done in
1484                      * Job_CatchChildren b/c it wasn't clear if there were
1485                      * more commands to execute or not...
1486                      */
1487                     JobClose(job);
1488                 }
1489             }
1490         } else {
1491             /*
1492              * We can do all the commands at once. hooray for sanity
1493              */
1494             numCommands = 0;
1495             Lst_ForEach(gn->commands, JobPrintCommand, job);
1496
1497             /*
1498              * If we didn't print out any commands to the shell script,
1499              * there's not much point in executing the shell, is there?
1500              */
1501             if (numCommands == 0) {
1502                 noExec = TRUE;
1503             }
1504         }
1505     } else if (noExecute) {
1506         /*
1507          * Not executing anything -- just print all the commands to stdout
1508          * in one fell swoop. This will still set up job->tailCmds correctly.
1509          */
1510         if (lastNode != gn) {
1511             MESSAGE(stdout, gn);
1512             lastNode = gn;
1513         }
1514         job->cmdFILE = stdout;
1515         /*
1516          * Only print the commands if they're ok, but don't die if they're
1517          * not -- just let the user know they're bad and keep going. It
1518          * doesn't do any harm in this case and may do some good.
1519          */
1520         if (cmdsOK) {
1521             Lst_ForEach(gn->commands, JobPrintCommand, job);
1522         }
1523         /*
1524          * Don't execute the shell, thank you.
1525          */
1526         noExec = TRUE;
1527     } else {
1528         /*
1529          * Just touch the target and note that no shell should be executed.
1530          * Set cmdFILE to stdout to make life easier. Check the commands, too,
1531          * but don't die if they're no good -- it does no harm to keep working
1532          * up the graph.
1533          */
1534         job->cmdFILE = stdout;
1535         Job_Touch(gn, job->flags & JOB_SILENT);
1536         noExec = TRUE;
1537     }
1538
1539     /*
1540      * If we're not supposed to execute a shell, don't.
1541      */
1542     if (noExec) {
1543         /*
1544          * Unlink and close the command file if we opened one
1545          */
1546         if (job->cmdFILE != stdout) {
1547             if (job->cmdFILE != NULL)
1548                  fclose(job->cmdFILE);
1549         } else {
1550               fflush(stdout);
1551         }
1552
1553         /*
1554          * We only want to work our way up the graph if we aren't here because
1555          * the commands for the job were no good.
1556          */
1557         if (cmdsOK) {
1558             if (aborting == 0) {
1559                 if (job->tailCmds != NULL) {
1560                     Lst_ForEachFrom(job->node->commands, job->tailCmds,
1561                         JobSaveCommand, job->node);
1562                 }
1563                 job->node->made = MADE;
1564                 Make_Update(job->node);
1565             }
1566             free(job);
1567             return(JOB_FINISHED);
1568         } else {
1569             free(job);
1570             return(JOB_ERROR);
1571         }
1572     } else {
1573          fflush(job->cmdFILE);
1574     }
1575
1576     /*
1577      * Set up the control arguments to the shell. This is based on the flags
1578      * set earlier for this job.
1579      */
1580     JobMakeArgv(job, argv);
1581
1582     /*
1583      * If we're using pipes to catch output, create the pipe by which we'll
1584      * get the shell's output. If we're using files, print out that we're
1585      * starting a job and then set up its temporary-file name.
1586      */
1587     if (!compatMake || (job->flags & JOB_FIRST)) {
1588         if (usePipes) {
1589             int fd[2];
1590
1591             if (pipe(fd) == -1)
1592                 Punt("Cannot create pipe: %s", strerror(errno));
1593             job->inPipe = fd[0];
1594             job->outPipe = fd[1];
1595             fcntl(job->inPipe, F_SETFD, 1);
1596             fcntl(job->outPipe, F_SETFD, 1);
1597         } else {
1598             fprintf(stdout, "Remaking `%s'\n", gn->name);
1599             fflush(stdout);
1600             strcpy(job->outFile, TMPPAT);
1601             if ((job->outFd = mkstemp(job->outFile)) == -1)
1602                 Punt("cannot create temp file: %s", strerror(errno));
1603             fcntl(job->outFd, F_SETFD, 1);
1604         }
1605     }
1606
1607     if ((nJobs >= maxJobs) && !(job->flags & JOB_SPECIAL) && (maxJobs != 0)) {
1608         /*
1609          * We've hit the limit of concurrency, so put the job on hold until
1610          * some other job finishes. Note that the special jobs (.BEGIN,
1611          * .INTERRUPT and .END) may be run even when the limit has been reached
1612          * (e.g. when maxJobs == 0).
1613          */
1614         jobFull = TRUE;
1615
1616         DEBUGF(JOB, ("Can only run job locally.\n"));
1617         job->flags |= JOB_RESTART;
1618         Lst_AtEnd(stoppedJobs, job);
1619     } else {
1620         if (nJobs >= maxJobs) {
1621             /*
1622              * If we're running this job locally as a special case (see above),
1623              * at least say the table is full.
1624              */
1625             jobFull = TRUE;
1626             DEBUGF(JOB, ("Local job queue is full.\n"));
1627         }
1628         JobExec(job, argv);
1629     }
1630     return (JOB_RUNNING);
1631 }
1632
1633 static char *
1634 JobOutput(Job *job, char *cp, char *endp, int msg)
1635 {
1636     char *ecp;
1637
1638     if (commandShell->noPrint) {
1639         ecp = strstr(cp, commandShell->noPrint);
1640         while (ecp != NULL) {
1641             if (cp != ecp) {
1642                 *ecp = '\0';
1643                 if (msg && job->node != lastNode) {
1644                     MESSAGE(stdout, job->node);
1645                     lastNode = job->node;
1646                 }
1647                 /*
1648                  * The only way there wouldn't be a newline after
1649                  * this line is if it were the last in the buffer.
1650                  * however, since the non-printable comes after it,
1651                  * there must be a newline, so we don't print one.
1652                  */
1653                  fprintf(stdout, "%s", cp);
1654                  fflush(stdout);
1655             }
1656             cp = ecp + commandShell->noPLen;
1657             if (cp != endp) {
1658                 /*
1659                  * Still more to print, look again after skipping
1660                  * the whitespace following the non-printable
1661                  * command....
1662                  */
1663                 cp++;
1664                 while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
1665                     cp++;
1666                 }
1667                 ecp = strstr(cp, commandShell->noPrint);
1668             } else {
1669                 return (cp);
1670             }
1671         }
1672     }
1673     return (cp);
1674 }
1675
1676 /*-
1677  *-----------------------------------------------------------------------
1678  * JobDoOutput  --
1679  *      This function is called at different times depending on
1680  *      whether the user has specified that output is to be collected
1681  *      via pipes or temporary files. In the former case, we are called
1682  *      whenever there is something to read on the pipe. We collect more
1683  *      output from the given job and store it in the job's outBuf. If
1684  *      this makes up a line, we print it tagged by the job's identifier,
1685  *      as necessary.
1686  *      If output has been collected in a temporary file, we open the
1687  *      file and read it line by line, transfering it to our own
1688  *      output channel until the file is empty. At which point we
1689  *      remove the temporary file.
1690  *      In both cases, however, we keep our figurative eye out for the
1691  *      'noPrint' line for the shell from which the output came. If
1692  *      we recognize a line, we don't print it. If the command is not
1693  *      alone on the line (the character after it is not \0 or \n), we
1694  *      do print whatever follows it.
1695  *
1696  * Results:
1697  *      None
1698  *
1699  * Side Effects:
1700  *      curPos may be shifted as may the contents of outBuf.
1701  *-----------------------------------------------------------------------
1702  */
1703 STATIC void
1704 JobDoOutput(Job *job, Boolean finish)
1705 {
1706     Boolean       gotNL = FALSE;  /* true if got a newline */
1707     Boolean       fbuf;           /* true if our buffer filled up */
1708     int           nr;             /* number of bytes read */
1709     int           i;              /* auxiliary index into outBuf */
1710     int           max;            /* limit for i (end of current data) */
1711     int           nRead;          /* (Temporary) number of bytes read */
1712
1713     FILE          *oFILE;         /* Stream pointer to shell's output file */
1714     char          inLine[132];
1715
1716     if (usePipes) {
1717         /*
1718          * Read as many bytes as will fit in the buffer.
1719          */
1720 end_loop:
1721         gotNL = FALSE;
1722         fbuf = FALSE;
1723
1724         nRead = read(job->inPipe, &job->outBuf[job->curPos],
1725                          JOB_BUFSIZE - job->curPos);
1726         /*
1727          * Check for interrupt here too, because the above read may block
1728          * when the child process is stopped. In this case the interrupt
1729          * will unblock it (we don't use SA_RESTART).
1730          */
1731         if (interrupted)
1732             JobPassSig(interrupted);
1733
1734         if (nRead < 0) {
1735             DEBUGF(JOB, ("JobDoOutput(piperead)"));
1736             nr = 0;
1737         } else {
1738             nr = nRead;
1739         }
1740
1741         /*
1742          * If we hit the end-of-file (the job is dead), we must flush its
1743          * remaining output, so pretend we read a newline if there's any
1744          * output remaining in the buffer.
1745          * Also clear the 'finish' flag so we stop looping.
1746          */
1747         if ((nr == 0) && (job->curPos != 0)) {
1748             job->outBuf[job->curPos] = '\n';
1749             nr = 1;
1750             finish = FALSE;
1751         } else if (nr == 0) {
1752             finish = FALSE;
1753         }
1754
1755         /*
1756          * Look for the last newline in the bytes we just got. If there is
1757          * one, break out of the loop with 'i' as its index and gotNL set
1758          * TRUE.
1759          */
1760         max = job->curPos + nr;
1761         for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1762             if (job->outBuf[i] == '\n') {
1763                 gotNL = TRUE;
1764                 break;
1765             } else if (job->outBuf[i] == '\0') {
1766                 /*
1767                  * Why?
1768                  */
1769                 job->outBuf[i] = ' ';
1770             }
1771         }
1772
1773         if (!gotNL) {
1774             job->curPos += nr;
1775             if (job->curPos == JOB_BUFSIZE) {
1776                 /*
1777                  * If we've run out of buffer space, we have no choice
1778                  * but to print the stuff. sigh.
1779                  */
1780                 fbuf = TRUE;
1781                 i = job->curPos;
1782             }
1783         }
1784         if (gotNL || fbuf) {
1785             /*
1786              * Need to send the output to the screen. Null terminate it
1787              * first, overwriting the newline character if there was one.
1788              * So long as the line isn't one we should filter (according
1789              * to the shell description), we print the line, preceded
1790              * by a target banner if this target isn't the same as the
1791              * one for which we last printed something.
1792              * The rest of the data in the buffer are then shifted down
1793              * to the start of the buffer and curPos is set accordingly.
1794              */
1795             job->outBuf[i] = '\0';
1796             if (i >= job->curPos) {
1797                 char *cp;
1798
1799                 cp = JobOutput(job, job->outBuf, &job->outBuf[i], FALSE);
1800
1801                 /*
1802                  * There's still more in that thar buffer. This time, though,
1803                  * we know there's no newline at the end, so we add one of
1804                  * our own free will.
1805                  */
1806                 if (*cp != '\0') {
1807                     if (job->node != lastNode) {
1808                         MESSAGE(stdout, job->node);
1809                         lastNode = job->node;
1810                     }
1811                      fprintf(stdout, "%s%s", cp, gotNL ? "\n" : "");
1812                      fflush(stdout);
1813                 }
1814             }
1815             if (i < max - 1) {
1816                 /* shift the remaining characters down */
1817                  memcpy(job->outBuf, &job->outBuf[i + 1], max - (i + 1));
1818                 job->curPos = max - (i + 1);
1819
1820             } else {
1821                 /*
1822                  * We have written everything out, so we just start over
1823                  * from the start of the buffer. No copying. No nothing.
1824                  */
1825                 job->curPos = 0;
1826             }
1827         }
1828         if (finish) {
1829             /*
1830              * If the finish flag is true, we must loop until we hit
1831              * end-of-file on the pipe. This is guaranteed to happen
1832              * eventually since the other end of the pipe is now closed
1833              * (we closed it explicitly and the child has exited). When
1834              * we do get an EOF, finish will be set FALSE and we'll fall
1835              * through and out.
1836              */
1837             goto end_loop;
1838         }
1839     } else {
1840         /*
1841          * We've been called to retrieve the output of the job from the
1842          * temporary file where it's been squirreled away. This consists of
1843          * opening the file, reading the output line by line, being sure not
1844          * to print the noPrint line for the shell we used, then close and
1845          * remove the temporary file. Very simple.
1846          *
1847          * Change to read in blocks and do FindSubString type things as for
1848          * pipes? That would allow for "@echo -n..."
1849          */
1850         oFILE = fopen(job->outFile, "r");
1851         if (oFILE != NULL) {
1852             fprintf(stdout, "Results of making %s:\n", job->node->name);
1853             fflush(stdout);
1854             while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
1855                 char    *cp, *endp, *oendp;
1856
1857                 cp = inLine;
1858                 oendp = endp = inLine + strlen(inLine);
1859                 if (endp[-1] == '\n') {
1860                     *--endp = '\0';
1861                 }
1862                 cp = JobOutput(job, inLine, endp, FALSE);
1863
1864                 /*
1865                  * There's still more in that thar buffer. This time, though,
1866                  * we know there's no newline at the end, so we add one of
1867                  * our own free will.
1868                  */
1869                 fprintf(stdout, "%s", cp);
1870                 fflush(stdout);
1871                 if (endp != oendp) {
1872                      fprintf(stdout, "\n");
1873                      fflush(stdout);
1874                 }
1875             }
1876             fclose(oFILE);
1877             eunlink(job->outFile);
1878         }
1879     }
1880 }
1881
1882 /*-
1883  *-----------------------------------------------------------------------
1884  * Job_CatchChildren --
1885  *      Handle the exit of a child. Called from Make_Make.
1886  *
1887  * Results:
1888  *      none.
1889  *
1890  * Side Effects:
1891  *      The job descriptor is removed from the list of children.
1892  *
1893  * Notes:
1894  *      We do waits, blocking or not, according to the wisdom of our
1895  *      caller, until there are no more children to report. For each
1896  *      job, call JobFinish to finish things off. This will take care of
1897  *      putting jobs on the stoppedJobs queue.
1898  *
1899  *-----------------------------------------------------------------------
1900  */
1901 void
1902 Job_CatchChildren(Boolean block)
1903 {
1904     int           pid;          /* pid of dead child */
1905     Job           *job;         /* job descriptor for dead child */
1906     LstNode       jnode;        /* list element for finding job */
1907     int           status;       /* Exit/termination status */
1908
1909     /*
1910      * Don't even bother if we know there's no one around.
1911      */
1912     if (nJobs == 0) {
1913         return;
1914     }
1915
1916     for (;;) {
1917         pid = waitpid((pid_t)-1, &status, (block ? 0 : WNOHANG) | WUNTRACED);
1918         if (pid <= 0)
1919             break;
1920         DEBUGF(JOB, ("Process %d exited or stopped.\n", pid));
1921
1922         jnode = Lst_Find(jobs, &pid, JobCmpPid);
1923
1924         if (jnode == NULL) {
1925             if (WIFSIGNALED(status) && (WTERMSIG(status) == SIGCONT)) {
1926                 jnode = Lst_Find(stoppedJobs, &pid, JobCmpPid);
1927                 if (jnode == NULL) {
1928                     Error("Resumed child (%d) not in table", pid);
1929                     continue;
1930                 }
1931                 job = Lst_Datum(jnode);
1932                 Lst_Remove(stoppedJobs, jnode);
1933             } else {
1934                 Error("Child (%d) not in table?", pid);
1935                 continue;
1936             }
1937         } else {
1938             job = Lst_Datum(jnode);
1939             Lst_Remove(jobs, jnode);
1940             nJobs -= 1;
1941             if (fifoFd >= 0 && maxJobs > 1) {
1942                 write(fifoFd, "+", 1);
1943                 maxJobs--;
1944                 if (nJobs >= maxJobs)
1945                     jobFull = TRUE;
1946                 else
1947                     jobFull = FALSE;
1948             } else {
1949                 DEBUGF(JOB, ("Job queue is no longer full.\n"));
1950                 jobFull = FALSE;
1951             }
1952         }
1953
1954         JobFinish(job, &status);
1955     }
1956     if (interrupted)
1957         JobPassSig(interrupted);
1958 }
1959
1960 /*-
1961  *-----------------------------------------------------------------------
1962  * Job_CatchOutput --
1963  *      Catch the output from our children, if we're using
1964  *      pipes do so. Otherwise just block time until we get a
1965  *      signal(most likely a SIGCHLD) since there's no point in
1966  *      just spinning when there's nothing to do and the reaping
1967  *      of a child can wait for a while.
1968  *
1969  * Results:
1970  *      None
1971  *
1972  * Side Effects:
1973  *      Output is read from pipes if we're piping.
1974  * -----------------------------------------------------------------------
1975  */
1976 void
1977 Job_CatchOutput(int flag)
1978 {
1979     int                   nfds;
1980 #ifdef USE_KQUEUE
1981 #define KEV_SIZE        4
1982     struct kevent         kev[KEV_SIZE];
1983     int                   i;
1984 #else
1985     struct timeval        timeout;
1986     fd_set                readfds;
1987     LstNode               ln;
1988     Job                   *job;
1989 #endif
1990
1991      fflush(stdout);
1992
1993     if (usePipes) {
1994 #ifdef USE_KQUEUE
1995         if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
1996             if (errno != EINTR)
1997                 Punt("kevent: %s", strerror(errno));
1998             if (interrupted)
1999                 JobPassSig(interrupted);
2000         } else {
2001             for (i = 0; i < nfds; i++) {
2002                 if (kev[i].flags & EV_ERROR) {
2003                     warnc(kev[i].data, "kevent");
2004                     continue;
2005                 }
2006                 switch (kev[i].filter) {
2007                 case EVFILT_READ:
2008                     JobDoOutput(kev[i].udata, FALSE);
2009                     break;
2010                 case EVFILT_PROC:
2011                     /* Just wake up and let Job_CatchChildren() collect the
2012                      * terminated job. */
2013                     break;
2014                 }
2015             }
2016         }
2017 #else
2018         readfds = outputs;
2019         timeout.tv_sec = SEL_SEC;
2020         timeout.tv_usec = SEL_USEC;
2021         if (flag && jobFull && fifoFd >= 0)
2022             FD_SET(fifoFd, &readfds);
2023
2024         nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
2025                            (fd_set *)NULL, &timeout);
2026         if (nfds <= 0) {
2027             if (interrupted)
2028                 JobPassSig(interrupted);
2029             return;
2030         }
2031         if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2032             if (--nfds <= 0)
2033                 return;
2034         }
2035         if (Lst_Open(jobs) == FAILURE) {
2036             Punt("Cannot open job table");
2037         }
2038         while (nfds && (ln = Lst_Next(jobs)) != NULL) {
2039             job = Lst_Datum(ln);
2040             if (FD_ISSET(job->inPipe, &readfds)) {
2041                 JobDoOutput(job, FALSE);
2042                 nfds -= 1;
2043             }
2044         }
2045         Lst_Close(jobs);
2046 #endif /* !USE_KQUEUE */
2047     }
2048 }
2049
2050 /*-
2051  *-----------------------------------------------------------------------
2052  * Job_Make --
2053  *      Start the creation of a target. Basically a front-end for
2054  *      JobStart used by the Make module.
2055  *
2056  * Results:
2057  *      None.
2058  *
2059  * Side Effects:
2060  *      Another job is started.
2061  *
2062  *-----------------------------------------------------------------------
2063  */
2064 void
2065 Job_Make(GNode *gn)
2066 {
2067
2068      JobStart(gn, 0, NULL);
2069 }
2070
2071 /*
2072  * JobCopyShell:
2073  *
2074  * Make a new copy of the shell structure including a copy of the strings
2075  * in it. This also defaults some fields in case they are NULL.
2076  *
2077  * The function returns a pointer to the new shell structure otherwise.
2078  */
2079 static Shell *
2080 JobCopyShell(const Shell *osh)
2081 {
2082         Shell *nsh;
2083
2084         nsh = emalloc(sizeof(*nsh));
2085         nsh->name = estrdup(osh->name);
2086
2087         if (osh->echoOff != NULL)
2088                 nsh->echoOff = estrdup(osh->echoOff);
2089         else
2090                 nsh->echoOff = NULL;
2091         if (osh->echoOn != NULL)
2092                 nsh->echoOn = estrdup(osh->echoOn);
2093         else
2094                 nsh->echoOn = NULL;
2095         nsh->hasEchoCtl = osh->hasEchoCtl;
2096
2097         if (osh->noPrint != NULL)
2098                 nsh->noPrint = estrdup(osh->noPrint);
2099         else
2100                 nsh->noPrint = NULL;
2101         nsh->noPLen = osh->noPLen;
2102
2103         nsh->hasErrCtl = osh->hasErrCtl;
2104         if (osh->errCheck == NULL)
2105                 nsh->errCheck = estrdup("");
2106         else
2107                 nsh->errCheck = estrdup(osh->errCheck);
2108         if (osh->ignErr == NULL)
2109                 nsh->ignErr = estrdup("%s");
2110         else
2111                 nsh->ignErr = estrdup(osh->ignErr);
2112
2113         if (osh->echo == NULL)
2114                 nsh->echo = estrdup("");
2115         else
2116                 nsh->echo = estrdup(osh->echo);
2117
2118         if (osh->exit == NULL)
2119                 nsh->exit = estrdup("");
2120         else
2121                 nsh->exit = estrdup(osh->exit);
2122
2123         return (nsh);
2124 }
2125
2126 /*
2127  * JobFreeShell:
2128  *
2129  * Free a shell structure and all associated strings.
2130  */
2131 static void
2132 JobFreeShell(Shell *sh)
2133 {
2134
2135         if (sh != NULL) {
2136                 free(sh->name);
2137                 free(sh->echoOff);
2138                 free(sh->echoOn);
2139                 free(sh->noPrint);
2140                 free(sh->errCheck);
2141                 free(sh->ignErr);
2142                 free(sh->echo);
2143                 free(sh->exit);
2144                 free(sh);
2145         }
2146 }
2147
2148 void
2149 Shell_Init(void)
2150 {
2151
2152     if (commandShell == NULL)
2153         commandShell = JobMatchShell(shells[DEFSHELL].name);
2154
2155     if (shellPath == NULL) {
2156         /*
2157          * The user didn't specify a shell to use, so we are using the
2158          * default one... Both the absolute path and the last component
2159          * must be set. The last component is taken from the 'name' field
2160          * of the default shell description pointed-to by commandShell.
2161          * All default shells are located in _PATH_DEFSHELLDIR.
2162          */
2163         shellName = commandShell->name;
2164         shellPath = str_concat(_PATH_DEFSHELLDIR, shellName, STR_ADDSLASH);
2165     }
2166 }
2167
2168 /*-
2169  *-----------------------------------------------------------------------
2170  * Job_Init --
2171  *      Initialize the process module, given a maximum number of jobs.
2172  *
2173  * Results:
2174  *      none
2175  *
2176  * Side Effects:
2177  *      lists and counters are initialized
2178  *-----------------------------------------------------------------------
2179  */
2180 void
2181 Job_Init(int maxproc)
2182 {
2183     GNode         *begin;     /* node for commands to do at the very start */
2184     const char    *env;
2185     struct sigaction sa;
2186
2187     fifoFd = -1;
2188     jobs = Lst_Init(FALSE);
2189     stoppedJobs = Lst_Init(FALSE);
2190     env = getenv("MAKE_JOBS_FIFO");
2191
2192     if (env == NULL && maxproc > 1) {
2193         /*
2194          * We did not find the environment variable so we are the leader.
2195          * Create the fifo, open it, write one char per allowed job into
2196          * the pipe.
2197          */
2198         mktemp(fifoName);
2199         if (!mkfifo(fifoName, 0600)) {
2200             fifoFd = open(fifoName, O_RDWR | O_NONBLOCK, 0);
2201             if (fifoFd >= 0) {
2202                 fifoMaster = 1;
2203                 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2204                 env = fifoName;
2205                 setenv("MAKE_JOBS_FIFO", env, 1);
2206                 while (maxproc-- > 0) {
2207                     write(fifoFd, "+", 1);
2208                 }
2209                 /* The master make does not get a magic token */
2210                 jobFull = TRUE;
2211                 maxJobs = 0;
2212             } else {
2213                 unlink(fifoName);
2214                 env = NULL;
2215             }
2216         }
2217     } else if (env != NULL) {
2218         /*
2219          * We had the environment variable so we are a slave.
2220          * Open fifo and give ourselves a magic token which represents
2221          * the token our parent make has grabbed to start his make process.
2222          * Otherwise the sub-makes would gobble up tokens and the proper
2223          * number of tokens to specify to -j would depend on the depth of
2224          * the tree and the order of execution.
2225          */
2226         fifoFd = open(env, O_RDWR, 0);
2227         if (fifoFd >= 0) {
2228             fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2229             maxJobs = 1;
2230             jobFull = FALSE;
2231         }
2232     }
2233     if (fifoFd <= 0) {
2234         maxJobs = maxproc;
2235         jobFull = FALSE;
2236     } else {
2237     }
2238     nJobs = 0;
2239
2240     aborting = 0;
2241     errors = 0;
2242
2243     lastNode = NULL;
2244
2245     if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2246         /*
2247          * If only one job can run at a time, there's no need for a banner,
2248          * no is there?
2249          */
2250         targFmt = "";
2251     } else {
2252         targFmt = TARG_FMT;
2253     }
2254
2255     Shell_Init();
2256
2257     /*
2258      * Catch the four signals that POSIX specifies if they aren't ignored.
2259      * JobCatchSignal will just set global variables and hope someone
2260      * else is going to handle the interrupt.
2261      */
2262     sa.sa_handler = JobCatchSig;
2263     sigemptyset(&sa.sa_mask);
2264     sa.sa_flags = 0;
2265
2266     if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2267         sigaction(SIGINT, &sa, NULL);
2268     }
2269     if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2270         sigaction(SIGHUP, &sa, NULL);
2271     }
2272     if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2273         sigaction(SIGQUIT, &sa, NULL);
2274     }
2275     if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2276         sigaction(SIGTERM, &sa, NULL);
2277     }
2278     /*
2279      * There are additional signals that need to be caught and passed if
2280      * either the export system wants to be told directly of signals or if
2281      * we're giving each job its own process group (since then it won't get
2282      * signals from the terminal driver as we own the terminal)
2283      */
2284 #if defined(USE_PGRP)
2285     if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2286         sigaction(SIGTSTP, &sa, NULL);
2287     }
2288     if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2289         sigaction(SIGTTOU, &sa, NULL);
2290     }
2291     if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2292         sigaction(SIGTTIN, &sa, NULL);
2293     }
2294     if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2295         sigaction(SIGWINCH, &sa, NULL);
2296     }
2297 #endif
2298
2299 #ifdef USE_KQUEUE
2300     if ((kqfd = kqueue()) == -1) {
2301         Punt("kqueue: %s", strerror(errno));
2302     }
2303 #endif
2304
2305     begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2306
2307     if (begin != NULL) {
2308         JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2309         while (nJobs) {
2310             Job_CatchOutput(0);
2311             Job_CatchChildren(!usePipes);
2312         }
2313     }
2314     postCommands = Targ_FindNode(".END", TARG_CREATE);
2315 }
2316
2317 /*-
2318  *-----------------------------------------------------------------------
2319  * Job_Full --
2320  *      See if the job table is full. It is considered full if it is OR
2321  *      if we are in the process of aborting OR if we have
2322  *      reached/exceeded our local quota. This prevents any more jobs
2323  *      from starting up.
2324  *
2325  * Results:
2326  *      TRUE if the job table is full, FALSE otherwise
2327  * Side Effects:
2328  *      None.
2329  *-----------------------------------------------------------------------
2330  */
2331 Boolean
2332 Job_Full(void)
2333 {
2334     char c;
2335     int i;
2336
2337     if (aborting)
2338         return (aborting);
2339     if (fifoFd >= 0 && jobFull) {
2340         i = read(fifoFd, &c, 1);
2341         if (i > 0) {
2342             maxJobs++;
2343             jobFull = FALSE;
2344         }
2345     }
2346     return (jobFull);
2347 }
2348
2349 /*-
2350  *-----------------------------------------------------------------------
2351  * Job_Empty --
2352  *      See if the job table is empty.  Because the local concurrency may
2353  *      be set to 0, it is possible for the job table to become empty,
2354  *      while the list of stoppedJobs remains non-empty. In such a case,
2355  *      we want to restart as many jobs as we can.
2356  *
2357  * Results:
2358  *      TRUE if it is. FALSE if it ain't.
2359  *
2360  * Side Effects:
2361  *      None.
2362  *
2363  * -----------------------------------------------------------------------
2364  */
2365 Boolean
2366 Job_Empty(void)
2367 {
2368     if (nJobs == 0) {
2369         if (!Lst_IsEmpty(stoppedJobs) && !aborting) {
2370             /*
2371              * The job table is obviously not full if it has no jobs in
2372              * it...Try and restart the stopped jobs.
2373              */
2374             jobFull = FALSE;
2375             JobRestartJobs();
2376             return (FALSE);
2377         } else {
2378             return (TRUE);
2379         }
2380     } else {
2381         return (FALSE);
2382     }
2383 }
2384
2385 /*-
2386  *-----------------------------------------------------------------------
2387  * JobMatchShell --
2388  *      Find a matching shell in 'shells' given its final component.
2389  *
2390  * Results:
2391  *      A pointer to a freshly allocated Shell structure with a copy
2392  *      of the static structure or NULL if no shell with the given name
2393  *      is found.
2394  *
2395  * Side Effects:
2396  *      None.
2397  *
2398  *-----------------------------------------------------------------------
2399  */
2400 static Shell *
2401 JobMatchShell(const char *name)
2402 {
2403     const struct CShell *sh;          /* Pointer into shells table */
2404     struct Shell *nsh;
2405
2406     for (sh = shells; sh < shells + __arysize(shells); sh++)
2407         if (strcmp(sh->name, name) == 0)
2408             break;
2409
2410     if (sh == shells + __arysize(shells))
2411         return (NULL);
2412
2413     /* make a copy */
2414     nsh = emalloc(sizeof(*nsh));
2415
2416     nsh->name = estrdup(sh->name);
2417     nsh->echoOff = estrdup(sh->echoOff);
2418     nsh->echoOn = estrdup(sh->echoOn);
2419     nsh->hasEchoCtl = sh->hasEchoCtl;
2420     nsh->noPrint = estrdup(sh->noPrint);
2421     nsh->noPLen = sh->noPLen;
2422     nsh->hasErrCtl = sh->hasErrCtl;
2423     nsh->errCheck = estrdup(sh->errCheck);
2424     nsh->ignErr = estrdup(sh->ignErr);
2425     nsh->echo = estrdup(sh->echo);
2426     nsh->exit = estrdup(sh->exit);
2427
2428     return (nsh);
2429 }
2430
2431 /*-
2432  *-----------------------------------------------------------------------
2433  * Job_ParseShell --
2434  *      Parse a shell specification and set up commandShell, shellPath
2435  *      and shellName appropriately.
2436  *
2437  * Results:
2438  *      FAILURE if the specification was incorrect.
2439  *
2440  * Side Effects:
2441  *      commandShell points to a Shell structure (either predefined or
2442  *      created from the shell spec), shellPath is the full path of the
2443  *      shell described by commandShell, while shellName is just the
2444  *      final component of shellPath.
2445  *
2446  * Notes:
2447  *      A shell specification consists of a .SHELL target, with dependency
2448  *      operator, followed by a series of blank-separated words. Double
2449  *      quotes can be used to use blanks in words. A backslash escapes
2450  *      anything (most notably a double-quote and a space) and
2451  *      provides the functionality it does in C. Each word consists of
2452  *      keyword and value separated by an equal sign. There should be no
2453  *      unnecessary spaces in the word. The keywords are as follows:
2454  *          name            Name of shell.
2455  *          path            Location of shell. Overrides "name" if given
2456  *          quiet           Command to turn off echoing.
2457  *          echo            Command to turn echoing on
2458  *          filter          Result of turning off echoing that shouldn't be
2459  *                          printed.
2460  *          echoFlag        Flag to turn echoing on at the start
2461  *          errFlag         Flag to turn error checking on at the start
2462  *          hasErrCtl       True if shell has error checking control
2463  *          check           Command to turn on error checking if hasErrCtl
2464  *                          is TRUE or template of command to echo a command
2465  *                          for which error checking is off if hasErrCtl is
2466  *                          FALSE.
2467  *          ignore          Command to turn off error checking if hasErrCtl
2468  *                          is TRUE or template of command to execute a
2469  *                          command so as to ignore any errors it returns if
2470  *                          hasErrCtl is FALSE.
2471  *
2472  *-----------------------------------------------------------------------
2473  */
2474 ReturnStatus
2475 Job_ParseShell(char *line)
2476 {
2477     char          **words;
2478     int           wordCount;
2479     char          **argv;
2480     int           argc;
2481     char          *path;
2482     Shell         newShell;
2483     Shell         *sh;
2484     Boolean       fullSpec = FALSE;
2485
2486     while (isspace((unsigned char)*line)) {
2487         line++;
2488     }
2489     words = brk_string(line, &wordCount, TRUE);
2490
2491     memset(&newShell, 0, sizeof(newShell));
2492
2493     /*
2494      * Parse the specification by keyword
2495      */
2496     for (path = NULL, argc = wordCount - 1, argv = words + 1;
2497          argc != 0;
2498          argc--, argv++) {
2499              if (strncmp(*argv, "path=", 5) == 0) {
2500                  path = &argv[0][5];
2501              } else if (strncmp(*argv, "name=", 5) == 0) {
2502                  newShell.name = &argv[0][5];
2503              } else {
2504                  if (strncmp(*argv, "quiet=", 6) == 0) {
2505                      newShell.echoOff = &argv[0][6];
2506                  } else if (strncmp(*argv, "echo=", 5) == 0) {
2507                      newShell.echoOn = &argv[0][5];
2508                  } else if (strncmp(*argv, "filter=", 7) == 0) {
2509                      newShell.noPrint = &argv[0][7];
2510                      newShell.noPLen = strlen(newShell.noPrint);
2511                  } else if (strncmp(*argv, "echoFlag=", 9) == 0) {
2512                      newShell.echo = &argv[0][9];
2513                  } else if (strncmp(*argv, "errFlag=", 8) == 0) {
2514                      newShell.exit = &argv[0][8];
2515                  } else if (strncmp(*argv, "hasErrCtl=", 10) == 0) {
2516                      char c = argv[0][10];
2517                      newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
2518                                            (c != 'T') && (c != 't'));
2519                  } else if (strncmp(*argv, "check=", 6) == 0) {
2520                      newShell.errCheck = &argv[0][6];
2521                  } else if (strncmp(*argv, "ignore=", 7) == 0) {
2522                      newShell.ignErr = &argv[0][7];
2523                  } else {
2524                      Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"",
2525                                   *argv);
2526                      return (FAILURE);
2527                  }
2528                  fullSpec = TRUE;
2529              }
2530     }
2531
2532     /*
2533      * Some checks (could be more)
2534      */
2535     if (fullSpec) {
2536         if ((newShell.echoOn != NULL) ^ (newShell.echoOff != NULL))
2537             Parse_Error(PARSE_FATAL, "Shell must have either both echoOff and "
2538                 "echoOn or none of them");
2539
2540         if (newShell.echoOn != NULL && newShell.echoOff)
2541             newShell.hasEchoCtl = TRUE;
2542     }
2543
2544     if (path == NULL) {
2545         /*
2546          * If no path was given, the user wants one of the pre-defined shells,
2547          * yes? So we find the one s/he wants with the help of JobMatchShell
2548          * and set things up the right way. shellPath will be set up by
2549          * Job_Init.
2550          */
2551         if (newShell.name == NULL) {
2552             Parse_Error(PARSE_FATAL, "Neither path nor name specified");
2553             return (FAILURE);
2554         }
2555         if ((sh = JobMatchShell(newShell.name)) == NULL) {
2556             Parse_Error(PARSE_FATAL, "%s: no matching shell", newShell.name);
2557             return (FAILURE);
2558         }
2559
2560     } else {
2561         /*
2562          * The user provided a path. If s/he gave nothing else (fullSpec is
2563          * FALSE), try and find a matching shell in the ones we know of.
2564          * Else we just take the specification at its word and copy it
2565          * to a new location. In either case, we need to record the
2566          * path the user gave for the shell.
2567          */
2568         free(shellPath);
2569         shellPath = estrdup(path);
2570         if (newShell.name == NULL) {
2571             /* get the base name as the name */
2572         path = strrchr(path, '/');
2573         if (path == NULL) {
2574             path = shellPath;
2575         } else {
2576             path += 1;
2577         }
2578             newShell.name = path;
2579         }
2580
2581         if (!fullSpec) {
2582             if ((sh = JobMatchShell(newShell.name)) == NULL) {
2583                 Parse_Error(PARSE_FATAL, "%s: no matching shell",
2584                     newShell.name);
2585                 return (FAILURE);
2586             }
2587         } else {
2588             sh = JobCopyShell(&newShell);
2589         }
2590     }
2591
2592     /* set the new shell */
2593     JobFreeShell(commandShell);
2594     commandShell = sh;
2595
2596     shellName = commandShell->name;
2597
2598     return (SUCCESS);
2599 }
2600
2601 /*-
2602  *-----------------------------------------------------------------------
2603  * JobInterrupt --
2604  *      Handle the receipt of an interrupt.
2605  *
2606  * Results:
2607  *      None
2608  *
2609  * Side Effects:
2610  *      All children are killed. Another job will be started if the
2611  *      .INTERRUPT target was given.
2612  *-----------------------------------------------------------------------
2613  */
2614 static void
2615 JobInterrupt(int runINTERRUPT, int signo)
2616 {
2617     LstNode       ln;           /* element in job table */
2618     Job           *job = NULL;  /* job descriptor in that element */
2619     GNode         *interrupt;   /* the node describing the .INTERRUPT target */
2620
2621     aborting = ABORT_INTERRUPT;
2622
2623     Lst_Open(jobs);
2624     while ((ln = Lst_Next(jobs)) != NULL) {
2625         job = Lst_Datum(ln);
2626
2627         if (!Targ_Precious(job->node)) {
2628             char *file = (job->node->path == NULL ?
2629                                 job->node->name :
2630                                 job->node->path);
2631             if (!noExecute && eunlink(file) != -1) {
2632                 Error("*** %s removed", file);
2633             }
2634         }
2635         if (job->pid) {
2636             DEBUGF(JOB, ("JobInterrupt passing signal to child %d.\n",
2637                    job->pid));
2638             KILL(job->pid, signo);
2639         }
2640     }
2641
2642     if (runINTERRUPT && !touchFlag) {
2643         /* clear the interrupted flag because we would get an
2644          * infinite loop otherwise */
2645         interrupted = 0;
2646
2647         interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2648         if (interrupt != NULL) {
2649             ignoreErrors = FALSE;
2650
2651             JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
2652             while (nJobs) {
2653                 Job_CatchOutput(0);
2654                 Job_CatchChildren(!usePipes);
2655             }
2656         }
2657     }
2658 }
2659
2660 /*
2661  *-----------------------------------------------------------------------
2662  * Job_Finish --
2663  *      Do final processing such as the running of the commands
2664  *      attached to the .END target.
2665  *
2666  * Results:
2667  *      Number of errors reported.
2668  *-----------------------------------------------------------------------
2669  */
2670 int
2671 Job_Finish(void)
2672 {
2673
2674     if (postCommands != NULL && !Lst_IsEmpty(postCommands->commands)) {
2675         if (errors) {
2676             Error("Errors reported so .END ignored");
2677         } else {
2678             JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
2679
2680             while (nJobs) {
2681                 Job_CatchOutput(0);
2682                 Job_CatchChildren(!usePipes);
2683             }
2684         }
2685     }
2686     if (fifoFd >= 0) {
2687         close(fifoFd);
2688         fifoFd = -1;
2689         if (fifoMaster)
2690             unlink(fifoName);
2691     }
2692     return (errors);
2693 }
2694
2695 /*-
2696  *-----------------------------------------------------------------------
2697  * Job_Wait --
2698  *      Waits for all running jobs to finish and returns. Sets 'aborting'
2699  *      to ABORT_WAIT to prevent other jobs from starting.
2700  *
2701  * Results:
2702  *      None.
2703  *
2704  * Side Effects:
2705  *      Currently running jobs finish.
2706  *
2707  *-----------------------------------------------------------------------
2708  */
2709 void
2710 Job_Wait(void)
2711 {
2712
2713     aborting = ABORT_WAIT;
2714     while (nJobs != 0) {
2715         Job_CatchOutput(0);
2716         Job_CatchChildren(!usePipes);
2717     }
2718     aborting = 0;
2719 }
2720
2721 /*-
2722  *-----------------------------------------------------------------------
2723  * Job_AbortAll --
2724  *      Abort all currently running jobs without handling output or anything.
2725  *      This function is to be called only in the event of a major
2726  *      error. Most definitely NOT to be called from JobInterrupt.
2727  *
2728  * Results:
2729  *      None
2730  *
2731  * Side Effects:
2732  *      All children are killed, not just the firstborn
2733  *-----------------------------------------------------------------------
2734  */
2735 void
2736 Job_AbortAll(void)
2737 {
2738     LstNode             ln;     /* element in job table */
2739     Job                 *job;   /* the job descriptor in that element */
2740     int                 foo;
2741
2742     aborting = ABORT_ERROR;
2743
2744     if (nJobs) {
2745         Lst_Open(jobs);
2746         while ((ln = Lst_Next(jobs)) != NULL) {
2747             job = Lst_Datum(ln);
2748
2749             /*
2750              * kill the child process with increasingly drastic signals to make
2751              * darn sure it's dead.
2752              */
2753             KILL(job->pid, SIGINT);
2754             KILL(job->pid, SIGKILL);
2755         }
2756     }
2757
2758     /*
2759      * Catch as many children as want to report in at first, then give up
2760      */
2761     while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2762         continue;
2763 }
2764
2765 /*-
2766  *-----------------------------------------------------------------------
2767  * JobRestartJobs --
2768  *      Tries to restart stopped jobs if there are slots available.
2769  *      Note that this tries to restart them regardless of pending errors.
2770  *      It's not good to leave stopped jobs lying around!
2771  *
2772  * Results:
2773  *      None.
2774  *
2775  * Side Effects:
2776  *      Resumes(and possibly migrates) jobs.
2777  *
2778  *-----------------------------------------------------------------------
2779  */
2780 static void
2781 JobRestartJobs(void)
2782 {
2783     while (!jobFull && !Lst_IsEmpty(stoppedJobs)) {
2784         DEBUGF(JOB, ("Job queue is not full. Restarting a stopped job.\n"));
2785         JobRestart(Lst_DeQueue(stoppedJobs));
2786     }
2787 }