3415859e0dde8c92ba63c4e24372ea6453356cc8
[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.36 2005/01/05 23:30:35 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 int maxJobs;            /* The most children we can run at once */
215 STATIC int      nJobs;          /* The number of children currently running */
216
217 /* The structures that describe them */
218 STATIC Lst jobs = Lst_Initializer(jobs);
219
220 STATIC Boolean  jobFull;        /* Flag to tell when the job table is full. It
221                                  * is set TRUE when (1) the total number of
222                                  * running jobs equals the maximum allowed */
223 #ifdef USE_KQUEUE
224 static int      kqfd;           /* File descriptor obtained by kqueue() */
225 #else
226 static fd_set   outputs;        /* Set of descriptors of pipes connected to
227                                  * the output channels of children */
228 #endif
229
230 STATIC GNode    *lastNode;      /* The node for which output was most recently
231                                  * produced. */
232 STATIC char     *targFmt;       /* Format string to use to head output from a
233                                  * job when it's not the most-recent job heard
234                                  * from */
235
236 #define TARG_FMT  "--- %s ---\n" /* Default format */
237 #define MESSAGE(fp, gn) \
238          fprintf(fp, targFmt, gn->name);
239
240 /*
241  * When JobStart attempts to run a job but isn't allowed to
242  * or when Job_CatchChildren detects a job that has
243  * been stopped somehow, the job is placed on the stoppedJobs queue to be run
244  * when the next job finishes.
245  *
246  * Lst of Job structures describing jobs that were stopped due to
247  * concurrency limits or externally
248  */
249 STATIC Lst stoppedJobs = Lst_Initializer(stoppedJobs);
250
251 STATIC int      fifoFd;         /* Fd of our job fifo */
252 STATIC char     fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
253 STATIC int      fifoMaster;
254
255 static sig_atomic_t interrupted;
256
257
258 #if defined(USE_PGRP) && defined(SYSV)
259 # define KILL(pid, sig)         killpg(-(pid), (sig))
260 #else
261 # if defined(USE_PGRP)
262 #  define KILL(pid, sig)        killpg((pid), (sig))
263 # else
264 #  define KILL(pid, sig)        kill((pid), (sig))
265 # endif
266 #endif
267
268 /*
269  * Grmpf... There is no way to set bits of the wait structure
270  * anymore with the stupid W*() macros. I liked the union wait
271  * stuff much more. So, we devise our own macros... This is
272  * really ugly, use dramamine sparingly. You have been warned.
273  */
274 #define W_SETMASKED(st, val, fun)                               \
275         {                                                       \
276                 int sh = (int)~0;                               \
277                 int mask = fun(sh);                             \
278                                                                 \
279                 for (sh = 0; ((mask >> sh) & 1) == 0; sh++)     \
280                         continue;                               \
281                 *(st) = (*(st) & ~mask) | ((val) << sh);        \
282         }
283
284 #define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
285 #define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
286
287
288 static int JobCondPassSig(void *, void *);
289 static void JobPassSig(int);
290 static int JobPrintCommand(void *, void *);
291 static int JobSaveCommand(void *, void *);
292 static void JobClose(Job *);
293 static void JobFinish(Job *, int *);
294 static void JobExec(Job *, char **);
295 static void JobMakeArgv(Job *, char **);
296 static void JobRestart(Job *);
297 static int JobStart(GNode *, int, Job *);
298 static char *JobOutput(Job *, char *, char *, int);
299 static void JobDoOutput(Job *, Boolean);
300 static Shell *JobMatchShell(const char *);
301 static void JobInterrupt(int, int);
302 static void JobRestartJobs(void);
303
304 /*
305  * JobCatchSignal
306  *
307  * Got a signal. Set global variables and hope that someone will
308  * handle it.
309  */
310 static void
311 JobCatchSig(int signo)
312 {
313
314         interrupted = signo;
315 }
316
317 /*-
318  *-----------------------------------------------------------------------
319  * JobCondPassSig --
320  *      Pass a signal to a job if USE_PGRP is defined.
321  *
322  * Results:
323  *      === 0
324  *
325  * Side Effects:
326  *      None, except the job may bite it.
327  *
328  *-----------------------------------------------------------------------
329  */
330 static int
331 JobCondPassSig(void *jobp, void *signop)
332 {
333     Job *job = jobp;
334     int signo = *(int *)signop;
335
336     DEBUGF(JOB, ("JobCondPassSig passing signal %d to child %d.\n",
337         signo, job->pid));
338     KILL(job->pid, signo);
339     return (0);
340 }
341
342 /*-
343  *-----------------------------------------------------------------------
344  * JobPassSig --
345  *      Pass a signal on to all local jobs if
346  *      USE_PGRP is defined, then die ourselves.
347  *
348  * Results:
349  *      None.
350  *
351  * Side Effects:
352  *      We die by the same signal.
353  *
354  *-----------------------------------------------------------------------
355  */
356 static void
357 JobPassSig(int signo)
358 {
359     sigset_t nmask, omask;
360     struct sigaction act;
361
362     sigemptyset(&nmask);
363     sigaddset(&nmask, signo);
364     sigprocmask(SIG_SETMASK, &nmask, &omask);
365
366     DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
367     Lst_ForEach(&jobs, JobCondPassSig, &signo);
368
369     /*
370      * Deal with proper cleanup based on the signal received. We only run
371      * the .INTERRUPT target if the signal was in fact an interrupt. The other
372      * three termination signals are more of a "get out *now*" command.
373      */
374     if (signo == SIGINT) {
375         JobInterrupt(TRUE, signo);
376     } else if ((signo == SIGHUP) || (signo == SIGTERM) || (signo == SIGQUIT)) {
377         JobInterrupt(FALSE, signo);
378     }
379
380     /*
381      * Leave gracefully if SIGQUIT, rather than core dumping.
382      */
383     if (signo == SIGQUIT) {
384         signo = SIGINT;
385     }
386
387     /*
388      * Send ourselves the signal now we've given the message to everyone else.
389      * Note we block everything else possible while we're getting the signal.
390      * This ensures that all our jobs get continued when we wake up before
391      * we take any other signal.
392      * XXX this comment seems wrong.
393      */
394     act.sa_handler = SIG_DFL;
395     sigemptyset(&act.sa_mask);
396     act.sa_flags = 0;
397     sigaction(signo, &act, NULL);
398
399     DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
400         ~0 & ~(1 << (signo - 1))));
401     signal(signo, SIG_DFL);
402
403     KILL(getpid(), signo);
404
405     signo = SIGCONT;
406     Lst_ForEach(&jobs, JobCondPassSig, &signo);
407
408     sigprocmask(SIG_SETMASK, &omask, NULL);
409     sigprocmask(SIG_SETMASK, &omask, NULL);
410     act.sa_handler = JobPassSig;
411     sigaction(signo, &act, NULL);
412 }
413
414 /*-
415  *-----------------------------------------------------------------------
416  * JobCmpPid  --
417  *      Compare the pid of the job with the given pid and return 0 if they
418  *      are equal. This function is called from Job_CatchChildren via
419  *      Lst_Find to find the job descriptor of the finished job.
420  *
421  * Results:
422  *      0 if the pid's match
423  *
424  * Side Effects:
425  *      None
426  *-----------------------------------------------------------------------
427  */
428 static int
429 JobCmpPid(const void *job, const void *pid)
430 {
431
432     return (*(const int *)pid - ((const Job *)job)->pid);
433 }
434
435 /*-
436  *-----------------------------------------------------------------------
437  * JobPrintCommand  --
438  *      Put out another command for the given job. If the command starts
439  *      with an @ or a - we process it specially. In the former case,
440  *      so long as the -s and -n flags weren't given to make, we stick
441  *      a shell-specific echoOff command in the script. In the latter,
442  *      we ignore errors for the entire job, unless the shell has error
443  *      control.
444  *      If the command is just "..." we take all future commands for this
445  *      job to be commands to be executed once the entire graph has been
446  *      made and return non-zero to signal that the end of the commands
447  *      was reached. These commands are later attached to the postCommands
448  *      node and executed by Job_Finish when all things are done.
449  *      This function is called from JobStart via Lst_ForEach.
450  *
451  * Results:
452  *      Always 0, unless the command was "..."
453  *
454  * Side Effects:
455  *      If the command begins with a '-' and the shell has no error control,
456  *      the JOB_IGNERR flag is set in the job descriptor.
457  *      If the command is "..." and we're not ignoring such things,
458  *      tailCmds is set to the successor node of the cmd.
459  *      numCommands is incremented if the command is actually printed.
460  *-----------------------------------------------------------------------
461  */
462 static int
463 JobPrintCommand(void *cmdp, void *jobp)
464 {
465     Boolean       noSpecials;       /* true if we shouldn't worry about
466                                      * inserting special commands into
467                                      * the input stream. */
468     Boolean       shutUp = FALSE;   /* true if we put a no echo command
469                                      * into the command file */
470     Boolean       errOff = FALSE;   /* true if we turned error checking
471                                      * off before printing the command
472                                      * and need to turn it back on */
473     char          *cmdTemplate;     /* Template to use when printing the
474                                      * command */
475     char          *cmdStart;        /* Start of expanded command */
476     LstNode       *cmdNode;         /* Node for replacing the command */
477     char          *cmd = cmdp;
478     Job           *job = jobp;
479
480     noSpecials = (noExecute && !(job->node->type & OP_MAKE));
481
482     if (strcmp(cmd, "...") == 0) {
483         job->node->type |= OP_SAVE_CMDS;
484         if ((job->flags & JOB_IGNDOTS) == 0) {
485             job->tailCmds = Lst_Succ(Lst_Member(&job->node->commands, cmd));
486             return (1);
487         }
488         return (0);
489     }
490
491 #define DBPRINTF(fmt, arg)                      \
492    DEBUGF(JOB, (fmt, arg));                     \
493     fprintf(job->cmdFILE, fmt, arg);    \
494     fflush(job->cmdFILE);
495
496     numCommands += 1;
497
498     /*
499      * For debugging, we replace each command with the result of expanding
500      * the variables in the command.
501      */
502     cmdNode = Lst_Member(&job->node->commands, cmd);
503     cmdStart = cmd = Var_Subst(NULL, cmd, job->node, FALSE);
504     Lst_Replace(cmdNode, cmdStart);
505
506     cmdTemplate = "%s\n";
507
508     /*
509      * Check for leading @', -' or +'s to control echoing, error checking,
510      * and execution on -n.
511      */
512     while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
513         switch (*cmd) {
514
515           case '@':
516             shutUp = DEBUG(LOUD) ? FALSE : TRUE;
517             break;
518
519           case '-':
520             errOff = TRUE;
521             break;
522
523           case '+':
524             if (noSpecials) {
525                 /*
526                  * We're not actually exececuting anything...
527                  * but this one needs to be - use compat mode just for it.
528                  */
529                 Compat_RunCommand(cmdp, job->node);
530                 return (0);
531             }
532             break;
533         }
534         cmd++;
535     }
536
537     while (isspace((unsigned char)*cmd))
538         cmd++;
539
540     if (shutUp) {
541         if (!(job->flags & JOB_SILENT) && !noSpecials &&
542             commandShell->hasEchoCtl) {
543                 DBPRINTF("%s\n", commandShell->echoOff);
544         } else {
545             shutUp = FALSE;
546         }
547     }
548
549     if (errOff) {
550         if ( !(job->flags & JOB_IGNERR) && !noSpecials) {
551             if (commandShell->hasErrCtl) {
552                 /*
553                  * we don't want the error-control commands showing
554                  * up either, so we turn off echoing while executing
555                  * them. We could put another field in the shell
556                  * structure to tell JobDoOutput to look for this
557                  * string too, but why make it any more complex than
558                  * it already is?
559                  */
560                 if (!(job->flags & JOB_SILENT) && !shutUp &&
561                     commandShell->hasEchoCtl) {
562                         DBPRINTF("%s\n", commandShell->echoOff);
563                         DBPRINTF("%s\n", commandShell->ignErr);
564                         DBPRINTF("%s\n", commandShell->echoOn);
565                 } else {
566                     DBPRINTF("%s\n", commandShell->ignErr);
567                 }
568             } else if (commandShell->ignErr &&
569                       (*commandShell->ignErr != '\0'))
570             {
571                 /*
572                  * The shell has no error control, so we need to be
573                  * weird to get it to ignore any errors from the command.
574                  * If echoing is turned on, we turn it off and use the
575                  * errCheck template to echo the command. Leave echoing
576                  * off so the user doesn't see the weirdness we go through
577                  * to ignore errors. Set cmdTemplate to use the weirdness
578                  * instead of the simple "%s\n" template.
579                  */
580                 if (!(job->flags & JOB_SILENT) && !shutUp &&
581                     commandShell->hasEchoCtl) {
582                         DBPRINTF("%s\n", commandShell->echoOff);
583                         DBPRINTF(commandShell->errCheck, cmd);
584                         shutUp = TRUE;
585                 }
586                 cmdTemplate = commandShell->ignErr;
587                 /*
588                  * The error ignoration (hee hee) is already taken care
589                  * of by the ignErr template, so pretend error checking
590                  * is still on.
591                  */
592                 errOff = FALSE;
593             } else {
594                 errOff = FALSE;
595             }
596         } else {
597             errOff = FALSE;
598         }
599     }
600
601     DBPRINTF(cmdTemplate, cmd);
602
603     if (errOff) {
604         /*
605          * If echoing is already off, there's no point in issuing the
606          * echoOff command. Otherwise we issue it and pretend it was on
607          * for the whole command...
608          */
609         if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl) {
610             DBPRINTF("%s\n", commandShell->echoOff);
611             shutUp = TRUE;
612         }
613         DBPRINTF("%s\n", commandShell->errCheck);
614     }
615     if (shutUp) {
616         DBPRINTF("%s\n", commandShell->echoOn);
617     }
618     return (0);
619 }
620
621 /*-
622  *-----------------------------------------------------------------------
623  * JobSaveCommand --
624  *      Save a command to be executed when everything else is done.
625  *      Callback function for JobFinish...
626  *
627  * Results:
628  *      Always returns 0
629  *
630  * Side Effects:
631  *      The command is tacked onto the end of postCommands's commands list.
632  *
633  *-----------------------------------------------------------------------
634  */
635 static int
636 JobSaveCommand(void *cmd, void *gn)
637 {
638
639     cmd = Var_Subst(NULL, cmd, gn, FALSE);
640     Lst_AtEnd(&postCommands->commands, cmd);
641     return (0);
642 }
643
644
645 /*-
646  *-----------------------------------------------------------------------
647  * JobClose --
648  *      Called to close both input and output pipes when a job is finished.
649  *
650  * Results:
651  *      Nada
652  *
653  * Side Effects:
654  *      The file descriptors associated with the job are closed.
655  *
656  *-----------------------------------------------------------------------
657  */
658 static void
659 JobClose(Job *job)
660 {
661
662     if (usePipes) {
663 #if !defined(USE_KQUEUE)
664         FD_CLR(job->inPipe, &outputs);
665 #endif
666         if (job->outPipe != job->inPipe) {
667            close(job->outPipe);
668         }
669         JobDoOutput(job, TRUE);
670         close(job->inPipe);
671     } else {
672         close(job->outFd);
673         JobDoOutput(job, TRUE);
674     }
675 }
676
677 /*-
678  *-----------------------------------------------------------------------
679  * JobFinish  --
680  *      Do final processing for the given job including updating
681  *      parents and starting new jobs as available/necessary. Note
682  *      that we pay no attention to the JOB_IGNERR flag here.
683  *      This is because when we're called because of a noexecute flag
684  *      or something, jstat.w_status is 0 and when called from
685  *      Job_CatchChildren, the status is zeroed if it s/b ignored.
686  *
687  * Results:
688  *      None
689  *
690  * Side Effects:
691  *      Some nodes may be put on the toBeMade queue.
692  *      Final commands for the job are placed on postCommands.
693  *
694  *      If we got an error and are aborting (aborting == ABORT_ERROR) and
695  *      the job list is now empty, we are done for the day.
696  *      If we recognized an error (errors !=0), we set the aborting flag
697  *      to ABORT_ERROR so no more jobs will be started.
698  *-----------------------------------------------------------------------
699  */
700 /*ARGSUSED*/
701 static void
702 JobFinish(Job *job, int *status)
703 {
704     Boolean      done;
705
706     if ((WIFEXITED(*status) &&
707          (((WEXITSTATUS(*status) != 0) && !(job->flags & JOB_IGNERR)))) ||
708         (WIFSIGNALED(*status) && (WTERMSIG(*status) != SIGCONT)))
709     {
710         /*
711          * If it exited non-zero and either we're doing things our
712          * way or we're not ignoring errors, the job is finished.
713          * Similarly, if the shell died because of a signal
714          * the job is also finished. In these
715          * cases, finish out the job's output before printing the exit
716          * status...
717          */
718         JobClose(job);
719         if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
720             fclose(job->cmdFILE);
721         }
722         done = TRUE;
723     } else if (WIFEXITED(*status)) {
724         /*
725          * Deal with ignored errors in -B mode. We need to print a message
726          * telling of the ignored error as well as setting status.w_status
727          * to 0 so the next command gets run. To do this, we set done to be
728          * TRUE if in -B mode and the job exited non-zero.
729          */
730         done = WEXITSTATUS(*status) != 0;
731         /*
732          * Old comment said: "Note we don't
733          * want to close down any of the streams until we know we're at the
734          * end."
735          * But we do. Otherwise when are we going to print the rest of the
736          * stuff?
737          */
738         JobClose(job);
739     } else {
740         /*
741          * No need to close things down or anything.
742          */
743         done = FALSE;
744     }
745
746     if (done ||
747         WIFSTOPPED(*status) ||
748         (WIFSIGNALED(*status) && (WTERMSIG(*status) == SIGCONT)) ||
749         DEBUG(JOB))
750     {
751         FILE      *out;
752
753         if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
754             /*
755              * If output is going to a file and this job is ignoring
756              * errors, arrange to have the exit status sent to the
757              * output file as well.
758              */
759             out = fdopen(job->outFd, "w");
760             if (out == NULL)
761                 Punt("Cannot fdopen");
762         } else {
763             out = stdout;
764         }
765
766         if (WIFEXITED(*status)) {
767             DEBUGF(JOB, ("Process %d exited.\n", job->pid));
768             if (WEXITSTATUS(*status) != 0) {
769                 if (usePipes && job->node != lastNode) {
770                     MESSAGE(out, job->node);
771                     lastNode = job->node;
772                 }
773                  fprintf(out, "*** Error code %d%s\n",
774                                WEXITSTATUS(*status),
775                                (job->flags & JOB_IGNERR) ? "(ignored)" : "");
776
777                 if (job->flags & JOB_IGNERR) {
778                     *status = 0;
779                 }
780             } else if (DEBUG(JOB)) {
781                 if (usePipes && job->node != lastNode) {
782                     MESSAGE(out, job->node);
783                     lastNode = job->node;
784                 }
785                 fprintf(out, "*** Completed successfully\n");
786             }
787         } else if (WIFSTOPPED(*status)) {
788             DEBUGF(JOB, ("Process %d stopped.\n", job->pid));
789             if (usePipes && job->node != lastNode) {
790                 MESSAGE(out, job->node);
791                 lastNode = job->node;
792             }
793             fprintf(out, "*** Stopped -- signal %d\n",
794                 WSTOPSIG(*status));
795             job->flags |= JOB_RESUME;
796             Lst_AtEnd(&stoppedJobs, job);
797             fflush(out);
798             return;
799         } else if (WTERMSIG(*status) == SIGCONT) {
800             /*
801              * If the beastie has continued, shift the Job from the stopped
802              * list to the running one (or re-stop it if concurrency is
803              * exceeded) and go and get another child.
804              */
805             if (job->flags & (JOB_RESUME|JOB_RESTART)) {
806                 if (usePipes && job->node != lastNode) {
807                     MESSAGE(out, job->node);
808                     lastNode = job->node;
809                 }
810                  fprintf(out, "*** Continued\n");
811             }
812             if (!(job->flags & JOB_CONTINUING)) {
813                 DEBUGF(JOB, ("Warning: process %d was not continuing.\n", job->pid));
814 #ifdef notdef
815                 /*
816                  * We don't really want to restart a job from scratch just
817                  * because it continued, especially not without killing the
818                  * continuing process!  That's why this is ifdef'ed out.
819                  * FD - 9/17/90
820                  */
821                 JobRestart(job);
822 #endif
823             }
824             job->flags &= ~JOB_CONTINUING;
825             Lst_AtEnd(&jobs, job);
826             nJobs += 1;
827             DEBUGF(JOB, ("Process %d is continuing locally.\n", job->pid));
828             if (nJobs == maxJobs) {
829                 jobFull = TRUE;
830                 DEBUGF(JOB, ("Job queue is full.\n"));
831             }
832             fflush(out);
833             return;
834         } else {
835             if (usePipes && job->node != lastNode) {
836                 MESSAGE(out, job->node);
837                 lastNode = job->node;
838             }
839             fprintf(out, "*** Signal %d\n", WTERMSIG(*status));
840         }
841
842         fflush(out);
843     }
844
845     /*
846      * Now handle the -B-mode stuff. If the beast still isn't finished,
847      * try and restart the job on the next command. If JobStart says it's
848      * ok, it's ok. If there's an error, this puppy is done.
849      */
850     if (compatMake && WIFEXITED(*status) &&
851         Lst_Succ(job->node->compat_command) != NULL) {
852         switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
853         case JOB_RUNNING:
854             done = FALSE;
855             break;
856         case JOB_ERROR:
857             done = TRUE;
858             W_SETEXITSTATUS(status, 1);
859             break;
860         case JOB_FINISHED:
861             /*
862              * If we got back a JOB_FINISHED code, JobStart has already
863              * called Make_Update and freed the job descriptor. We set
864              * done to false here to avoid fake cycles and double frees.
865              * JobStart needs to do the update so we can proceed up the
866              * graph when given the -n flag..
867              */
868             done = FALSE;
869             break;
870         default:
871             break;
872         }
873     } else {
874         done = TRUE;
875     }
876
877
878     if (done &&
879         (aborting != ABORT_ERROR) &&
880         (aborting != ABORT_INTERRUPT) &&
881         (*status == 0))
882     {
883         /*
884          * As long as we aren't aborting and the job didn't return a non-zero
885          * status that we shouldn't ignore, we call Make_Update to update
886          * the parents. In addition, any saved commands for the node are placed
887          * on the .END target.
888          */
889         if (job->tailCmds != NULL) {
890             Lst_ForEachFrom(&job->node->commands, job->tailCmds,
891                 JobSaveCommand, job->node);
892         }
893         job->node->made = MADE;
894         Make_Update(job->node);
895         free(job);
896     } else if (*status != 0) {
897         errors += 1;
898         free(job);
899     }
900
901     JobRestartJobs();
902
903     /*
904      * Set aborting if any error.
905      */
906     if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
907         /*
908          * If we found any errors in this batch of children and the -k flag
909          * wasn't given, we set the aborting flag so no more jobs get
910          * started.
911          */
912         aborting = ABORT_ERROR;
913     }
914
915     if ((aborting == ABORT_ERROR) && Job_Empty())
916         /*
917          * If we are aborting and the job table is now empty, we finish.
918          */
919         Finish(errors);
920 }
921
922 /*-
923  *-----------------------------------------------------------------------
924  * Job_Touch --
925  *      Touch the given target. Called by JobStart when the -t flag was
926  *      given.  Prints messages unless told to be silent.
927  *
928  * Results:
929  *      None
930  *
931  * Side Effects:
932  *      The data modification of the file is changed. In addition, if the
933  *      file did not exist, it is created.
934  *-----------------------------------------------------------------------
935  */
936 void
937 Job_Touch(GNode *gn, Boolean silent)
938 {
939     int           streamID;     /* ID of stream opened to do the touch */
940     struct utimbuf times;       /* Times for utime() call */
941
942     if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
943         /*
944          * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets
945          * and, as such, shouldn't really be created.
946          */
947         return;
948     }
949
950     if (!silent) {
951          fprintf(stdout, "touch %s\n", gn->name);
952          fflush(stdout);
953     }
954
955     if (noExecute) {
956         return;
957     }
958
959     if (gn->type & OP_ARCHV) {
960         Arch_Touch(gn);
961     } else if (gn->type & OP_LIB) {
962         Arch_TouchLib(gn);
963     } else {
964         char    *file = gn->path ? gn->path : gn->name;
965
966         times.actime = times.modtime = now;
967         if (utime(file, &times) < 0){
968             streamID = open(file, O_RDWR | O_CREAT, 0666);
969
970             if (streamID >= 0) {
971                 char    c;
972
973                 /*
974                  * Read and write a byte to the file to change the
975                  * modification time, then close the file.
976                  */
977                 if (read(streamID, &c, 1) == 1) {
978                      lseek(streamID, (off_t)0, SEEK_SET);
979                     write(streamID, &c, 1);
980                 }
981
982                 close(streamID);
983             } else {
984                  fprintf(stdout, "*** couldn't touch %s: %s",
985                                file, strerror(errno));
986                  fflush(stdout);
987             }
988         }
989     }
990 }
991
992 /*-
993  *-----------------------------------------------------------------------
994  * Job_CheckCommands --
995  *      Make sure the given node has all the commands it needs.
996  *
997  * Results:
998  *      TRUE if the commands list is/was ok.
999  *
1000  * Side Effects:
1001  *      The node will have commands from the .DEFAULT rule added to it
1002  *      if it needs them.
1003  *-----------------------------------------------------------------------
1004  */
1005 Boolean
1006 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1007 {
1008
1009     if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
1010         (gn->type & OP_LIB) == 0) {
1011         /*
1012          * No commands. Look for .DEFAULT rule from which we might infer
1013          * commands
1014          */
1015         if ((DEFAULT != NULL) && !Lst_IsEmpty(&DEFAULT->commands)) {
1016             char *p1;
1017             /*
1018              * Make only looks for a .DEFAULT if the node was never the
1019              * target of an operator, so that's what we do too. If
1020              * a .DEFAULT was given, we substitute its commands for gn's
1021              * commands and set the IMPSRC variable to be the target's name
1022              * The DEFAULT node acts like a transformation rule, in that
1023              * gn also inherits any attributes or sources attached to
1024              * .DEFAULT itself.
1025              */
1026             Make_HandleUse(DEFAULT, gn);
1027             Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn);
1028             free(p1);
1029         } else if (Dir_MTime(gn) == 0) {
1030             /*
1031              * The node wasn't the target of an operator we have no .DEFAULT
1032              * rule to go on and the target doesn't already exist. There's
1033              * nothing more we can do for this branch. If the -k flag wasn't
1034              * given, we stop in our tracks, otherwise we just don't update
1035              * this node's parents so they never get examined.
1036              */
1037             static const char msg[] = "make: don't know how to make";
1038
1039             if (gn->type & OP_OPTIONAL) {
1040                  fprintf(stdout, "%s %s(ignored)\n", msg, gn->name);
1041                  fflush(stdout);
1042             } else if (keepgoing) {
1043                  fprintf(stdout, "%s %s(continuing)\n", msg, gn->name);
1044                  fflush(stdout);
1045                  return (FALSE);
1046             } else {
1047 #if OLD_JOKE
1048                 if (strcmp(gn->name,"love") == 0)
1049                     (*abortProc)("Not war.");
1050                 else
1051 #endif
1052                     (*abortProc)("%s %s. Stop", msg, gn->name);
1053                 return (FALSE);
1054             }
1055         }
1056     }
1057     return (TRUE);
1058 }
1059
1060 /*-
1061  *-----------------------------------------------------------------------
1062  * JobExec --
1063  *      Execute the shell for the given job. Called from JobStart and
1064  *      JobRestart.
1065  *
1066  * Results:
1067  *      None.
1068  *
1069  * Side Effects:
1070  *      A shell is executed, outputs is altered and the Job structure added
1071  *      to the job table.
1072  *
1073  *-----------------------------------------------------------------------
1074  */
1075 static void
1076 JobExec(Job *job, char **argv)
1077 {
1078     int           cpid;         /* ID of new child */
1079
1080     if (DEBUG(JOB)) {
1081         int       i;
1082
1083         DEBUGF(JOB, ("Running %s\n", job->node->name));
1084         DEBUGF(JOB, ("\tCommand: "));
1085         for (i = 0; argv[i] != NULL; i++) {
1086             DEBUGF(JOB, ("%s ", argv[i]));
1087         }
1088         DEBUGF(JOB, ("\n"));
1089     }
1090
1091     /*
1092      * Some jobs produce no output and it's disconcerting to have
1093      * no feedback of their running (since they produce no output, the
1094      * banner with their name in it never appears). This is an attempt to
1095      * provide that feedback, even if nothing follows it.
1096      */
1097     if ((lastNode != job->node) && (job->flags & JOB_FIRST) &&
1098         !(job->flags & JOB_SILENT)) {
1099         MESSAGE(stdout, job->node);
1100         lastNode = job->node;
1101     }
1102
1103     if ((cpid = vfork()) == -1) {
1104         Punt("Cannot fork");
1105     } else if (cpid == 0) {
1106
1107         if (fifoFd >= 0)
1108             close(fifoFd);
1109         /*
1110          * Must duplicate the input stream down to the child's input and
1111          * reset it to the beginning (again). Since the stream was marked
1112          * close-on-exec, we must clear that bit in the new input.
1113          */
1114         if (dup2(FILENO(job->cmdFILE), 0) == -1)
1115             Punt("Cannot dup2: %s", strerror(errno));
1116         fcntl(0, F_SETFD, 0);
1117         lseek(0, (off_t)0, SEEK_SET);
1118
1119         if (usePipes) {
1120             /*
1121              * Set up the child's output to be routed through the pipe
1122              * we've created for it.
1123              */
1124             if (dup2(job->outPipe, 1) == -1)
1125                 Punt("Cannot dup2: %s", strerror(errno));
1126         } else {
1127             /*
1128              * We're capturing output in a file, so we duplicate the
1129              * descriptor to the temporary file into the standard
1130              * output.
1131              */
1132             if (dup2(job->outFd, 1) == -1)
1133                 Punt("Cannot dup2: %s", strerror(errno));
1134         }
1135         /*
1136          * The output channels are marked close on exec. This bit was
1137          * duplicated by the dup2 (on some systems), so we have to clear
1138          * it before routing the shell's error output to the same place as
1139          * its standard output.
1140          */
1141         fcntl(1, F_SETFD, 0);
1142         if (dup2(1, 2) == -1)
1143             Punt("Cannot dup2: %s", strerror(errno));
1144
1145 #ifdef USE_PGRP
1146         /*
1147          * We want to switch the child into a different process family so
1148          * we can kill it and all its descendants in one fell swoop,
1149          * by killing its process family, but not commit suicide.
1150          */
1151 # if defined(SYSV)
1152         setsid();
1153 # else
1154         setpgid(0, getpid());
1155 # endif
1156 #endif /* USE_PGRP */
1157
1158         execv(shellPath, argv);
1159
1160         write(STDERR_FILENO, "Could not execute shell\n",
1161                      sizeof("Could not execute shell"));
1162         _exit(1);
1163     } else {
1164         job->pid = cpid;
1165
1166         if (usePipes && (job->flags & JOB_FIRST) ) {
1167             /*
1168              * The first time a job is run for a node, we set the current
1169              * position in the buffer to the beginning and mark another
1170              * stream to watch in the outputs mask
1171              */
1172 #ifdef USE_KQUEUE
1173             struct kevent       kev[2];
1174 #endif
1175             job->curPos = 0;
1176
1177 #if defined(USE_KQUEUE)
1178             EV_SET(&kev[0], job->inPipe, EVFILT_READ, EV_ADD, 0, 0, job);
1179             EV_SET(&kev[1], job->pid, EVFILT_PROC, EV_ADD | EV_ONESHOT,
1180                 NOTE_EXIT, 0, NULL);
1181             if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1182                 /* kevent() will fail if the job is already finished */
1183                 if (errno != EINTR && errno != EBADF && errno != ESRCH)
1184                     Punt("kevent: %s", strerror(errno));
1185             }
1186 #else
1187             FD_SET(job->inPipe, &outputs);
1188 #endif /* USE_KQUEUE */
1189         }
1190
1191         if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1192             fclose(job->cmdFILE);
1193             job->cmdFILE = NULL;
1194         }
1195     }
1196
1197     /*
1198      * Now the job is actually running, add it to the table.
1199      */
1200     nJobs += 1;
1201     Lst_AtEnd(&jobs, job);
1202     if (nJobs == maxJobs) {
1203         jobFull = TRUE;
1204     }
1205 }
1206
1207 /*-
1208  *-----------------------------------------------------------------------
1209  * JobMakeArgv --
1210  *      Create the argv needed to execute the shell for a given job.
1211  *
1212  *
1213  * Results:
1214  *
1215  * Side Effects:
1216  *
1217  *-----------------------------------------------------------------------
1218  */
1219 static void
1220 JobMakeArgv(Job *job, char **argv)
1221 {
1222     int           argc;
1223     static char   args[10];     /* For merged arguments */
1224
1225     argv[0] = shellName;
1226     argc = 1;
1227
1228     if ((commandShell->exit && (*commandShell->exit != '-')) ||
1229         (commandShell->echo && (*commandShell->echo != '-')))
1230     {
1231         /*
1232          * At least one of the flags doesn't have a minus before it, so
1233          * merge them together. Have to do this because the *(&(@*#*&#$#
1234          * Bourne shell thinks its second argument is a file to source.
1235          * Grrrr. Note the ten-character limitation on the combined arguments.
1236          */
1237         sprintf(args, "-%s%s",
1238                       ((job->flags & JOB_IGNERR) ? "" :
1239                        (commandShell->exit ? commandShell->exit : "")),
1240                       ((job->flags & JOB_SILENT) ? "" :
1241                        (commandShell->echo ? commandShell->echo : "")));
1242
1243         if (args[1]) {
1244             argv[argc] = args;
1245             argc++;
1246         }
1247     } else {
1248         if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1249             argv[argc] = commandShell->exit;
1250             argc++;
1251         }
1252         if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1253             argv[argc] = commandShell->echo;
1254             argc++;
1255         }
1256     }
1257     argv[argc] = NULL;
1258 }
1259
1260 /*-
1261  *-----------------------------------------------------------------------
1262  * JobRestart --
1263  *      Restart a job that stopped for some reason.
1264  *
1265  * Results:
1266  *      None.
1267  *
1268  * Side Effects:
1269  *      jobFull will be set if the job couldn't be run.
1270  *
1271  *-----------------------------------------------------------------------
1272  */
1273 static void
1274 JobRestart(Job *job)
1275 {
1276
1277     if (job->flags & JOB_RESTART) {
1278         /*
1279          * Set up the control arguments to the shell. This is based on the
1280          * flags set earlier for this job. If the JOB_IGNERR flag is clear,
1281          * the 'exit' flag of the commandShell is used to cause it to exit
1282          * upon receiving an error. If the JOB_SILENT flag is clear, the
1283          * 'echo' flag of the commandShell is used to get it to start echoing
1284          * as soon as it starts processing commands.
1285          */
1286         char      *argv[4];
1287
1288         JobMakeArgv(job, argv);
1289
1290         DEBUGF(JOB, ("Restarting %s...", job->node->name));
1291         if (((nJobs >= maxJobs) && !(job->flags & JOB_SPECIAL))) {
1292             /*
1293              * Can't be exported and not allowed to run locally -- put it
1294              * back on the hold queue and mark the table full
1295              */
1296             DEBUGF(JOB, ("holding\n"));
1297             Lst_AtFront(&stoppedJobs, (void *)job);
1298             jobFull = TRUE;
1299             DEBUGF(JOB, ("Job queue is full.\n"));
1300             return;
1301         } else {
1302             /*
1303              * Job may be run locally.
1304              */
1305             DEBUGF(JOB, ("running locally\n"));
1306         }
1307         JobExec(job, argv);
1308     } else {
1309         /*
1310          * The job has stopped and needs to be restarted. Why it stopped,
1311          * we don't know...
1312          */
1313         DEBUGF(JOB, ("Resuming %s...", job->node->name));
1314         if (((nJobs < maxJobs) ||
1315             ((job->flags & JOB_SPECIAL) &&
1316              (maxJobs == 0))) &&
1317            (nJobs != maxJobs))
1318         {
1319             /*
1320              * If we haven't reached the concurrency limit already (or the
1321              * job must be run and maxJobs is 0), it's ok to resume it.
1322              */
1323             Boolean error;
1324             int status;
1325
1326             error = (KILL(job->pid, SIGCONT) != 0);
1327
1328             if (!error) {
1329                 /*
1330                  * Make sure the user knows we've continued the beast and
1331                  * actually put the thing in the job table.
1332                  */
1333                 job->flags |= JOB_CONTINUING;
1334                 W_SETTERMSIG(&status, SIGCONT);
1335                 JobFinish(job, &status);
1336
1337                 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1338                 DEBUGF(JOB, ("done\n"));
1339             } else {
1340                 Error("couldn't resume %s: %s",
1341                     job->node->name, strerror(errno));
1342                 status = 0;
1343                 W_SETEXITSTATUS(&status, 1);
1344                 JobFinish(job, &status);
1345             }
1346         } else {
1347             /*
1348              * Job cannot be restarted. Mark the table as full and
1349              * place the job back on the list of stopped jobs.
1350              */
1351             DEBUGF(JOB, ("table full\n"));
1352             Lst_AtFront(&stoppedJobs, (void *)job);
1353             jobFull = TRUE;
1354             DEBUGF(JOB, ("Job queue is full.\n"));
1355         }
1356     }
1357 }
1358
1359 /*-
1360  *-----------------------------------------------------------------------
1361  * JobStart  --
1362  *      Start a target-creation process going for the target described
1363  *      by the graph node gn.
1364  *
1365  * Results:
1366  *      JOB_ERROR if there was an error in the commands, JOB_FINISHED
1367  *      if there isn't actually anything left to do for the job and
1368  *      JOB_RUNNING if the job has been started.
1369  *
1370  * Side Effects:
1371  *      A new Job node is created and added to the list of running
1372  *      jobs. PMake is forked and a child shell created.
1373  *-----------------------------------------------------------------------
1374  */
1375 static int
1376 JobStart(GNode *gn, int flags, Job *previous)
1377 {
1378     Job           *job;       /* new job descriptor */
1379     char          *argv[4];   /* Argument vector to shell */
1380     Boolean       cmdsOK;     /* true if the nodes commands were all right */
1381     Boolean       noExec;     /* Set true if we decide not to run the job */
1382     int           tfd;        /* File descriptor for temp file */
1383
1384     if (interrupted) {
1385         JobPassSig(interrupted);
1386         return (JOB_ERROR);
1387     }
1388     if (previous != NULL) {
1389         previous->flags &= ~(JOB_FIRST|JOB_IGNERR|JOB_SILENT);
1390         job = previous;
1391     } else {
1392         job = emalloc(sizeof(Job));
1393         flags |= JOB_FIRST;
1394     }
1395
1396     job->node = gn;
1397     job->tailCmds = NULL;
1398
1399     /*
1400      * Set the initial value of the flags for this job based on the global
1401      * ones and the node's attributes... Any flags supplied by the caller
1402      * are also added to the field.
1403      */
1404     job->flags = 0;
1405     if (Targ_Ignore(gn)) {
1406         job->flags |= JOB_IGNERR;
1407     }
1408     if (Targ_Silent(gn)) {
1409         job->flags |= JOB_SILENT;
1410     }
1411     job->flags |= flags;
1412
1413     /*
1414      * Check the commands now so any attributes from .DEFAULT have a chance
1415      * to migrate to the node
1416      */
1417     if (!compatMake && job->flags & JOB_FIRST) {
1418         cmdsOK = Job_CheckCommands(gn, Error);
1419     } else {
1420         cmdsOK = TRUE;
1421     }
1422
1423     /*
1424      * If the -n flag wasn't given, we open up OUR (not the child's)
1425      * temporary file to stuff commands in it. The thing is rd/wr so we don't
1426      * need to reopen it to feed it to the shell. If the -n flag *was* given,
1427      * we just set the file to be stdout. Cute, huh?
1428      */
1429     if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1430         /*
1431          * We're serious here, but if the commands were bogus, we're
1432          * also dead...
1433          */
1434         if (!cmdsOK) {
1435             DieHorribly();
1436         }
1437
1438         strcpy(tfile, TMPPAT);
1439         if ((tfd = mkstemp(tfile)) == -1)
1440             Punt("Cannot create temp file: %s", strerror(errno));
1441         job->cmdFILE = fdopen(tfd, "w+");
1442         eunlink(tfile);
1443         if (job->cmdFILE == NULL) {
1444             close(tfd);
1445             Punt("Could not open %s", tfile);
1446         }
1447         fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1448         /*
1449          * Send the commands to the command file, flush all its buffers then
1450          * rewind and remove the thing.
1451          */
1452         noExec = FALSE;
1453
1454         /*
1455          * used to be backwards; replace when start doing multiple commands
1456          * per shell.
1457          */
1458         if (compatMake) {
1459             /*
1460              * Be compatible: If this is the first time for this node,
1461              * verify its commands are ok and open the commands list for
1462              * sequential access by later invocations of JobStart.
1463              * Once that is done, we take the next command off the list
1464              * and print it to the command file. If the command was an
1465              * ellipsis, note that there's nothing more to execute.
1466              */
1467             if (job->flags & JOB_FIRST)
1468                 gn->compat_command = Lst_First(&gn->commands);
1469             else
1470                 gn->compat_command = Lst_Succ(gn->compat_command);
1471
1472             if (gn->compat_command == NULL ||
1473                 JobPrintCommand(Lst_Datum(gn->compat_command), job))
1474                 noExec = TRUE;
1475
1476             if (noExec && !(job->flags & JOB_FIRST)) {
1477                 /*
1478                  * If we're not going to execute anything, the job
1479                  * is done and we need to close down the various
1480                  * file descriptors we've opened for output, then
1481                  * call JobDoOutput to catch the final characters or
1482                  * send the file to the screen... Note that the i/o streams
1483                  * are only open if this isn't the first job.
1484                  * Note also that this could not be done in
1485                  * Job_CatchChildren b/c it wasn't clear if there were
1486                  * more commands to execute or not...
1487                  */
1488                  JobClose(job);
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         for (ln = Lst_First(&jobs); nfds != 0 && ln != NULL; ln = Lst_Succ(ln)){
2036             job = Lst_Datum(ln);
2037             if (FD_ISSET(job->inPipe, &readfds)) {
2038                 JobDoOutput(job, FALSE);
2039                 nfds -= 1;
2040             }
2041         }
2042 #endif /* !USE_KQUEUE */
2043     }
2044 }
2045
2046 /*-
2047  *-----------------------------------------------------------------------
2048  * Job_Make --
2049  *      Start the creation of a target. Basically a front-end for
2050  *      JobStart used by the Make module.
2051  *
2052  * Results:
2053  *      None.
2054  *
2055  * Side Effects:
2056  *      Another job is started.
2057  *
2058  *-----------------------------------------------------------------------
2059  */
2060 void
2061 Job_Make(GNode *gn)
2062 {
2063
2064      JobStart(gn, 0, NULL);
2065 }
2066
2067 /*
2068  * JobCopyShell:
2069  *
2070  * Make a new copy of the shell structure including a copy of the strings
2071  * in it. This also defaults some fields in case they are NULL.
2072  *
2073  * The function returns a pointer to the new shell structure otherwise.
2074  */
2075 static Shell *
2076 JobCopyShell(const Shell *osh)
2077 {
2078         Shell *nsh;
2079
2080         nsh = emalloc(sizeof(*nsh));
2081         nsh->name = estrdup(osh->name);
2082
2083         if (osh->echoOff != NULL)
2084                 nsh->echoOff = estrdup(osh->echoOff);
2085         else
2086                 nsh->echoOff = NULL;
2087         if (osh->echoOn != NULL)
2088                 nsh->echoOn = estrdup(osh->echoOn);
2089         else
2090                 nsh->echoOn = NULL;
2091         nsh->hasEchoCtl = osh->hasEchoCtl;
2092
2093         if (osh->noPrint != NULL)
2094                 nsh->noPrint = estrdup(osh->noPrint);
2095         else
2096                 nsh->noPrint = NULL;
2097         nsh->noPLen = osh->noPLen;
2098
2099         nsh->hasErrCtl = osh->hasErrCtl;
2100         if (osh->errCheck == NULL)
2101                 nsh->errCheck = estrdup("");
2102         else
2103                 nsh->errCheck = estrdup(osh->errCheck);
2104         if (osh->ignErr == NULL)
2105                 nsh->ignErr = estrdup("%s");
2106         else
2107                 nsh->ignErr = estrdup(osh->ignErr);
2108
2109         if (osh->echo == NULL)
2110                 nsh->echo = estrdup("");
2111         else
2112                 nsh->echo = estrdup(osh->echo);
2113
2114         if (osh->exit == NULL)
2115                 nsh->exit = estrdup("");
2116         else
2117                 nsh->exit = estrdup(osh->exit);
2118
2119         return (nsh);
2120 }
2121
2122 /*
2123  * JobFreeShell:
2124  *
2125  * Free a shell structure and all associated strings.
2126  */
2127 static void
2128 JobFreeShell(Shell *sh)
2129 {
2130
2131         if (sh != NULL) {
2132                 free(sh->name);
2133                 free(sh->echoOff);
2134                 free(sh->echoOn);
2135                 free(sh->noPrint);
2136                 free(sh->errCheck);
2137                 free(sh->ignErr);
2138                 free(sh->echo);
2139                 free(sh->exit);
2140                 free(sh);
2141         }
2142 }
2143
2144 void
2145 Shell_Init(void)
2146 {
2147
2148     if (commandShell == NULL)
2149         commandShell = JobMatchShell(shells[DEFSHELL].name);
2150
2151     if (shellPath == NULL) {
2152         /*
2153          * The user didn't specify a shell to use, so we are using the
2154          * default one... Both the absolute path and the last component
2155          * must be set. The last component is taken from the 'name' field
2156          * of the default shell description pointed-to by commandShell.
2157          * All default shells are located in _PATH_DEFSHELLDIR.
2158          */
2159         shellName = commandShell->name;
2160         shellPath = str_concat(_PATH_DEFSHELLDIR, shellName, STR_ADDSLASH);
2161     }
2162 }
2163
2164 /*-
2165  *-----------------------------------------------------------------------
2166  * Job_Init --
2167  *      Initialize the process module, given a maximum number of jobs.
2168  *
2169  * Results:
2170  *      none
2171  *
2172  * Side Effects:
2173  *      lists and counters are initialized
2174  *-----------------------------------------------------------------------
2175  */
2176 void
2177 Job_Init(int maxproc)
2178 {
2179     GNode         *begin;     /* node for commands to do at the very start */
2180     const char    *env;
2181     struct sigaction sa;
2182
2183     fifoFd = -1;
2184     env = getenv("MAKE_JOBS_FIFO");
2185
2186     if (env == NULL && maxproc > 1) {
2187         /*
2188          * We did not find the environment variable so we are the leader.
2189          * Create the fifo, open it, write one char per allowed job into
2190          * the pipe.
2191          */
2192         mktemp(fifoName);
2193         if (!mkfifo(fifoName, 0600)) {
2194             fifoFd = open(fifoName, O_RDWR | O_NONBLOCK, 0);
2195             if (fifoFd >= 0) {
2196                 fifoMaster = 1;
2197                 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2198                 env = fifoName;
2199                 setenv("MAKE_JOBS_FIFO", env, 1);
2200                 while (maxproc-- > 0) {
2201                     write(fifoFd, "+", 1);
2202                 }
2203                 /* The master make does not get a magic token */
2204                 jobFull = TRUE;
2205                 maxJobs = 0;
2206             } else {
2207                 unlink(fifoName);
2208                 env = NULL;
2209             }
2210         }
2211     } else if (env != NULL) {
2212         /*
2213          * We had the environment variable so we are a slave.
2214          * Open fifo and give ourselves a magic token which represents
2215          * the token our parent make has grabbed to start his make process.
2216          * Otherwise the sub-makes would gobble up tokens and the proper
2217          * number of tokens to specify to -j would depend on the depth of
2218          * the tree and the order of execution.
2219          */
2220         fifoFd = open(env, O_RDWR, 0);
2221         if (fifoFd >= 0) {
2222             fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2223             maxJobs = 1;
2224             jobFull = FALSE;
2225         }
2226     }
2227     if (fifoFd <= 0) {
2228         maxJobs = maxproc;
2229         jobFull = FALSE;
2230     } else {
2231     }
2232     nJobs = 0;
2233
2234     aborting = 0;
2235     errors = 0;
2236
2237     lastNode = NULL;
2238
2239     if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2240         /*
2241          * If only one job can run at a time, there's no need for a banner,
2242          * no is there?
2243          */
2244         targFmt = "";
2245     } else {
2246         targFmt = TARG_FMT;
2247     }
2248
2249     Shell_Init();
2250
2251     /*
2252      * Catch the four signals that POSIX specifies if they aren't ignored.
2253      * JobCatchSignal will just set global variables and hope someone
2254      * else is going to handle the interrupt.
2255      */
2256     sa.sa_handler = JobCatchSig;
2257     sigemptyset(&sa.sa_mask);
2258     sa.sa_flags = 0;
2259
2260     if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2261         sigaction(SIGINT, &sa, NULL);
2262     }
2263     if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2264         sigaction(SIGHUP, &sa, NULL);
2265     }
2266     if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2267         sigaction(SIGQUIT, &sa, NULL);
2268     }
2269     if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2270         sigaction(SIGTERM, &sa, NULL);
2271     }
2272     /*
2273      * There are additional signals that need to be caught and passed if
2274      * either the export system wants to be told directly of signals or if
2275      * we're giving each job its own process group (since then it won't get
2276      * signals from the terminal driver as we own the terminal)
2277      */
2278 #if defined(USE_PGRP)
2279     if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2280         sigaction(SIGTSTP, &sa, NULL);
2281     }
2282     if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2283         sigaction(SIGTTOU, &sa, NULL);
2284     }
2285     if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2286         sigaction(SIGTTIN, &sa, NULL);
2287     }
2288     if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2289         sigaction(SIGWINCH, &sa, NULL);
2290     }
2291 #endif
2292
2293 #ifdef USE_KQUEUE
2294     if ((kqfd = kqueue()) == -1) {
2295         Punt("kqueue: %s", strerror(errno));
2296     }
2297 #endif
2298
2299     begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2300
2301     if (begin != NULL) {
2302         JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2303         while (nJobs) {
2304             Job_CatchOutput(0);
2305             Job_CatchChildren(!usePipes);
2306         }
2307     }
2308     postCommands = Targ_FindNode(".END", TARG_CREATE);
2309 }
2310
2311 /*-
2312  *-----------------------------------------------------------------------
2313  * Job_Full --
2314  *      See if the job table is full. It is considered full if it is OR
2315  *      if we are in the process of aborting OR if we have
2316  *      reached/exceeded our local quota. This prevents any more jobs
2317  *      from starting up.
2318  *
2319  * Results:
2320  *      TRUE if the job table is full, FALSE otherwise
2321  * Side Effects:
2322  *      None.
2323  *-----------------------------------------------------------------------
2324  */
2325 Boolean
2326 Job_Full(void)
2327 {
2328     char c;
2329     int i;
2330
2331     if (aborting)
2332         return (aborting);
2333     if (fifoFd >= 0 && jobFull) {
2334         i = read(fifoFd, &c, 1);
2335         if (i > 0) {
2336             maxJobs++;
2337             jobFull = FALSE;
2338         }
2339     }
2340     return (jobFull);
2341 }
2342
2343 /*-
2344  *-----------------------------------------------------------------------
2345  * Job_Empty --
2346  *      See if the job table is empty.  Because the local concurrency may
2347  *      be set to 0, it is possible for the job table to become empty,
2348  *      while the list of stoppedJobs remains non-empty. In such a case,
2349  *      we want to restart as many jobs as we can.
2350  *
2351  * Results:
2352  *      TRUE if it is. FALSE if it ain't.
2353  *
2354  * Side Effects:
2355  *      None.
2356  *
2357  * -----------------------------------------------------------------------
2358  */
2359 Boolean
2360 Job_Empty(void)
2361 {
2362     if (nJobs == 0) {
2363         if (!Lst_IsEmpty(&stoppedJobs) && !aborting) {
2364             /*
2365              * The job table is obviously not full if it has no jobs in
2366              * it...Try and restart the stopped jobs.
2367              */
2368             jobFull = FALSE;
2369             JobRestartJobs();
2370             return (FALSE);
2371         } else {
2372             return (TRUE);
2373         }
2374     } else {
2375         return (FALSE);
2376     }
2377 }
2378
2379 /*-
2380  *-----------------------------------------------------------------------
2381  * JobMatchShell --
2382  *      Find a matching shell in 'shells' given its final component.
2383  *
2384  * Results:
2385  *      A pointer to a freshly allocated Shell structure with a copy
2386  *      of the static structure or NULL if no shell with the given name
2387  *      is found.
2388  *
2389  * Side Effects:
2390  *      None.
2391  *
2392  *-----------------------------------------------------------------------
2393  */
2394 static Shell *
2395 JobMatchShell(const char *name)
2396 {
2397     const struct CShell *sh;          /* Pointer into shells table */
2398     struct Shell *nsh;
2399
2400     for (sh = shells; sh < shells + __arysize(shells); sh++)
2401         if (strcmp(sh->name, name) == 0)
2402             break;
2403
2404     if (sh == shells + __arysize(shells))
2405         return (NULL);
2406
2407     /* make a copy */
2408     nsh = emalloc(sizeof(*nsh));
2409
2410     nsh->name = estrdup(sh->name);
2411     nsh->echoOff = estrdup(sh->echoOff);
2412     nsh->echoOn = estrdup(sh->echoOn);
2413     nsh->hasEchoCtl = sh->hasEchoCtl;
2414     nsh->noPrint = estrdup(sh->noPrint);
2415     nsh->noPLen = sh->noPLen;
2416     nsh->hasErrCtl = sh->hasErrCtl;
2417     nsh->errCheck = estrdup(sh->errCheck);
2418     nsh->ignErr = estrdup(sh->ignErr);
2419     nsh->echo = estrdup(sh->echo);
2420     nsh->exit = estrdup(sh->exit);
2421
2422     return (nsh);
2423 }
2424
2425 /*-
2426  *-----------------------------------------------------------------------
2427  * Job_ParseShell --
2428  *      Parse a shell specification and set up commandShell, shellPath
2429  *      and shellName appropriately.
2430  *
2431  * Results:
2432  *      FAILURE if the specification was incorrect.
2433  *
2434  * Side Effects:
2435  *      commandShell points to a Shell structure (either predefined or
2436  *      created from the shell spec), shellPath is the full path of the
2437  *      shell described by commandShell, while shellName is just the
2438  *      final component of shellPath.
2439  *
2440  * Notes:
2441  *      A shell specification consists of a .SHELL target, with dependency
2442  *      operator, followed by a series of blank-separated words. Double
2443  *      quotes can be used to use blanks in words. A backslash escapes
2444  *      anything (most notably a double-quote and a space) and
2445  *      provides the functionality it does in C. Each word consists of
2446  *      keyword and value separated by an equal sign. There should be no
2447  *      unnecessary spaces in the word. The keywords are as follows:
2448  *          name            Name of shell.
2449  *          path            Location of shell. Overrides "name" if given
2450  *          quiet           Command to turn off echoing.
2451  *          echo            Command to turn echoing on
2452  *          filter          Result of turning off echoing that shouldn't be
2453  *                          printed.
2454  *          echoFlag        Flag to turn echoing on at the start
2455  *          errFlag         Flag to turn error checking on at the start
2456  *          hasErrCtl       True if shell has error checking control
2457  *          check           Command to turn on error checking if hasErrCtl
2458  *                          is TRUE or template of command to echo a command
2459  *                          for which error checking is off if hasErrCtl is
2460  *                          FALSE.
2461  *          ignore          Command to turn off error checking if hasErrCtl
2462  *                          is TRUE or template of command to execute a
2463  *                          command so as to ignore any errors it returns if
2464  *                          hasErrCtl is FALSE.
2465  *
2466  *-----------------------------------------------------------------------
2467  */
2468 ReturnStatus
2469 Job_ParseShell(char *line)
2470 {
2471     char          **words;
2472     int           wordCount;
2473     char          **argv;
2474     int           argc;
2475     char          *path;
2476     Shell         newShell;
2477     Shell         *sh;
2478     Boolean       fullSpec = FALSE;
2479
2480     while (isspace((unsigned char)*line)) {
2481         line++;
2482     }
2483     words = brk_string(line, &wordCount, TRUE);
2484
2485     memset(&newShell, 0, sizeof(newShell));
2486
2487     /*
2488      * Parse the specification by keyword
2489      */
2490     for (path = NULL, argc = wordCount - 1, argv = words + 1;
2491          argc != 0;
2492          argc--, argv++) {
2493              if (strncmp(*argv, "path=", 5) == 0) {
2494                  path = &argv[0][5];
2495              } else if (strncmp(*argv, "name=", 5) == 0) {
2496                  newShell.name = &argv[0][5];
2497              } else {
2498                  if (strncmp(*argv, "quiet=", 6) == 0) {
2499                      newShell.echoOff = &argv[0][6];
2500                  } else if (strncmp(*argv, "echo=", 5) == 0) {
2501                      newShell.echoOn = &argv[0][5];
2502                  } else if (strncmp(*argv, "filter=", 7) == 0) {
2503                      newShell.noPrint = &argv[0][7];
2504                      newShell.noPLen = strlen(newShell.noPrint);
2505                  } else if (strncmp(*argv, "echoFlag=", 9) == 0) {
2506                      newShell.echo = &argv[0][9];
2507                  } else if (strncmp(*argv, "errFlag=", 8) == 0) {
2508                      newShell.exit = &argv[0][8];
2509                  } else if (strncmp(*argv, "hasErrCtl=", 10) == 0) {
2510                      char c = argv[0][10];
2511                      newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
2512                                            (c != 'T') && (c != 't'));
2513                  } else if (strncmp(*argv, "check=", 6) == 0) {
2514                      newShell.errCheck = &argv[0][6];
2515                  } else if (strncmp(*argv, "ignore=", 7) == 0) {
2516                      newShell.ignErr = &argv[0][7];
2517                  } else {
2518                      Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"",
2519                                   *argv);
2520                      return (FAILURE);
2521                  }
2522                  fullSpec = TRUE;
2523              }
2524     }
2525
2526     /*
2527      * Some checks (could be more)
2528      */
2529     if (fullSpec) {
2530         if ((newShell.echoOn != NULL) ^ (newShell.echoOff != NULL))
2531             Parse_Error(PARSE_FATAL, "Shell must have either both echoOff and "
2532                 "echoOn or none of them");
2533
2534         if (newShell.echoOn != NULL && newShell.echoOff)
2535             newShell.hasEchoCtl = TRUE;
2536     }
2537
2538     if (path == NULL) {
2539         /*
2540          * If no path was given, the user wants one of the pre-defined shells,
2541          * yes? So we find the one s/he wants with the help of JobMatchShell
2542          * and set things up the right way. shellPath will be set up by
2543          * Job_Init.
2544          */
2545         if (newShell.name == NULL) {
2546             Parse_Error(PARSE_FATAL, "Neither path nor name specified");
2547             return (FAILURE);
2548         }
2549         if ((sh = JobMatchShell(newShell.name)) == NULL) {
2550             Parse_Error(PARSE_FATAL, "%s: no matching shell", newShell.name);
2551             return (FAILURE);
2552         }
2553
2554     } else {
2555         /*
2556          * The user provided a path. If s/he gave nothing else (fullSpec is
2557          * FALSE), try and find a matching shell in the ones we know of.
2558          * Else we just take the specification at its word and copy it
2559          * to a new location. In either case, we need to record the
2560          * path the user gave for the shell.
2561          */
2562         free(shellPath);
2563         shellPath = estrdup(path);
2564         if (newShell.name == NULL) {
2565             /* get the base name as the name */
2566             path = strrchr(path, '/');
2567             if (path == NULL) {
2568                 path = shellPath;
2569             } else {
2570                 path += 1;
2571             }
2572             newShell.name = path;
2573         }
2574
2575         if (!fullSpec) {
2576             if ((sh = JobMatchShell(newShell.name)) == NULL) {
2577                 Parse_Error(PARSE_FATAL, "%s: no matching shell",
2578                     newShell.name);
2579                 return (FAILURE);
2580             }
2581         } else {
2582             sh = JobCopyShell(&newShell);
2583         }
2584     }
2585
2586     /* set the new shell */
2587     JobFreeShell(commandShell);
2588     commandShell = sh;
2589
2590     shellName = commandShell->name;
2591
2592     return (SUCCESS);
2593 }
2594
2595 /*-
2596  *-----------------------------------------------------------------------
2597  * JobInterrupt --
2598  *      Handle the receipt of an interrupt.
2599  *
2600  * Results:
2601  *      None
2602  *
2603  * Side Effects:
2604  *      All children are killed. Another job will be started if the
2605  *      .INTERRUPT target was given.
2606  *-----------------------------------------------------------------------
2607  */
2608 static void
2609 JobInterrupt(int runINTERRUPT, int signo)
2610 {
2611     LstNode       *ln;          /* element in job table */
2612     Job           *job;         /* job descriptor in that element */
2613     GNode         *interrupt;   /* the node describing the .INTERRUPT target */
2614
2615     aborting = ABORT_INTERRUPT;
2616
2617     for (ln = Lst_First(&jobs); ln != NULL; ln = Lst_Succ(ln)) {
2618         job = Lst_Datum(ln);
2619
2620         if (!Targ_Precious(job->node)) {
2621             char *file = (job->node->path == NULL ?
2622                                 job->node->name :
2623                                 job->node->path);
2624             if (!noExecute && eunlink(file) != -1) {
2625                 Error("*** %s removed", file);
2626             }
2627         }
2628         if (job->pid) {
2629             DEBUGF(JOB, ("JobInterrupt passing signal to child %d.\n",
2630                    job->pid));
2631             KILL(job->pid, signo);
2632         }
2633     }
2634
2635     if (runINTERRUPT && !touchFlag) {
2636         /* clear the interrupted flag because we would get an
2637          * infinite loop otherwise */
2638         interrupted = 0;
2639
2640         interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2641         if (interrupt != NULL) {
2642             ignoreErrors = FALSE;
2643
2644             JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
2645             while (nJobs) {
2646                 Job_CatchOutput(0);
2647                 Job_CatchChildren(!usePipes);
2648             }
2649         }
2650     }
2651 }
2652
2653 /*
2654  *-----------------------------------------------------------------------
2655  * Job_Finish --
2656  *      Do final processing such as the running of the commands
2657  *      attached to the .END target.
2658  *
2659  * Results:
2660  *      Number of errors reported.
2661  *-----------------------------------------------------------------------
2662  */
2663 int
2664 Job_Finish(void)
2665 {
2666
2667     if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
2668         if (errors) {
2669             Error("Errors reported so .END ignored");
2670         } else {
2671             JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
2672
2673             while (nJobs) {
2674                 Job_CatchOutput(0);
2675                 Job_CatchChildren(!usePipes);
2676             }
2677         }
2678     }
2679     if (fifoFd >= 0) {
2680         close(fifoFd);
2681         fifoFd = -1;
2682         if (fifoMaster)
2683             unlink(fifoName);
2684     }
2685     return (errors);
2686 }
2687
2688 /*-
2689  *-----------------------------------------------------------------------
2690  * Job_Wait --
2691  *      Waits for all running jobs to finish and returns. Sets 'aborting'
2692  *      to ABORT_WAIT to prevent other jobs from starting.
2693  *
2694  * Results:
2695  *      None.
2696  *
2697  * Side Effects:
2698  *      Currently running jobs finish.
2699  *
2700  *-----------------------------------------------------------------------
2701  */
2702 void
2703 Job_Wait(void)
2704 {
2705
2706     aborting = ABORT_WAIT;
2707     while (nJobs != 0) {
2708         Job_CatchOutput(0);
2709         Job_CatchChildren(!usePipes);
2710     }
2711     aborting = 0;
2712 }
2713
2714 /*-
2715  *-----------------------------------------------------------------------
2716  * Job_AbortAll --
2717  *      Abort all currently running jobs without handling output or anything.
2718  *      This function is to be called only in the event of a major
2719  *      error. Most definitely NOT to be called from JobInterrupt.
2720  *
2721  * Results:
2722  *      None
2723  *
2724  * Side Effects:
2725  *      All children are killed, not just the firstborn
2726  *-----------------------------------------------------------------------
2727  */
2728 void
2729 Job_AbortAll(void)
2730 {
2731     LstNode             *ln;    /* element in job table */
2732     Job                 *job;   /* the job descriptor in that element */
2733     int                 foo;
2734
2735     aborting = ABORT_ERROR;
2736
2737     if (nJobs) {
2738         for (ln = Lst_First(&jobs); ln != NULL; ln = Lst_Succ(ln)) {
2739             job = Lst_Datum(ln);
2740
2741             /*
2742              * kill the child process with increasingly drastic signals to make
2743              * darn sure it's dead.
2744              */
2745             KILL(job->pid, SIGINT);
2746             KILL(job->pid, SIGKILL);
2747         }
2748     }
2749
2750     /*
2751      * Catch as many children as want to report in at first, then give up
2752      */
2753     while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2754         continue;
2755 }
2756
2757 /*-
2758  *-----------------------------------------------------------------------
2759  * JobRestartJobs --
2760  *      Tries to restart stopped jobs if there are slots available.
2761  *      Note that this tries to restart them regardless of pending errors.
2762  *      It's not good to leave stopped jobs lying around!
2763  *
2764  * Results:
2765  *      None.
2766  *
2767  * Side Effects:
2768  *      Resumes(and possibly migrates) jobs.
2769  *
2770  *-----------------------------------------------------------------------
2771  */
2772 static void
2773 JobRestartJobs(void)
2774 {
2775     while (!jobFull && !Lst_IsEmpty(&stoppedJobs)) {
2776         DEBUGF(JOB, ("Job queue is not full. Restarting a stopped job.\n"));
2777         JobRestart(Lst_DeQueue(&stoppedJobs));
2778     }
2779 }