Do not temporarily set signals to SIG_IGN when polling whether the parent
[dfdiff.git] / usr.bin / make / job.c
blob73e47650fbc77a423488eae8f6b4d80b69b43e42
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.
8 * This code is derived from software contributed to Berkeley by
9 * Adam de Boor.
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.
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.
39 * @(#)job.c 8.2 (Berkeley) 3/19/94
40 * $FreeBSD: src/usr.bin/make/job.c,v 1.75 2005/02/10 14:32:14 harti Exp $
41 * $DragonFly: src/usr.bin/make/job.c,v 1.147 2006/10/04 20:13:53 dillon Exp $
44 #ifndef OLD_JOKE
45 #define OLD_JOKE 0
46 #endif /* OLD_JOKE */
48 /**
49 * job.c
50 * handle the creation etc. of our child processes.
52 * Interface:
53 * Job_Make Start the creation of the given target.
55 * Job_CatchChildren
56 * Check for and handle the termination of any children.
57 * This must be called reasonably frequently to keep the
58 * whole make going at a decent clip, since job table
59 * entries aren't removed until their process is caught
60 * this way. Its single argument is true if the function
61 * should block waiting for a child to terminate.
63 * Job_CatchOutput Print any output our children have produced. Should
64 * also be called fairly frequently to keep the user
65 * informed of what's going on. If no output is waiting,
66 * it will block for a time given by the SEL_* constants,
67 * below, or until output is ready.
69 * Job_Init Called to initialize this module. in addition, any
70 * commands attached to the .BEGIN target are executed
71 * before this function returns. Hence, the makefile must
72 * have been parsed before this function is called.
74 * Job_Full Return true if the job table is filled.
76 * Job_Empty Return true if the job table is completely empty.
78 * Job_Finish Perform any final processing which needs doing. This
79 * includes the execution of any commands which have
80 * been/were attached to the .END target. It should only
81 * be called when the job table is empty.
83 * Job_AbortAll Abort all currently running jobs. It doesn't handle
84 * output or do anything for the jobs, just kills them.
85 * It should only be called in an emergency, as it were.
87 * JobCheckCommands
88 * Verify that the commands for a target are ok. Provide
89 * them if necessary and possible.
91 * JobTouch Update a target without really updating it.
93 * Job_Wait Wait for all currently-running jobs to finish.
95 * compat.c
96 * The routines in this file implement the full-compatibility
97 * mode of PMake. Most of the special functionality of PMake
98 * is available in this mode. Things not supported:
99 * - different shells.
100 * - friendly variable substitution.
102 * Interface:
103 * Compat_Run Initialize things for this module and recreate
104 * thems as need creatin'
107 #include <sys/queue.h>
108 #include <sys/types.h>
109 #include <sys/select.h>
110 #include <sys/stat.h>
111 #include <sys/wait.h>
112 #include <ctype.h>
113 #include <err.h>
114 #include <errno.h>
115 #include <fcntl.h>
116 #include <inttypes.h>
117 #include <string.h>
118 #include <signal.h>
119 #include <stdlib.h>
120 #include <unistd.h>
121 #include <utime.h>
123 #include "arch.h"
124 #include "buf.h"
125 #include "config.h"
126 #include "dir.h"
127 #include "globals.h"
128 #include "GNode.h"
129 #include "job.h"
130 #include "make.h"
131 #include "parse.h"
132 #include "pathnames.h"
133 #include "proc.h"
134 #include "shell.h"
135 #include "str.h"
136 #include "suff.h"
137 #include "targ.h"
138 #include "util.h"
139 #include "var.h"
141 #define TMPPAT "/tmp/makeXXXXXXXXXX"
142 #define MKLVL_MAXVAL 500
143 #define MKLVL_ENVVAR "__MKLVL__"
146 * The SEL_ constants determine the maximum amount of time spent in select
147 * before coming out to see if a child has finished. SEL_SEC is the number of
148 * seconds and SEL_USEC is the number of micro-seconds
150 #define SEL_SEC 2
151 #define SEL_USEC 0
154 * Job Table definitions.
156 * The job "table" is kept as a linked Lst in 'jobs', with the number of
157 * active jobs maintained in the 'nJobs' variable. At no time will this
158 * exceed the value of 'maxJobs', initialized by the Job_Init function.
160 * When a job is finished, the Make_Update function is called on each of the
161 * parents of the node which was just remade. This takes care of the upward
162 * traversal of the dependency graph.
164 #define JOB_BUFSIZE 1024
165 typedef struct Job {
166 struct Shell *shell;
167 pid_t pid; /* The child's process ID */
169 struct GNode *node; /* The target the child is making */
172 * A LstNode for the first command to be saved after the job completes.
173 * This is NULL if there was no "..." in the job's commands.
175 LstNode *tailCmds;
178 * An FILE* for writing out the commands. This is only
179 * used before the job is actually started.
181 FILE *cmdFILE;
184 * A word of flags which determine how the module handles errors,
185 * echoing, etc. for the job
187 short flags; /* Flags to control treatment of job */
188 #define JOB_IGNERR 0x001 /* Ignore non-zero exits */
189 #define JOB_SILENT 0x002 /* no output */
190 #define JOB_SPECIAL 0x004 /* Target is a special one. i.e. run it locally
191 * if we can't export it and maxLocal is 0 */
192 #define JOB_IGNDOTS 0x008 /* Ignore "..." lines when processing
193 * commands */
194 #define JOB_FIRST 0x020 /* Job is first job for the node */
195 #define JOB_RESTART 0x080 /* Job needs to be completely restarted */
196 #define JOB_RESUME 0x100 /* Job needs to be resumed b/c it stopped,
197 * for some reason */
198 #define JOB_CONTINUING 0x200 /* We are in the process of resuming this job.
199 * Used to avoid infinite recursion between
200 * JobFinish and JobRestart */
202 /* union for handling shell's output */
203 union {
205 * This part is used when usePipes is true.
206 * The output is being caught via a pipe and the descriptors
207 * of our pipe, an array in which output is line buffered and
208 * the current position in that buffer are all maintained for
209 * each job.
211 struct {
213 * Input side of pipe associated with
214 * job's output channel
216 int op_inPipe;
219 * Output side of pipe associated with job's
220 * output channel
222 int op_outPipe;
225 * Buffer for storing the output of the
226 * job, line by line
228 char op_outBuf[JOB_BUFSIZE + 1];
230 /* Current position in op_outBuf */
231 int op_curPos;
232 } o_pipe;
235 * If usePipes is false the output is routed to a temporary
236 * file and all that is kept is the name of the file and the
237 * descriptor open to the file.
239 struct {
240 /* Name of file to which shell output was rerouted */
241 char of_outFile[sizeof(TMPPAT)];
244 * Stream open to the output file. Used to funnel all
245 * from a single job to one file while still allowing
246 * multiple shell invocations
248 int of_outFd;
249 } o_file;
251 } output; /* Data for tracking a shell's output */
253 TAILQ_ENTRY(Job) link; /* list link */
254 } Job;
256 #define outPipe output.o_pipe.op_outPipe
257 #define inPipe output.o_pipe.op_inPipe
258 #define outBuf output.o_pipe.op_outBuf
259 #define curPos output.o_pipe.op_curPos
261 #define outFile output.o_file.of_outFile
262 #define outFd output.o_file.of_outFd
264 TAILQ_HEAD(JobList, Job);
267 * error handling variables
269 static int errors = 0; /* number of errors reported */
270 static int aborting = 0; /* why is the make aborting? */
271 #define ABORT_ERROR 1 /* Because of an error */
272 #define ABORT_INTERRUPT 2 /* Because it was interrupted */
273 #define ABORT_WAIT 3 /* Waiting for jobs to finish */
276 * post-make command processing. The node postCommands is really just the
277 * .END target but we keep it around to avoid having to search for it
278 * all the time.
280 static GNode *postCommands;
283 * The number of commands actually printed for a target. Should this
284 * number be 0, no shell will be executed.
286 static int numCommands;
289 * Return values from JobStart.
291 #define JOB_RUNNING 0 /* Job is running */
292 #define JOB_ERROR 1 /* Error in starting the job */
293 #define JOB_FINISHED 2 /* The job is already finished */
294 #define JOB_STOPPED 3 /* The job is stopped */
297 * The maximum number of jobs that may run. This is initialize from the
298 * -j argument for the leading make and from the FIFO for sub-makes.
300 static int maxJobs;
301 static int nJobs; /* The number of children currently running */
303 /* The structures that describe them */
304 static struct JobList jobs = TAILQ_HEAD_INITIALIZER(jobs);
306 static bool jobFull; /* Flag to tell when the job table is full. It
307 * is set true when (1) the total number of
308 * running jobs equals the maximum allowed */
309 static fd_set outputs; /* Set of descriptors of pipes connected to
310 * the output channels of children */
311 static GNode *lastNode; /* The node for which output was most recently
312 * produced. */
313 static const char *targFmt; /* Format string to use to head output from a
314 * job when it's not the most-recent job heard
315 * from */
317 #define TARG_FMT "--- %s ---\n" /* Default format */
318 #define MESSAGE(fp, gn) \
319 fprintf(fp, targFmt, gn->name);
322 * When JobStart attempts to run a job but isn't allowed to
323 * or when Job_CatchChildren detects a job that has
324 * been stopped somehow, the job is placed on the stoppedJobs queue to be run
325 * when the next job finishes.
327 * Lst of Job structures describing jobs that were stopped due to
328 * concurrency limits or externally
330 static struct JobList stoppedJobs = TAILQ_HEAD_INITIALIZER(stoppedJobs);
332 static int fifoFd; /* Fd of our job fifo */
333 static char fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
334 static int fifoMaster;
336 #if defined(USE_PGRP)
337 # if defined(SYSV)
338 # define KILL(pid, sig) killpg(-(pid), (sig))
339 # else
340 # define KILL(pid, sig) killpg((pid), (sig))
341 # endif
342 #else
343 # define KILL(pid, sig) kill((pid), (sig))
344 #endif
347 * Grmpf... There is no way to set bits of the wait structure
348 * anymore with the stupid W*() macros. I liked the union wait
349 * stuff much more. So, we devise our own macros... This is
350 * really ugly, use dramamine sparingly. You have been warned.
352 #define W_SETMASKED(st, val, fun) \
354 int sh = (int)~0; \
355 int mask = fun(sh); \
357 for (sh = 0; ((mask >> sh) & 1) == 0; sh++) \
358 continue; \
359 *(st) = (*(st) & ~mask) | ((val) << sh); \
362 #define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
363 #define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
365 typedef void AbortProc(const char [], ...);
367 static void JobRestart(Job *);
368 static int JobStart(GNode *, int, Job *);
369 static void JobDoOutput(Job *, bool);
370 static void JobRestartJobs(void);
371 static int Compat_RunCommand(GNode *, const char [], GNode *);
372 static void JobPassSig(int);
373 static void JobTouch(GNode *, bool);
374 static bool JobCheckCommands(GNode *, AbortProc *);
376 static GNode *curTarg = NULL;
378 static volatile sig_atomic_t got_SIGINT;
379 static volatile sig_atomic_t got_SIGHUP;
380 static volatile sig_atomic_t got_SIGQUIT;
381 static volatile sig_atomic_t got_SIGTERM;
382 #if defined(USE_PGRP)
383 static volatile sig_atomic_t got_SIGTSTP;
384 static volatile sig_atomic_t got_SIGTTOU;
385 static volatile sig_atomic_t got_SIGTTIN;
386 static volatile sig_atomic_t got_SIGWINCH;
387 #endif
389 Shell *commandShell = NULL;
392 * In lieu of a good way to prevent every possible looping in make(1), stop
393 * there from being more than MKLVL_MAXVAL processes forked by make(1), to
394 * prevent a forkbomb from happening, in a dumb and mechanical way.
396 * Side Effects:
397 * Creates or modifies environment variable MKLVL_ENVVAR via setenv().
399 static void
400 check_make_level(void)
402 char *value = getenv(MKLVL_ENVVAR);
403 int level = (value == NULL) ? 0 : atoi(value);
405 if (level < 0) {
406 errc(2, EAGAIN, "Invalid value for recursion level (%d).",
407 level);
408 } else if (level > MKLVL_MAXVAL) {
409 errc(2, EAGAIN, "Max recursion level (%d) exceeded.",
410 MKLVL_MAXVAL);
411 } else {
412 char new_value[32];
413 sprintf(new_value, "%d", level + 1);
414 if (setenv(MKLVL_ENVVAR, new_value, 1) == -1)
415 Punt("setenv: %s: can't allocate memory", MKLVL_ENVVAR);
420 * Handle recept of a signal by setting a variable. The handling action is
421 * defered until the mainline code can safely handle it.
423 static void
424 SigCatcher(int sig)
426 switch (sig) {
427 case SIGCHLD:
428 /* do nothing */
429 break;
430 case SIGINT:
431 got_SIGINT++;
432 break;
433 case SIGHUP:
434 got_SIGHUP++;
435 break;
436 case SIGQUIT:
437 got_SIGQUIT++;
438 break;
439 case SIGTERM:
440 got_SIGTERM++;
441 break;
442 #if defined(USE_PGRP)
443 case SIGTSTP:
444 got_SIGTSTP++;
445 break;
446 case SIGTTOU:
447 got_SIGTTOU++;
448 break;
449 case SIGTTIN:
450 got_SIGTTIN++;
451 break;
452 case SIGWINCH:
453 got_SIGWINCH++;
454 break;
455 #endif
456 default:
457 /* unexpected signal */
458 break;
465 static void
466 SigHandler(void)
468 if (got_SIGINT) {
469 got_SIGINT = 0;
470 JobPassSig(SIGINT);
472 if (got_SIGHUP) {
473 got_SIGHUP = 0;
474 JobPassSig(SIGHUP);
476 if (got_SIGQUIT) {
477 got_SIGQUIT = 0;
478 JobPassSig(SIGQUIT);
480 if (got_SIGTERM) {
481 got_SIGTERM = 0;
482 JobPassSig(SIGTERM);
484 #if defined(USE_PGRP)
485 if (got_SIGTSTP) {
486 got_SIGTSTP = 0;
487 JobPassSig(SIGTSTP);
489 if (got_SIGTTOU) {
490 got_SIGTTOU = 0;
491 JobPassSig(SIGTTOU);
493 if (got_SIGTTIN) {
494 got_SIGTTIN = 0;
495 JobPassSig(SIGTTIN);
497 if (got_SIGWINCH) {
498 got_SIGWINCH = 0;
499 JobPassSig(SIGWINCH);
501 #endif
504 static
505 sig_t
506 getsignal(int signo)
508 struct sigaction sa;
509 if (sigaction(signo, NULL, &sa) < 0)
510 sa.sa_handler = SIG_IGN;
511 return(sa.sa_handler);
514 void
515 Sig_Init(bool compat)
517 struct sigaction sa;
519 got_SIGINT = 0;
520 got_SIGHUP = 0;
521 got_SIGQUIT = 0;
522 got_SIGTERM = 0;
523 #if defined(USE_PGRP)
524 got_SIGTSTP = 0;
525 got_SIGTTOU = 0;
526 got_SIGTTIN = 0;
527 got_SIGWINCH = 0;
528 #endif
530 if (compat == false) {
532 * Setup handler to catch SIGCHLD so that we get kicked out
533 * of select() when we need to look at a child. This is only
534 * known to matter for the -j case (perhaps without -P).
536 sigemptyset(&sa.sa_mask);
537 sa.sa_handler = SigCatcher;
538 sa.sa_flags = SA_NOCLDSTOP;
539 sigaction(SIGCHLD, &sa, NULL);
543 * Catch the four signals that POSIX specifies if they aren't
544 * ignored.
546 sigemptyset(&sa.sa_mask);
547 sa.sa_handler = SigCatcher;
548 sa.sa_flags = 0;
550 if (getsignal(SIGINT) != SIG_IGN) {
551 sigaction(SIGINT, &sa, NULL);
553 if (getsignal(SIGHUP) != SIG_IGN) {
554 sigaction(SIGHUP, &sa, NULL);
556 if (getsignal(SIGQUIT) != SIG_IGN) {
557 sigaction(SIGQUIT, &sa, NULL);
559 if (getsignal(SIGTERM) != SIG_IGN) {
560 sigaction(SIGTERM, &sa, NULL);
563 #if defined(USE_PGRP)
564 if (compat == false) {
566 * There are additional signals that need to be caught and
567 * passed if either the export system wants to be told
568 * directly of signals or if we're giving each job its own
569 * process group (since then it won't get signals from the
570 * terminal driver as we own the terminal)
572 if (getsignal(SIGTSTP) != SIG_IGN) {
573 sigaction(SIGTSTP, &sa, NULL);
575 if (getsignal(SIGTTOU) != SIG_IGN) {
576 sigaction(SIGTTOU, &sa, NULL);
578 if (getsignal(SIGTTIN) != SIG_IGN) {
579 sigaction(SIGTTIN, &sa, NULL);
581 if (getsignal(SIGWINCH) != SIG_IGN) {
582 sigaction(SIGWINCH, &sa, NULL);
585 #endif
590 void
591 Proc_Init(void)
593 check_make_level();
595 #ifdef RLIMIT_NOFILE
597 struct rlimit rl;
600 * get rid of resource limit on file descriptors
602 if (getrlimit(RLIMIT_NOFILE, &rl) == -1) {
603 err(2, "getrlimit");
605 rl.rlim_cur = rl.rlim_max;
606 if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
607 err(2, "setrlimit");
610 #endif
614 * Wait for child process to terminate.
616 static int
617 ProcWait(ProcStuff *ps)
620 * Wait for the process to exit.
622 for (;;) {
623 pid_t pid;
625 pid = waitpid(ps->child_pid, &ps->child_status, 0);
626 if (pid == ps->child_pid) {
628 * We finished waiting for the child.
630 return (0);
631 } else {
632 if (errno == EINTR) {
634 * Return so we can handle the signal that
635 * was delivered.
637 return (-1);
638 } else {
639 Fatal("error in wait: %d", pid);
640 /* NOTREACHED */
647 * Execute the list of command associated with the node.
649 * @param save Commands preceeded by "..." are save in this node to be
650 * executed after the other rules are executed.
652 static void
653 Compat_RunCmds(GNode *gn, GNode *save)
655 Lst *cmds = &gn->commands;
656 LstNode *ln;
658 LST_FOREACH(ln, cmds) {
659 char *cmd = Lst_Datum(ln);
661 if (Compat_RunCommand(gn, cmd, save))
662 break;
667 * Pass a signal on to all jobs.
669 * Side Effects:
670 * We die by the same signal.
672 static void
673 JobPassSig(int signo)
675 Job *job;
677 DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
680 * Propagate signal to children and in addition, send SIGCONT
681 * in case any of the children where suspended, so the the
682 * signal will get delivered.
684 TAILQ_FOREACH(job, &jobs, link) {
685 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
686 signo, (intmax_t)job->pid));
687 KILL(job->pid, signo);
688 KILL(job->pid, SIGCONT);
691 #if defined(USE_PGRP)
693 * Why are we even catching these signals?
694 * SIGTSTP, SIGTTOU, SIGTTIN, and SIGWINCH
696 switch (signo) {
697 case SIGTSTP:
698 case SIGTTOU:
699 case SIGTTIN:
700 case SIGWINCH:
701 return;
702 default:
703 break;
705 #endif
708 * Deal with proper cleanup based on the signal received. We only run
709 * the .INTERRUPT target if the signal was in fact an interrupt.
710 * The other three termination signals are more of a "get out *now*"
711 * command.
714 aborting = ABORT_INTERRUPT;
716 TAILQ_FOREACH(job, &jobs, link) {
717 if (!Targ_Precious(job->node)) {
718 char *file = (job->node->path == NULL ?
719 job->node->name : job->node->path);
721 if (!noExecute && eunlink(file) != -1) {
722 Error("*** %s removed", file);
727 if ((signo == SIGINT) && !touchFlag) {
728 GNode *interrupt;
730 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
731 if (interrupt != NULL) {
732 ignoreErrors = false;
734 JobStart(interrupt, JOB_IGNDOTS, NULL);
735 while (nJobs) {
736 Job_CatchOutput(0);
737 Job_CatchChildren(!usePipes);
743 * Leave gracefully if SIGQUIT, rather than core dumping.
745 if (signo == SIGQUIT) {
746 signo = SIGINT;
749 DEBUGF(JOB, ("JobPassSig passing signal %d to self.\n", signo));
751 signal(signo, SIG_DFL);
752 KILL(getpid(), signo);
756 * JobPrintCommand
757 * Put out another command for the given job. If the command starts
758 * with an @ or a - we process it specially. In the former case,
759 * so long as the -s and -n flags weren't given to make, we stick
760 * a shell-specific echoOff command in the script. In the latter,
761 * we ignore errors for the entire job, unless the shell has error
762 * control.
763 * If the command is just "..." we take all future commands for this
764 * job to be commands to be executed once the entire graph has been
765 * made and return non-zero to signal that the end of the commands
766 * was reached. These commands are later attached to the postCommands
767 * node and executed by Job_Finish when all things are done.
768 * This function is called from JobStart via LST_FOREACH.
770 * Results:
771 * Always 0, unless the command was "..."
773 * Side Effects:
774 * If the command begins with a '-' and the shell has no error control,
775 * the JOB_IGNERR flag is set in the job descriptor.
776 * If the command is "..." and we're not ignoring such things,
777 * tailCmds is set to the successor node of the cmd.
778 * numCommands is incremented if the command is actually printed.
780 static int
781 JobPrintCommand(char *cmd, Job *job)
783 struct Shell *shell = job->shell;
784 bool noSpecials; /* true if we shouldn't worry about
785 * inserting special commands into
786 * the input stream. */
787 bool shutUp = false; /* true if we put a no echo command
788 * into the command file */
789 bool errOff = false; /* true if we turned error checking
790 * off before printing the command
791 * and need to turn it back on */
792 const char *cmdTemplate;/* Template to use when printing the command */
793 char *cmdStart; /* Start of expanded command */
794 LstNode *cmdNode; /* Node for replacing the command */
796 noSpecials = (noExecute && !(job->node->type & OP_MAKE));
798 if (strcmp(cmd, "...") == 0) {
799 job->node->type |= OP_SAVE_CMDS;
800 if ((job->flags & JOB_IGNDOTS) == 0) {
801 job->tailCmds =
802 Lst_Succ(Lst_Member(&job->node->commands, cmd));
803 return (1);
805 return (0);
808 #define DBPRINTF(fmt, arg) \
809 DEBUGF(JOB, (fmt, arg)); \
810 fprintf(job->cmdFILE, fmt, arg); \
811 fflush(job->cmdFILE);
813 numCommands += 1;
816 * For debugging, we replace each command with the result of expanding
817 * the variables in the command.
819 cmdNode = Lst_Member(&job->node->commands, cmd);
821 cmd = Buf_Peel(Var_Subst(cmd, job->node, false));
822 cmdStart = cmd;
824 Lst_Replace(cmdNode, cmdStart);
826 cmdTemplate = "%s\n";
829 * Check for leading @', -' or +'s to control echoing, error checking,
830 * and execution on -n.
832 while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
833 switch (*cmd) {
835 case '@':
836 shutUp = DEBUG(LOUD) ? false : true;
837 break;
839 case '-':
840 errOff = true;
841 break;
843 case '+':
844 if (noSpecials) {
846 * We're not actually executing anything...
847 * but this one needs to be - use compat mode
848 * just for it.
850 Compat_RunCommand(job->node, cmd, NULL);
851 return (0);
853 break;
855 cmd++;
858 while (isspace((unsigned char)*cmd))
859 cmd++;
861 if (shutUp) {
862 if (!(job->flags & JOB_SILENT) && !noSpecials &&
863 shell->hasEchoCtl) {
864 DBPRINTF("%s\n", shell->echoOff);
865 } else {
866 shutUp = false;
870 if (errOff) {
871 if (!(job->flags & JOB_IGNERR) && !noSpecials) {
872 if (shell->hasErrCtl) {
874 * We don't want the error-control commands
875 * showing up either, so we turn off echoing
876 * while executing them. We could put another
877 * field in the shell structure to tell
878 * JobDoOutput to look for this string too,
879 * but why make it any more complex than
880 * it already is?
882 if (!(job->flags & JOB_SILENT) && !shutUp &&
883 shell->hasEchoCtl) {
884 DBPRINTF("%s\n", shell->echoOff);
885 DBPRINTF("%s\n", shell->ignErr);
886 DBPRINTF("%s\n", shell->echoOn);
887 } else {
888 DBPRINTF("%s\n", shell->ignErr);
890 } else if (shell->ignErr &&
891 *shell->ignErr != '\0') {
893 * The shell has no error control, so we need to
894 * be weird to get it to ignore any errors from
895 * the command. If echoing is turned on, we turn
896 * it off and use the errCheck template to echo
897 * the command. Leave echoing off so the user
898 * doesn't see the weirdness we go through to
899 * ignore errors. Set cmdTemplate to use the
900 * weirdness instead of the simple "%s\n"
901 * template.
903 if (!(job->flags & JOB_SILENT) && !shutUp &&
904 shell->hasEchoCtl) {
905 DBPRINTF("%s\n", shell->echoOff);
906 DBPRINTF(shell->errCheck, cmd);
907 shutUp = true;
909 cmdTemplate = shell->ignErr;
911 * The error ignoration (hee hee) is already
912 * taken care of by the ignErr template, so
913 * pretend error checking is still on.
915 errOff = false;
916 } else {
917 errOff = false;
919 } else {
920 errOff = false;
924 DBPRINTF(cmdTemplate, cmd);
926 if (errOff) {
928 * If echoing is already off, there's no point in issuing the
929 * echoOff command. Otherwise we issue it and pretend it was on
930 * for the whole command...
932 if (!shutUp && !(job->flags & JOB_SILENT) &&
933 shell->hasEchoCtl) {
934 DBPRINTF("%s\n", shell->echoOff);
935 shutUp = true;
937 DBPRINTF("%s\n", shell->errCheck);
939 if (shutUp) {
940 DBPRINTF("%s\n", shell->echoOn);
942 return (0);
946 * JobClose
947 * Called to close both input and output pipes when a job is finished.
949 * Side Effects:
950 * The file descriptors associated with the job are closed.
952 static void
953 JobClose(Job *job)
956 if (usePipes) {
957 FD_CLR(job->inPipe, &outputs);
958 if (job->outPipe != job->inPipe) {
959 close(job->outPipe);
961 JobDoOutput(job, true);
962 close(job->inPipe);
963 } else {
964 close(job->outFd);
965 JobDoOutput(job, true);
970 * JobFinish
971 * Do final processing for the given job including updating
972 * parents and starting new jobs as available/necessary. Note
973 * that we pay no attention to the JOB_IGNERR flag here.
974 * This is because when we're called because of a noexecute flag
975 * or something, jstat.w_status is 0 and when called from
976 * Job_CatchChildren, the status is zeroed if it s/b ignored.
978 * Side Effects:
979 * Some nodes may be put on the toBeMade queue.
980 * Final commands for the job are placed on postCommands.
982 * If we got an error and are aborting (aborting == ABORT_ERROR) and
983 * the job list is now empty, we are done for the day.
984 * If we recognized an error (errors !=0), we set the aborting flag
985 * to ABORT_ERROR so no more jobs will be started.
987 static void
988 JobFinish(Job *job, int *status)
990 bool done;
991 LstNode *ln;
993 if (WIFEXITED(*status)) {
994 int job_status = WEXITSTATUS(*status);
996 JobClose(job);
998 * Deal with ignored errors in -B mode. We need to
999 * print a message telling of the ignored error as
1000 * well as setting status.w_status to 0 so the next
1001 * command gets run. To do this, we set done to be
1002 * true if in -B mode and the job exited non-zero.
1004 if (job_status == 0) {
1005 done = false;
1006 } else {
1007 if (job->flags & JOB_IGNERR) {
1008 done = true;
1009 } else {
1011 * If it exited non-zero and either we're
1012 * doing things our way or we're not ignoring
1013 * errors, the job is finished. Similarly, if
1014 * the shell died because of a signal the job
1015 * is also finished. In these cases, finish
1016 * out the job's output before printing the
1017 * exit status...
1019 done = true;
1020 if (job->cmdFILE != NULL &&
1021 job->cmdFILE != stdout) {
1022 fclose(job->cmdFILE);
1027 } else if (WIFSIGNALED(*status)) {
1028 if (WTERMSIG(*status) == SIGCONT) {
1030 * No need to close things down or anything.
1032 done = false;
1033 } else {
1035 * If it exited non-zero and either we're
1036 * doing things our way or we're not ignoring
1037 * errors, the job is finished. Similarly, if
1038 * the shell died because of a signal the job
1039 * is also finished. In these cases, finish
1040 * out the job's output before printing the
1041 * exit status...
1043 JobClose(job);
1044 if (job->cmdFILE != NULL &&
1045 job->cmdFILE != stdout) {
1046 fclose(job->cmdFILE);
1048 done = true;
1050 } else {
1052 * No need to close things down or anything.
1054 done = false;
1057 if (WIFEXITED(*status)) {
1058 if (done || DEBUG(JOB)) {
1059 FILE *out;
1061 if (compatMake &&
1062 !usePipes &&
1063 (job->flags & JOB_IGNERR)) {
1065 * If output is going to a file and this job
1066 * is ignoring errors, arrange to have the
1067 * exit status sent to the output file as
1068 * well.
1070 out = fdopen(job->outFd, "w");
1071 if (out == NULL)
1072 Punt("Cannot fdopen");
1073 } else {
1074 out = stdout;
1077 DEBUGF(JOB, ("Process %jd exited.\n",
1078 (intmax_t)job->pid));
1080 if (WEXITSTATUS(*status) == 0) {
1081 if (DEBUG(JOB)) {
1082 if (usePipes && job->node != lastNode) {
1083 MESSAGE(out, job->node);
1084 lastNode = job->node;
1086 fprintf(out,
1087 "*** Completed successfully\n");
1089 } else {
1090 if (usePipes && job->node != lastNode) {
1091 MESSAGE(out, job->node);
1092 lastNode = job->node;
1094 fprintf(out, "*** Error code %d%s\n",
1095 WEXITSTATUS(*status),
1096 (job->flags & JOB_IGNERR) ?
1097 "(ignored)" : "");
1099 if (job->flags & JOB_IGNERR) {
1100 *status = 0;
1104 fflush(out);
1106 } else if (WIFSIGNALED(*status)) {
1107 if (done || DEBUG(JOB) || (WTERMSIG(*status) == SIGCONT)) {
1108 FILE *out;
1110 if (compatMake &&
1111 !usePipes &&
1112 (job->flags & JOB_IGNERR)) {
1114 * If output is going to a file and this job
1115 * is ignoring errors, arrange to have the
1116 * exit status sent to the output file as
1117 * well.
1119 out = fdopen(job->outFd, "w");
1120 if (out == NULL)
1121 Punt("Cannot fdopen");
1122 } else {
1123 out = stdout;
1126 if (WTERMSIG(*status) == SIGCONT) {
1128 * If the beastie has continued, shift the
1129 * Job from the stopped list to the running
1130 * one (or re-stop it if concurrency is
1131 * exceeded) and go and get another child.
1133 if (job->flags & (JOB_RESUME | JOB_RESTART)) {
1134 if (usePipes && job->node != lastNode) {
1135 MESSAGE(out, job->node);
1136 lastNode = job->node;
1138 fprintf(out, "*** Continued\n");
1140 if (!(job->flags & JOB_CONTINUING)) {
1141 DEBUGF(JOB, ("Warning: process %jd was not "
1142 "continuing.\n", (intmax_t) job->pid));
1143 #ifdef notdef
1145 * We don't really want to restart a
1146 * job from scratch just because it
1147 * continued, especially not without
1148 * killing the continuing process!
1149 * That's why this is ifdef'ed out.
1150 * FD - 9/17/90
1152 JobRestart(job);
1153 #endif
1155 job->flags &= ~JOB_CONTINUING;
1156 TAILQ_INSERT_TAIL(&jobs, job, link);
1157 nJobs += 1;
1158 DEBUGF(JOB, ("Process %jd is continuing locally.\n",
1159 (intmax_t) job->pid));
1160 if (nJobs == maxJobs) {
1161 jobFull = true;
1162 DEBUGF(JOB, ("Job queue is full.\n"));
1164 fflush(out);
1165 return;
1167 } else {
1168 if (usePipes && job->node != lastNode) {
1169 MESSAGE(out, job->node);
1170 lastNode = job->node;
1172 fprintf(out,
1173 "*** Signal %d\n", WTERMSIG(*status));
1174 fflush(out);
1177 } else {
1178 /* STOPPED */
1179 FILE *out;
1181 if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
1183 * If output is going to a file and this job
1184 * is ignoring errors, arrange to have the
1185 * exit status sent to the output file as
1186 * well.
1188 out = fdopen(job->outFd, "w");
1189 if (out == NULL)
1190 Punt("Cannot fdopen");
1191 } else {
1192 out = stdout;
1195 DEBUGF(JOB, ("Process %jd stopped.\n", (intmax_t) job->pid));
1196 if (usePipes && job->node != lastNode) {
1197 MESSAGE(out, job->node);
1198 lastNode = job->node;
1200 fprintf(out, "*** Stopped -- signal %d\n", WSTOPSIG(*status));
1201 job->flags |= JOB_RESUME;
1202 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1203 fflush(out);
1204 return;
1208 * Now handle the -B-mode stuff. If the beast still isn't finished,
1209 * try and restart the job on the next command. If JobStart says it's
1210 * ok, it's ok. If there's an error, this puppy is done.
1212 if (compatMake && WIFEXITED(*status) &&
1213 Lst_Succ(job->node->compat_command) != NULL) {
1214 switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
1215 case JOB_RUNNING:
1216 done = false;
1217 break;
1218 case JOB_ERROR:
1219 done = true;
1220 W_SETEXITSTATUS(status, 1);
1221 break;
1222 case JOB_FINISHED:
1224 * If we got back a JOB_FINISHED code, JobStart has
1225 * already called Make_Update and freed the job
1226 * descriptor. We set done to false here to avoid fake
1227 * cycles and double frees. JobStart needs to do the
1228 * update so we can proceed up the graph when given
1229 * the -n flag..
1231 done = false;
1232 break;
1233 default:
1234 break;
1236 } else {
1237 done = true;
1240 if (done && aborting != ABORT_ERROR &&
1241 aborting != ABORT_INTERRUPT && *status == 0) {
1243 * As long as we aren't aborting and the job didn't return a
1244 * non-zero status that we shouldn't ignore, we call
1245 * Make_Update to update the parents. In addition, any saved
1246 * commands for the node are placed on the .END target.
1248 for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
1249 Lst_AtEnd(&postCommands->commands,
1250 Buf_Peel(
1251 Var_Subst(Lst_Datum(ln), job->node, false)));
1254 job->node->made = MADE;
1255 Make_Update(job->node);
1256 free(job);
1258 } else if (*status != 0) {
1259 errors += 1;
1260 free(job);
1263 JobRestartJobs();
1266 * Set aborting if any error.
1268 if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
1270 * If we found any errors in this batch of children and the -k
1271 * flag wasn't given, we set the aborting flag so no more jobs
1272 * get started.
1274 aborting = ABORT_ERROR;
1277 if (aborting == ABORT_ERROR && Job_Empty()) {
1279 * If we are aborting and the job table is now empty, we finish.
1281 Finish(errors);
1286 * JobTouch
1287 * Touch the given target. Called by JobStart when the -t flag was
1288 * given. Prints messages unless told to be silent.
1290 * Side Effects:
1291 * The data modification of the file is changed. In addition, if the
1292 * file did not exist, it is created.
1294 static void
1295 JobTouch(GNode *gn, bool silent)
1297 int streamID; /* ID of stream opened to do the touch */
1298 struct utimbuf times; /* Times for utime() call */
1300 if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
1302 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
1303 * targets and, as such, shouldn't really be created.
1305 return;
1308 if (!silent) {
1309 fprintf(stdout, "touch %s\n", gn->name);
1310 fflush(stdout);
1313 if (noExecute) {
1314 return;
1317 if (gn->type & OP_ARCHV) {
1318 Arch_Touch(gn);
1319 } else if (gn->type & OP_LIB) {
1320 Arch_TouchLib(gn);
1321 } else {
1322 char *file = gn->path ? gn->path : gn->name;
1324 times.actime = times.modtime = now;
1325 if (utime(file, &times) < 0) {
1326 streamID = open(file, O_RDWR | O_CREAT, 0666);
1328 if (streamID >= 0) {
1329 char c;
1332 * Read and write a byte to the file to change
1333 * the modification time, then close the file.
1335 if (read(streamID, &c, 1) == 1) {
1336 lseek(streamID, (off_t)0, SEEK_SET);
1337 write(streamID, &c, 1);
1340 close(streamID);
1341 } else {
1342 fprintf(stdout, "*** couldn't touch %s: %s",
1343 file, strerror(errno));
1344 fflush(stdout);
1351 * JobCheckCommands
1352 * Make sure the given node has all the commands it needs.
1354 * Results:
1355 * true if the commands list is/was ok.
1357 * Side Effects:
1358 * The node will have commands from the .DEFAULT rule added to it
1359 * if it needs them.
1361 bool
1362 JobCheckCommands(GNode *gn, AbortProc *abortProc)
1364 const char *msg = "make: don't know how to make";
1366 if (!OP_NOP(gn->type)) {
1367 return (true); /* this node does nothing */
1370 if (!Lst_IsEmpty(&gn->commands)) {
1371 return (true); /* this node has no commands */
1374 if (gn->type & OP_LIB) {
1375 return (true);
1379 * No commands. Look for .DEFAULT rule from which we might infer
1380 * commands.
1382 if (DEFAULT != NULL && !Lst_IsEmpty(&DEFAULT->commands)) {
1384 * Make only looks for a .DEFAULT if the node was
1385 * never the target of an operator, so that's what we
1386 * do too. If a .DEFAULT was given, we substitute its
1387 * commands for gn's commands and set the IMPSRC
1388 * variable to be the target's name The DEFAULT node
1389 * acts like a transformation rule, in that gn also
1390 * inherits any attributes or sources attached to
1391 * .DEFAULT itself.
1393 Make_HandleUse(DEFAULT, gn);
1394 Var_Set(IMPSRC, Var_Value(TARGET, gn), gn);
1395 return (true);
1398 if (Dir_MTime(gn) != 0) {
1399 return (true);
1403 * The node wasn't the target of an operator we have
1404 * no .DEFAULT rule to go on and the target doesn't
1405 * already exist. There's nothing more we can do for
1406 * this branch. If the -k flag wasn't given, we stop
1407 * in our tracks, otherwise we just don't update
1408 * this node's parents so they never get examined.
1410 if (gn->type & OP_OPTIONAL) {
1411 fprintf(stdout, "%s %s(ignored)\n", msg, gn->name);
1412 fflush(stdout);
1413 return (true);
1416 if (keepgoing) {
1417 fprintf(stdout, "%s %s(continuing)\n", msg, gn->name);
1418 fflush(stdout);
1419 return (false);
1422 #if OLD_JOKE
1423 if (strcmp(gn->name,"love") == 0)
1424 abortProc("Not war.");
1425 else
1426 #endif
1427 abortProc("%s %s. Stop", msg, gn->name);
1429 return (false);
1433 * JobExec
1434 * Execute the shell for the given job. Called from JobStart and
1435 * JobRestart.
1437 * Side Effects:
1438 * A shell is executed, outputs is altered and the Job structure added
1439 * to the job table.
1441 static void
1442 JobExec(Job *job, char **argv)
1444 struct Shell *shell = job->shell;
1445 ProcStuff ps;
1447 if (DEBUG(JOB)) {
1448 int i;
1450 DEBUGF(JOB, ("Running %s\n", job->node->name));
1451 DEBUGF(JOB, ("\tCommand: "));
1452 for (i = 0; argv[i] != NULL; i++) {
1453 DEBUGF(JOB, ("%s ", argv[i]));
1455 DEBUGF(JOB, ("\n"));
1459 * Some jobs produce no output and it's disconcerting to have
1460 * no feedback of their running (since they produce no output, the
1461 * banner with their name in it never appears). This is an attempt to
1462 * provide that feedback, even if nothing follows it.
1464 if (lastNode != job->node && (job->flags & JOB_FIRST) &&
1465 !(job->flags & JOB_SILENT)) {
1466 MESSAGE(stdout, job->node);
1467 lastNode = job->node;
1470 ps.in = FILENO(job->cmdFILE);
1471 if (usePipes) {
1473 * Set up the child's output to be routed through the
1474 * pipe we've created for it.
1476 ps.out = job->outPipe;
1477 } else {
1479 * We're capturing output in a file, so we duplicate
1480 * the descriptor to the temporary file into the
1481 * standard output.
1483 ps.out = job->outFd;
1485 ps.err = STDERR_FILENO;
1487 ps.merge_errors = 1;
1488 ps.pgroup = 1;
1489 ps.searchpath = 0;
1491 ps.argv = argv;
1492 ps.argv_free = 0;
1495 * Fork. Warning since we are doing vfork() instead of fork(),
1496 * do not allocate memory in the child process!
1498 if ((ps.child_pid = vfork()) == -1) {
1499 Punt("Cannot fork");
1501 } else if (ps.child_pid == 0) {
1503 * Child
1505 if (fifoFd >= 0)
1506 close(fifoFd);
1508 Proc_Exec(&ps, shell);
1509 /* NOTREACHED */
1511 } else {
1513 * Parent
1515 job->pid = ps.child_pid;
1517 if (usePipes && (job->flags & JOB_FIRST)) {
1519 * The first time a job is run for a node, we set the
1520 * current position in the buffer to the beginning and
1521 * mark another stream to watch in the outputs mask.
1523 job->curPos = 0;
1524 FD_SET(job->inPipe, &outputs);
1527 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1528 fclose(job->cmdFILE);
1529 job->cmdFILE = NULL;
1533 * Now the job is actually running, add it to the table.
1535 nJobs += 1;
1536 TAILQ_INSERT_TAIL(&jobs, job, link);
1537 if (nJobs == maxJobs) {
1538 jobFull = true;
1544 * JobMakeArgv
1545 * Create the argv needed to execute the shell for a given job.
1547 static void
1548 JobMakeArgv(Job *job, char **argv)
1550 struct Shell *shell = job->shell;
1551 int argc;
1552 static char args[10]; /* For merged arguments */
1554 argv[0] = shell->name;
1555 argc = 1;
1557 if ((shell->exit && *shell->exit != '-') ||
1558 (shell->echo && *shell->echo != '-')) {
1560 * At least one of the flags doesn't have a minus before it, so
1561 * merge them together. Have to do this because the *(&(@*#*&#$#
1562 * Bourne shell thinks its second argument is a file to source.
1563 * Grrrr. Note the ten-character limitation on the combined
1564 * arguments.
1566 sprintf(args, "-%s%s", (job->flags & JOB_IGNERR) ? "" :
1567 shell->exit ? shell->exit : "",
1568 (job->flags & JOB_SILENT) ? "" :
1569 shell->echo ? shell->echo : "");
1571 if (args[1]) {
1572 argv[argc] = args;
1573 argc++;
1575 } else {
1576 if (!(job->flags & JOB_IGNERR) && shell->exit) {
1577 argv[argc] = shell->exit;
1578 argc++;
1580 if (!(job->flags & JOB_SILENT) && shell->echo) {
1581 argv[argc] = shell->echo;
1582 argc++;
1585 argv[argc] = NULL;
1589 * JobRestart
1590 * Restart a job that stopped for some reason. The job must be neither
1591 * on the jobs nor on the stoppedJobs list.
1593 * Side Effects:
1594 * jobFull will be set if the job couldn't be run.
1596 static void
1597 JobRestart(Job *job)
1600 if (job->flags & JOB_RESTART) {
1602 * Set up the control arguments to the shell. This is based on
1603 * the flags set earlier for this job. If the JOB_IGNERR flag
1604 * is clear, the 'exit' flag of the shell is used to
1605 * cause it to exit upon receiving an error. If the JOB_SILENT
1606 * flag is clear, the 'echo' flag of the shell is used
1607 * to get it to start echoing as soon as it starts
1608 * processing commands.
1610 char *argv[4];
1612 JobMakeArgv(job, argv);
1614 DEBUGF(JOB, ("Restarting %s...", job->node->name));
1615 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL)) {
1617 * Not allowed to run -- put it back on the hold
1618 * queue and mark the table full
1620 DEBUGF(JOB, ("holding\n"));
1621 TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1622 jobFull = true;
1623 DEBUGF(JOB, ("Job queue is full.\n"));
1624 return;
1625 } else {
1627 * Job may be run locally.
1629 DEBUGF(JOB, ("running locally\n"));
1631 JobExec(job, argv);
1633 } else {
1635 * The job has stopped and needs to be restarted.
1636 * Why it stopped, we don't know...
1638 DEBUGF(JOB, ("Resuming %s...", job->node->name));
1639 if ((nJobs < maxJobs || ((job->flags & JOB_SPECIAL) &&
1640 maxJobs == 0)) && nJobs != maxJobs) {
1642 * If we haven't reached the concurrency limit already
1643 * (or the job must be run and maxJobs is 0), it's ok
1644 * to resume it.
1646 bool error;
1647 int status;
1649 error = (KILL(job->pid, SIGCONT) != 0);
1651 if (!error) {
1653 * Make sure the user knows we've continued
1654 * the beast and actually put the thing in the
1655 * job table.
1657 job->flags |= JOB_CONTINUING;
1658 status = 0;
1659 W_SETTERMSIG(&status, SIGCONT);
1660 JobFinish(job, &status);
1662 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1663 DEBUGF(JOB, ("done\n"));
1664 } else {
1665 Error("couldn't resume %s: %s",
1666 job->node->name, strerror(errno));
1667 status = 0;
1668 W_SETEXITSTATUS(&status, 1);
1669 JobFinish(job, &status);
1671 } else {
1673 * Job cannot be restarted. Mark the table as full and
1674 * place the job back on the list of stopped jobs.
1676 DEBUGF(JOB, ("table full\n"));
1677 TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1678 jobFull = true;
1679 DEBUGF(JOB, ("Job queue is full.\n"));
1685 * JobStart
1686 * Start a target-creation process going for the target described
1687 * by the graph node gn.
1689 * Results:
1690 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1691 * if there isn't actually anything left to do for the job and
1692 * JOB_RUNNING if the job has been started.
1694 * Side Effects:
1695 * A new Job node is created and added to the list of running
1696 * jobs. PMake is forked and a child shell created.
1698 static int
1699 JobStart(GNode *gn, int flags, Job *previous)
1701 Job *job; /* new job descriptor */
1702 char *argv[4]; /* Argument vector to shell */
1703 bool cmdsOK; /* true if the nodes commands were all right */
1704 bool noExec; /* Set true if we decide not to run the job */
1705 int tfd; /* File descriptor for temp file */
1706 LstNode *ln;
1707 char tfile[sizeof(TMPPAT)];
1709 if (previous == NULL) {
1710 job = emalloc(sizeof(Job));
1711 flags |= JOB_FIRST;
1712 } else {
1713 previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1714 job = previous;
1717 job->shell = commandShell;
1718 job->node = gn;
1719 job->tailCmds = NULL;
1722 * Set the initial value of the flags for this job based on the global
1723 * ones and the node's attributes... Any flags supplied by the caller
1724 * are also added to the field.
1726 job->flags = 0;
1727 if (Targ_Ignore(gn)) {
1728 job->flags |= JOB_IGNERR;
1730 if (Targ_Silent(gn)) {
1731 job->flags |= JOB_SILENT;
1733 job->flags |= flags;
1736 * Check the commands now so any attributes from .DEFAULT have a chance
1737 * to migrate to the node.
1739 if (!compatMake && (job->flags & JOB_FIRST)) {
1740 cmdsOK = JobCheckCommands(gn, Error);
1741 } else {
1742 cmdsOK = true;
1746 * If the -n flag wasn't given, we open up OUR (not the child's)
1747 * temporary file to stuff commands in it. The thing is rd/wr so we
1748 * don't need to reopen it to feed it to the shell. If the -n flag
1749 * *was* given, we just set the file to be stdout. Cute, huh?
1751 if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1753 * We're serious here, but if the commands were bogus, we're
1754 * also dead...
1756 if (!cmdsOK) {
1757 DieHorribly();
1760 strcpy(tfile, TMPPAT);
1761 if ((tfd = mkstemp(tfile)) == -1)
1762 Punt("Cannot create temp file: %s", strerror(errno));
1763 job->cmdFILE = fdopen(tfd, "w+");
1764 eunlink(tfile);
1765 if (job->cmdFILE == NULL) {
1766 close(tfd);
1767 Punt("Could not open %s", tfile);
1769 fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1771 * Send the commands to the command file, flush all its
1772 * buffers then rewind and remove the thing.
1774 noExec = false;
1777 * Used to be backwards; replace when start doing multiple
1778 * commands per shell.
1780 if (compatMake) {
1782 * Be compatible: If this is the first time for this
1783 * node, verify its commands are ok and open the
1784 * commands list for sequential access by later
1785 * invocations of JobStart. Once that is done, we take
1786 * the next command off the list and print it to the
1787 * command file. If the command was an ellipsis, note
1788 * that there's nothing more to execute.
1790 if (job->flags & JOB_FIRST)
1791 gn->compat_command = Lst_First(&gn->commands);
1792 else
1793 gn->compat_command =
1794 Lst_Succ(gn->compat_command);
1796 if (gn->compat_command == NULL ||
1797 JobPrintCommand(Lst_Datum(gn->compat_command), job))
1798 noExec = true;
1800 if (noExec && !(job->flags & JOB_FIRST)) {
1802 * If we're not going to execute anything, the
1803 * job is done and we need to close down the
1804 * various file descriptors we've opened for
1805 * output, then call JobDoOutput to catch the
1806 * final characters or send the file to the
1807 * screen... Note that the i/o streams are only
1808 * open if this isn't the first job. Note also
1809 * that this could not be done in
1810 * Job_CatchChildren b/c it wasn't clear if
1811 * there were more commands to execute or not...
1813 JobClose(job);
1815 } else {
1817 * We can do all the commands at once. hooray for sanity
1819 numCommands = 0;
1820 LST_FOREACH(ln, &gn->commands) {
1821 if (JobPrintCommand(Lst_Datum(ln), job))
1822 break;
1826 * If we didn't print out any commands to the shell
1827 * script, there's not much point in executing the
1828 * shell, is there?
1830 if (numCommands == 0) {
1831 noExec = true;
1835 } else if (noExecute) {
1837 * Not executing anything -- just print all the commands to
1838 * stdout in one fell swoop. This will still set up
1839 * job->tailCmds correctly.
1841 if (lastNode != gn) {
1842 MESSAGE(stdout, gn);
1843 lastNode = gn;
1845 job->cmdFILE = stdout;
1848 * Only print the commands if they're ok, but don't die if
1849 * they're not -- just let the user know they're bad and keep
1850 * going. It doesn't do any harm in this case and may do
1851 * some good.
1853 if (cmdsOK) {
1854 LST_FOREACH(ln, &gn->commands) {
1855 if (JobPrintCommand(Lst_Datum(ln), job))
1856 break;
1860 * Don't execute the shell, thank you.
1862 noExec = true;
1864 } else {
1866 * Just touch the target and note that no shell should be
1867 * executed. Set cmdFILE to stdout to make life easier. Check
1868 * the commands, too, but don't die if they're no good -- it
1869 * does no harm to keep working up the graph.
1871 job->cmdFILE = stdout;
1872 JobTouch(gn, job->flags & JOB_SILENT);
1873 noExec = true;
1877 * If we're not supposed to execute a shell, don't.
1879 if (noExec) {
1881 * Unlink and close the command file if we opened one
1883 if (job->cmdFILE != stdout) {
1884 if (job->cmdFILE != NULL)
1885 fclose(job->cmdFILE);
1886 } else {
1887 fflush(stdout);
1891 * We only want to work our way up the graph if we aren't here
1892 * because the commands for the job were no good.
1894 if (cmdsOK) {
1895 if (aborting == 0) {
1896 for (ln = job->tailCmds; ln != NULL;
1897 ln = LST_NEXT(ln)) {
1898 Lst_AtEnd(&postCommands->commands,
1899 Buf_Peel(Var_Subst(Lst_Datum(ln),
1900 job->node, false)));
1902 job->node->made = MADE;
1903 Make_Update(job->node);
1905 free(job);
1906 return(JOB_FINISHED);
1907 } else {
1908 free(job);
1909 return(JOB_ERROR);
1911 } else {
1912 fflush(job->cmdFILE);
1916 * Set up the control arguments to the shell. This is based on the flags
1917 * set earlier for this job.
1919 JobMakeArgv(job, argv);
1922 * If we're using pipes to catch output, create the pipe by which we'll
1923 * get the shell's output. If we're using files, print out that we're
1924 * starting a job and then set up its temporary-file name.
1926 if (!compatMake || (job->flags & JOB_FIRST)) {
1927 if (usePipes) {
1928 int fd[2];
1930 if (pipe(fd) == -1)
1931 Punt("Cannot create pipe: %s", strerror(errno));
1932 job->inPipe = fd[0];
1933 job->outPipe = fd[1];
1934 fcntl(job->inPipe, F_SETFD, 1);
1935 fcntl(job->outPipe, F_SETFD, 1);
1936 } else {
1937 fprintf(stdout, "Remaking `%s'\n", gn->name);
1938 fflush(stdout);
1939 strcpy(job->outFile, TMPPAT);
1940 if ((job->outFd = mkstemp(job->outFile)) == -1)
1941 Punt("cannot create temp file: %s",
1942 strerror(errno));
1943 fcntl(job->outFd, F_SETFD, 1);
1947 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL) && maxJobs != 0) {
1949 * We've hit the limit of concurrency, so put the job on hold
1950 * until some other job finishes. Note that the special jobs
1951 * (.BEGIN, .INTERRUPT and .END) may be run even when the
1952 * limit has been reached (e.g. when maxJobs == 0).
1954 jobFull = true;
1956 DEBUGF(JOB, ("Can only run job locally.\n"));
1957 job->flags |= JOB_RESTART;
1958 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1959 } else {
1960 if (nJobs >= maxJobs) {
1962 * If we're running this job as a special case
1963 * (see above), at least say the table is full.
1965 jobFull = true;
1966 DEBUGF(JOB, ("Local job queue is full.\n"));
1968 JobExec(job, argv);
1970 return (JOB_RUNNING);
1973 static char *
1974 JobOutput(Job *job, char *cp, char *endp, int msg)
1976 struct Shell *shell = job->shell;
1977 char *ecp;
1979 if (shell->noPrint) {
1980 ecp = strstr(cp, shell->noPrint);
1981 while (ecp != NULL) {
1982 if (cp != ecp) {
1983 *ecp = '\0';
1984 if (msg && job->node != lastNode) {
1985 MESSAGE(stdout, job->node);
1986 lastNode = job->node;
1989 * The only way there wouldn't be a newline
1990 * after this line is if it were the last in
1991 * the buffer. However, since the non-printable
1992 * comes after it, there must be a newline, so
1993 * we don't print one.
1995 fprintf(stdout, "%s", cp);
1996 fflush(stdout);
1998 cp = ecp + strlen(shell->noPrint);
1999 if (cp != endp) {
2001 * Still more to print, look again after
2002 * skipping the whitespace following the
2003 * non-printable command....
2005 cp++;
2006 while (*cp == ' ' || *cp == '\t' ||
2007 *cp == '\n') {
2008 cp++;
2010 ecp = strstr(cp, shell->noPrint);
2011 } else {
2012 return (cp);
2016 return (cp);
2020 * JobDoOutput
2021 * This function is called at different times depending on
2022 * whether the user has specified that output is to be collected
2023 * via pipes or temporary files. In the former case, we are called
2024 * whenever there is something to read on the pipe. We collect more
2025 * output from the given job and store it in the job's outBuf. If
2026 * this makes up a line, we print it tagged by the job's identifier,
2027 * as necessary.
2028 * If output has been collected in a temporary file, we open the
2029 * file and read it line by line, transferring it to our own
2030 * output channel until the file is empty. At which point we
2031 * remove the temporary file.
2032 * In both cases, however, we keep our figurative eye out for the
2033 * 'noPrint' line for the shell from which the output came. If
2034 * we recognize a line, we don't print it. If the command is not
2035 * alone on the line (the character after it is not \0 or \n), we
2036 * do print whatever follows it.
2038 * Side Effects:
2039 * curPos may be shifted as may the contents of outBuf.
2041 static void
2042 JobDoOutput(Job *job, bool finish)
2044 bool gotNL = false; /* true if got a newline */
2045 bool fbuf; /* true if our buffer filled up */
2046 int nr; /* number of bytes read */
2047 int i; /* auxiliary index into outBuf */
2048 int max; /* limit for i (end of current data) */
2049 int nRead; /* (Temporary) number of bytes read */
2050 FILE *oFILE; /* Stream pointer to shell's output file */
2051 char inLine[132];
2053 if (usePipes) {
2055 * Read as many bytes as will fit in the buffer.
2057 end_loop:
2058 gotNL = false;
2059 fbuf = false;
2061 nRead = read(job->inPipe, &job->outBuf[job->curPos],
2062 JOB_BUFSIZE - job->curPos);
2064 * Check for interrupt here too, because the above read may
2065 * block when the child process is stopped. In this case the
2066 * interrupt will unblock it (we don't use SA_RESTART).
2068 SigHandler();
2070 if (nRead < 0) {
2071 DEBUGF(JOB, ("JobDoOutput(piperead)"));
2072 nr = 0;
2073 } else {
2074 nr = nRead;
2078 * If we hit the end-of-file (the job is dead), we must flush
2079 * its remaining output, so pretend we read a newline if
2080 * there's any output remaining in the buffer.
2081 * Also clear the 'finish' flag so we stop looping.
2083 if (nr == 0 && job->curPos != 0) {
2084 job->outBuf[job->curPos] = '\n';
2085 nr = 1;
2086 finish = false;
2087 } else if (nr == 0) {
2088 finish = false;
2092 * Look for the last newline in the bytes we just got. If there
2093 * is one, break out of the loop with 'i' as its index and
2094 * gotNL set true.
2096 max = job->curPos + nr;
2097 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
2098 if (job->outBuf[i] == '\n') {
2099 gotNL = true;
2100 break;
2101 } else if (job->outBuf[i] == '\0') {
2103 * Why?
2105 job->outBuf[i] = ' ';
2109 if (!gotNL) {
2110 job->curPos += nr;
2111 if (job->curPos == JOB_BUFSIZE) {
2113 * If we've run out of buffer space, we have
2114 * no choice but to print the stuff. sigh.
2116 fbuf = true;
2117 i = job->curPos;
2120 if (gotNL || fbuf) {
2122 * Need to send the output to the screen. Null terminate
2123 * it first, overwriting the newline character if there
2124 * was one. So long as the line isn't one we should
2125 * filter (according to the shell description), we print
2126 * the line, preceded by a target banner if this target
2127 * isn't the same as the one for which we last printed
2128 * something. The rest of the data in the buffer are
2129 * then shifted down to the start of the buffer and
2130 * curPos is set accordingly.
2132 job->outBuf[i] = '\0';
2133 if (i >= job->curPos) {
2134 char *cp;
2136 cp = JobOutput(job, job->outBuf,
2137 &job->outBuf[i], false);
2140 * There's still more in that buffer. This time,
2141 * though, we know there's no newline at the
2142 * end, so we add one of our own free will.
2144 if (*cp != '\0') {
2145 if (job->node != lastNode) {
2146 MESSAGE(stdout, job->node);
2147 lastNode = job->node;
2149 fprintf(stdout, "%s%s", cp,
2150 gotNL ? "\n" : "");
2151 fflush(stdout);
2154 if (i < max - 1) {
2155 /* shift the remaining characters down */
2156 memcpy(job->outBuf, &job->outBuf[i + 1],
2157 max - (i + 1));
2158 job->curPos = max - (i + 1);
2160 } else {
2162 * We have written everything out, so we just
2163 * start over from the start of the buffer.
2164 * No copying. No nothing.
2166 job->curPos = 0;
2169 if (finish) {
2171 * If the finish flag is true, we must loop until we hit
2172 * end-of-file on the pipe. This is guaranteed to happen
2173 * eventually since the other end of the pipe is now
2174 * closed (we closed it explicitly and the child has
2175 * exited). When we do get an EOF, finish will be set
2176 * false and we'll fall through and out.
2178 goto end_loop;
2181 } else {
2183 * We've been called to retrieve the output of the job from the
2184 * temporary file where it's been squirreled away. This consists
2185 * of opening the file, reading the output line by line, being
2186 * sure not to print the noPrint line for the shell we used,
2187 * then close and remove the temporary file. Very simple.
2189 * Change to read in blocks and do FindSubString type things
2190 * as for pipes? That would allow for "@echo -n..."
2192 oFILE = fopen(job->outFile, "r");
2193 if (oFILE != NULL) {
2194 fprintf(stdout, "Results of making %s:\n",
2195 job->node->name);
2196 fflush(stdout);
2198 while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2199 char *cp, *endp, *oendp;
2201 cp = inLine;
2202 oendp = endp = inLine + strlen(inLine);
2203 if (endp[-1] == '\n') {
2204 *--endp = '\0';
2206 cp = JobOutput(job, inLine, endp, false);
2209 * There's still more in that buffer. This time,
2210 * though, we know there's no newline at the
2211 * end, so we add one of our own free will.
2213 fprintf(stdout, "%s", cp);
2214 fflush(stdout);
2215 if (endp != oendp) {
2216 fprintf(stdout, "\n");
2217 fflush(stdout);
2220 fclose(oFILE);
2221 eunlink(job->outFile);
2227 * Job_CatchChildren
2228 * Handle the exit of a child. Called from Make_Make.
2230 * Side Effects:
2231 * The job descriptor is removed from the list of children.
2233 * Notes:
2234 * We do waits, blocking or not, according to the wisdom of our
2235 * caller, until there are no more children to report. For each
2236 * job, call JobFinish to finish things off. This will take care of
2237 * putting jobs on the stoppedJobs queue.
2239 void
2240 Job_CatchChildren(bool block)
2242 pid_t pid; /* pid of dead child */
2243 Job *job; /* job descriptor for dead child */
2244 int status; /* Exit/termination status */
2247 * Don't even bother if we know there's no one around.
2249 if (nJobs == 0) {
2250 return;
2253 for (;;) {
2254 pid = waitpid((pid_t)-1, &status,
2255 (block ? 0 : WNOHANG) | WUNTRACED);
2256 if (pid <= 0)
2257 break;
2259 DEBUGF(JOB, ("Process %jd exited or stopped.\n",
2260 (intmax_t)pid));
2262 TAILQ_FOREACH(job, &jobs, link) {
2263 if (job->pid == pid)
2264 break;
2267 if (job == NULL) {
2268 if (WIFSIGNALED(status) &&
2269 (WTERMSIG(status) == SIGCONT)) {
2270 TAILQ_FOREACH(job, &jobs, link) {
2271 if (job->pid == pid)
2272 break;
2274 if (job == NULL) {
2275 Error("Resumed child (%jd) "
2276 "not in table", (intmax_t)pid);
2277 continue;
2279 TAILQ_REMOVE(&stoppedJobs, job, link);
2280 } else {
2281 Error("Child (%jd) not in table?",
2282 (intmax_t)pid);
2283 continue;
2285 } else {
2286 TAILQ_REMOVE(&jobs, job, link);
2287 nJobs -= 1;
2288 if (fifoFd >= 0 && maxJobs > 1) {
2289 write(fifoFd, "+", 1);
2290 maxJobs--;
2291 if (nJobs >= maxJobs)
2292 jobFull = true;
2293 else
2294 jobFull = false;
2295 } else {
2296 DEBUGF(JOB, ("Job queue is no longer full.\n"));
2297 jobFull = false;
2301 JobFinish(job, &status);
2303 SigHandler();
2307 * Job_CatchOutput
2308 * Catch the output from our children, if we're using
2309 * pipes do so. Otherwise just block time until we get a
2310 * signal(most likely a SIGCHLD) since there's no point in
2311 * just spinning when there's nothing to do and the reaping
2312 * of a child can wait for a while.
2314 * Side Effects:
2315 * Output is read from pipes if we're piping.
2317 void
2318 Job_CatchOutput(int flag)
2320 int nfds;
2321 struct timeval timeout;
2322 fd_set readfds;
2323 Job *job;
2325 fflush(stdout);
2327 if (usePipes) {
2328 readfds = outputs;
2329 timeout.tv_sec = SEL_SEC;
2330 timeout.tv_usec = SEL_USEC;
2331 if (flag && jobFull && fifoFd >= 0)
2332 FD_SET(fifoFd, &readfds);
2334 nfds = select(FD_SETSIZE, &readfds, NULL, NULL, &timeout);
2335 if (nfds == 0) {
2336 /* timeout expired */
2337 SigHandler();
2338 return;
2339 } else if (nfds < 0) {
2340 /* must be EINTR */
2341 SigHandler();
2342 return;
2343 } else {
2344 if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2345 if (--nfds <= 0)
2346 return;
2348 job = TAILQ_FIRST(&jobs);
2349 while (nfds != 0 && job != NULL) {
2350 if (FD_ISSET(job->inPipe, &readfds)) {
2351 JobDoOutput(job, false);
2352 nfds--;
2354 job = TAILQ_NEXT(job, link);
2361 * Job_Make
2362 * Start the creation of a target. Basically a front-end for
2363 * JobStart used by the Make module.
2365 * Side Effects:
2366 * Another job is started.
2368 void
2369 Job_Make(GNode *gn)
2372 JobStart(gn, 0, NULL);
2376 * Job_Init
2377 * Initialize the process module, given a maximum number of jobs.
2379 * Side Effects:
2380 * lists and counters are initialized
2382 void
2383 Job_Init(int maxproc)
2385 GNode *begin; /* node for commands to do at the very start */
2386 const char *env;
2388 fifoFd = -1;
2389 env = getenv("MAKE_JOBS_FIFO");
2391 if (env == NULL && maxproc > 1) {
2393 * We did not find the environment variable so we are the
2394 * leader. Create the fifo, open it, write one char per
2395 * allowed job into the pipe.
2397 fifoFd = mkfifotemp(fifoName);
2398 if (fifoFd < 0) {
2399 env = NULL;
2400 } else {
2401 fifoMaster = 1;
2402 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2403 env = fifoName;
2404 if (setenv("MAKE_JOBS_FIFO", env, 1) == -1)
2405 Punt("setenv: MAKE_JOBS_FIFO: can't allocate memory");
2406 while (maxproc-- > 0) {
2407 write(fifoFd, "+", 1);
2409 /* The master make does not get a magic token */
2410 jobFull = true;
2411 maxJobs = 0;
2414 } else if (env != NULL) {
2416 * We had the environment variable so we are a slave.
2417 * Open fifo and give ourselves a magic token which represents
2418 * the token our parent make has grabbed to start his make
2419 * process. Otherwise the sub-makes would gobble up tokens and
2420 * the proper number of tokens to specify to -j would depend
2421 * on the depth of the tree and the order of execution.
2423 fifoFd = open(env, O_RDWR, 0);
2424 if (fifoFd >= 0) {
2425 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2426 maxJobs = 1;
2427 jobFull = false;
2430 if (fifoFd <= 0) {
2431 maxJobs = maxproc;
2432 jobFull = false;
2433 } else {
2435 nJobs = 0;
2437 aborting = 0;
2438 errors = 0;
2440 lastNode = NULL;
2442 if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2444 * If only one job can run at a time, there's no need for a
2445 * banner, no is there?
2447 targFmt = "";
2448 } else {
2449 targFmt = TARG_FMT;
2452 begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2454 if (begin != NULL) {
2455 JobStart(begin, JOB_SPECIAL, NULL);
2456 while (nJobs) {
2457 Job_CatchOutput(0);
2458 Job_CatchChildren(!usePipes);
2461 postCommands = Targ_FindNode(".END", TARG_CREATE);
2465 * Job_Full
2466 * See if the job table is full. It is considered full if it is OR
2467 * if we are in the process of aborting OR if we have
2468 * reached/exceeded our local quota. This prevents any more jobs
2469 * from starting up.
2471 * Results:
2472 * true if the job table is full, false otherwise
2474 bool
2475 Job_Full(void)
2477 char c;
2478 int i;
2480 if (aborting)
2481 return (aborting);
2482 if (fifoFd >= 0 && jobFull) {
2483 i = read(fifoFd, &c, 1);
2484 if (i > 0) {
2485 maxJobs++;
2486 jobFull = false;
2489 return (jobFull);
2493 * Job_Empty
2494 * See if the job table is empty. Because the local concurrency may
2495 * be set to 0, it is possible for the job table to become empty,
2496 * while the list of stoppedJobs remains non-empty. In such a case,
2497 * we want to restart as many jobs as we can.
2499 * Results:
2500 * true if it is. false if it ain't.
2502 bool
2503 Job_Empty(void)
2506 if (nJobs == 0) {
2507 if (!TAILQ_EMPTY(&stoppedJobs) && !aborting) {
2509 * The job table is obviously not full if it has no
2510 * jobs in it...Try and restart the stopped jobs.
2512 jobFull = false;
2513 JobRestartJobs();
2514 return (false);
2515 } else {
2516 return (true);
2518 } else {
2519 return (false);
2524 * Job_Finish
2525 * Do final processing such as the running of the commands
2526 * attached to the .END target.
2528 * Results:
2529 * Number of errors reported.
2532 Job_Finish(void)
2535 if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
2536 if (errors) {
2537 Error("Errors reported so .END ignored");
2538 } else {
2539 JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
2541 while (nJobs) {
2542 Job_CatchOutput(0);
2543 Job_CatchChildren(!usePipes);
2547 if (fifoFd >= 0) {
2548 close(fifoFd);
2549 fifoFd = -1;
2550 if (fifoMaster)
2551 unlink(fifoName);
2553 return (errors);
2557 * Job_Wait
2558 * Waits for all running jobs to finish and returns. Sets 'aborting'
2559 * to ABORT_WAIT to prevent other jobs from starting.
2561 * Side Effects:
2562 * Currently running jobs finish.
2564 void
2565 Job_Wait(void)
2568 aborting = ABORT_WAIT;
2569 while (nJobs != 0) {
2570 Job_CatchOutput(0);
2571 Job_CatchChildren(!usePipes);
2573 aborting = 0;
2577 * Job_AbortAll
2578 * Abort all currently running jobs without handling output or anything.
2579 * This function is to be called only in the event of a major
2580 * error.
2582 * Side Effects:
2583 * All children are killed, not just the firstborn
2585 void
2586 Job_AbortAll(void)
2588 Job *job; /* the job descriptor in that element */
2589 int status;
2591 aborting = ABORT_ERROR;
2593 if (nJobs) {
2594 TAILQ_FOREACH(job, &jobs, link) {
2596 * kill the child process with increasingly drastic
2597 * signals to make darn sure it's dead.
2599 KILL(job->pid, SIGINT);
2600 KILL(job->pid, SIGKILL);
2605 * Catch as many children as want to report in at first, then give up
2607 while (waitpid((pid_t)-1, &status, WNOHANG) > 0)
2612 * JobRestartJobs
2613 * Tries to restart stopped jobs if there are slots available.
2614 * Note that this tries to restart them regardless of pending errors.
2615 * It's not good to leave stopped jobs lying around!
2617 * Side Effects:
2618 * Resumes(and possibly migrates) jobs.
2620 static void
2621 JobRestartJobs(void)
2623 Job *job;
2625 while (!jobFull && (job = TAILQ_FIRST(&stoppedJobs)) != NULL) {
2626 DEBUGF(JOB, ("Job queue is not full. "
2627 "Restarting a stopped job.\n"));
2628 TAILQ_REMOVE(&stoppedJobs, job, link);
2629 JobRestart(job);
2634 * Cmd_Exec
2635 * Execute the command in cmd, and return the output of that command
2636 * in a string.
2638 * Results:
2639 * A string containing the output of the command, or the empty string
2640 * If error is not NULL, it contains the reason for the command failure
2641 * Any output sent to stderr in the child process is passed to stderr,
2642 * and not captured in the string.
2644 * Side Effects:
2645 * The string must be freed by the caller.
2647 Buffer *
2648 Cmd_Exec(const char *cmd, const char **error)
2650 Shell *shell = commandShell;
2651 int fds[2]; /* Pipe streams */
2652 Buffer *buf; /* buffer to store the result */
2653 ssize_t rcnt;
2654 ProcStuff ps;
2656 *error = NULL;
2657 buf = Buf_Init(0);
2660 * Open a pipe for fetching its output
2662 if (pipe(fds) == -1) {
2663 *error = "Couldn't create pipe for \"%s\"";
2664 return (buf);
2667 /* Set close-on-exec on read side of pipe. */
2668 fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC);
2670 ps.in = STDIN_FILENO;
2671 ps.out = fds[1];
2672 ps.err = STDERR_FILENO;
2674 ps.merge_errors = 0;
2675 ps.pgroup = 0;
2676 ps.searchpath = 0;
2678 /* Set up arguments for shell */
2679 ps.argv = emalloc(4 * sizeof(char *));
2680 ps.argv[0] = strdup(shell->name);
2681 ps.argv[1] = strdup("-c");
2682 ps.argv[2] = strdup(cmd);
2683 ps.argv[3] = NULL;
2684 ps.argv_free = 1;
2687 * Fork. Warning since we are doing vfork() instead of fork(),
2688 * do not allocate memory in the child process!
2690 if ((ps.child_pid = vfork()) == -1) {
2691 *error = "Couldn't exec \"%s\"";
2693 } else if (ps.child_pid == 0) {
2695 * Child
2697 Proc_Exec(&ps, shell);
2698 /* NOTREACHED */
2700 } else {
2701 free(ps.argv[2]);
2702 free(ps.argv[1]);
2703 free(ps.argv[0]);
2704 free(ps.argv);
2706 close(fds[1]); /* No need for the writing half of the pipe. */
2708 do {
2709 char result[BUFSIZ];
2711 rcnt = read(fds[0], result, sizeof(result));
2712 if (rcnt != -1)
2713 Buf_AddBytes(buf, (size_t)rcnt, result);
2714 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
2716 if (rcnt == -1)
2717 *error = "Error reading shell's output for \"%s\"";
2720 * Close the input side of the pipe.
2722 close(fds[0]);
2724 ProcWait(&ps);
2725 if (ps.child_status)
2726 *error = "\"%s\" returned non-zero status";
2728 Buf_StripNewlines(buf);
2731 return (buf);
2735 * Handle interrupts during the creation of the target and remove
2736 * it if it ain't precious. The default handler for the signal is
2737 * reinstalled, and the signal is raised again.
2739 * Side Effects:
2740 * The target is removed and the process exits. If the cause was SIGINT
2741 * and .INTERRUPT: exists its commands are run.
2743 static void
2744 CompatInterrupt(void)
2746 GNode *gn;
2747 int signo;
2749 if (got_SIGINT) {
2750 got_SIGINT = 0;
2751 signo = SIGINT;
2753 } else if (got_SIGHUP) {
2754 got_SIGHUP = 0;
2755 signo = SIGHUP;
2757 } else if (got_SIGQUIT) {
2758 got_SIGQUIT = 0;
2759 signo = SIGQUIT;
2761 } else if (got_SIGTERM) {
2762 got_SIGTERM = 0;
2763 signo = SIGTERM;
2765 } else {
2766 return; /* no signal delivered */
2769 if (curTarg != NULL && !Targ_Precious(curTarg)) {
2770 const char *file = Var_Value(TARGET, curTarg);
2772 if (!noExecute && eunlink(file) != -1) {
2773 printf("*** %s removed\n", file);
2778 * Run .INTERRUPT only if hit with interrupt signal
2780 if (signo == SIGINT) {
2781 gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2782 if (gn != NULL) {
2783 Compat_RunCmds(gn, NULL);
2787 if (signo == SIGQUIT) {
2789 * We do not raise SIGQUIT, since on systems that create core
2790 * files upon receipt of SIGQUIT, the core from make would
2791 * conflict with a core file from the command that was
2792 * running when the SIGQUIT arrived.
2794 * This is true even on BSD systems that name the core file
2795 * after the program, since we might be calling make
2796 * recursively.
2798 exit(2);
2801 signal(signo, SIG_DFL);
2802 kill(getpid(), signo);
2804 /* NOTREACHED */
2808 * Execute the next command for a target. If the command returns an
2809 * error, the node's made field is set to ERROR and creation stops.
2810 * The node from which the command came is also given. This is used
2811 * to execute the commands in compat mode and when executing commands
2812 * with the '+' flag in non-compat mode. In these modes each command
2813 * line should be executed by its own shell. We do some optimization here:
2814 * if the shell description defines both a string of meta characters and
2815 * a list of builtins and the command line neither contains a meta character
2816 * nor starts with one of the builtins then we execute the command directly
2817 * without invoking a shell.
2819 * Results:
2820 * 0 if the command succeeded, 1 if an error occurred.
2822 * Side Effects:
2823 * The node's 'made' field may be set to ERROR.
2825 static int
2826 Compat_RunCommand(GNode *gn, const char cmd[], GNode *ENDNode)
2828 Shell *shell = commandShell;
2829 ArgArray aa;
2830 char *cmdStart; /* Start of expanded command */
2831 bool silent; /* Don't print command */
2832 bool doit; /* Execute even in -n */
2833 bool errCheck; /* Check errors */
2834 int status; /* Description of child's death */
2835 LstNode *cmdNode; /* Node where current cmd is located */
2836 char **av; /* Argument vector for thing to exec */
2837 ProcStuff ps;
2838 char *line;
2840 cmdNode = Lst_Member(&gn->commands, cmd);
2842 cmdStart = Buf_Peel(Var_Subst(cmd, gn, false));
2843 if (cmdStart[0] == '\0') {
2844 free(cmdStart);
2845 Error("%s expands to empty string", cmd);
2846 return (0);
2849 Lst_Replace(cmdNode, cmdStart);
2851 if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
2852 if (ENDNode != NULL) {
2853 Lst_AtEnd(&ENDNode->commands, cmdStart);
2855 return (0);
2858 if (strcmp(cmdStart, "...") == 0) {
2859 gn->type |= OP_SAVE_CMDS;
2860 return (0); /* any further commands are deferred */
2863 line = cmdStart;
2864 silent = gn->type & OP_SILENT;
2865 doit = false;
2866 errCheck = !(gn->type & OP_IGNORE);
2868 while (*line == '@' || *line == '-' || *line == '+') {
2869 switch (*line) {
2871 case '@':
2872 silent = DEBUG(LOUD) ? false : true;
2873 break;
2875 case '-':
2876 errCheck = false;
2877 break;
2879 case '+':
2880 doit = true;
2881 break;
2883 line++;
2886 while (isspace((unsigned char)*line))
2887 line++;
2889 if (noExecute && doit == false) {
2890 /* Just print out the command */
2891 printf("%s\n", line);
2892 fflush(stdout);
2893 return (0);
2896 if (silent == false) {
2898 * Print the command before echoing if we're not supposed to
2899 * be quiet for this one.
2901 printf("%s\n", line);
2902 fflush(stdout);
2905 if (shell->meta == NULL || strpbrk(line, shell->meta) == NULL) {
2906 char **p;
2907 char **sh_builtin = shell->builtins.argv + 1;
2910 * Break the command into words to form an argument
2911 * vector we can execute.
2913 brk_string(&aa, line, true);
2914 av = aa.argv + 1;
2916 for (p = sh_builtin; *p != 0; p++) {
2917 if (strcmp(av[0], *p) == 0) {
2919 * This command must be passed by the shell
2920 * for other reasons.. or.. possibly not at
2921 * all.
2923 av = NULL;
2924 break;
2927 } else {
2929 * We found a "meta" character and need to pass the command
2930 * off to the shell.
2932 av = NULL;
2935 ps.in = STDIN_FILENO;
2936 ps.out = STDOUT_FILENO;
2937 ps.err = STDERR_FILENO;
2939 ps.merge_errors = 0;
2940 ps.pgroup = 0;
2941 ps.searchpath = 1;
2943 if (av == NULL) {
2945 * We give the shell the -e flag as well as -c if it's
2946 * supposed to exit when it hits an error.
2948 ps.argv = emalloc(4 * sizeof(char *));
2949 ps.argv[0] = strdup(shell->path);
2950 ps.argv[1] = strdup(errCheck ? "-ec" : "-c");
2951 ps.argv[2] = strdup(line);
2952 ps.argv[3] = NULL;
2953 ps.argv_free = 1;
2954 } else {
2955 ps.argv = av;
2956 ps.argv_free = 0;
2958 ps.errCheck = errCheck;
2961 * Fork and execute the single command. If the fork fails, we abort.
2962 * Warning since we are doing vfork() instead of fork(),
2963 * do not allocate memory in the child process!
2965 if ((ps.child_pid = vfork()) == -1) {
2966 Fatal("Could not fork");
2968 } else if (ps.child_pid == 0) {
2970 * Child
2972 Proc_Exec(&ps, shell);
2973 /* NOTREACHED */
2975 } else {
2976 if (ps.argv_free) {
2977 free(ps.argv[2]);
2978 free(ps.argv[1]);
2979 free(ps.argv[0]);
2980 free(ps.argv);
2981 } else {
2982 ArgArray_Done(&aa);
2986 * we need to print out the command associated with this
2987 * Gnode in Targ_PrintCmd from Targ_PrintGraph when debugging
2988 * at level g2, in main(), Fatal() and DieHorribly(),
2989 * therefore do not free it when debugging.
2991 if (!DEBUG(GRAPH2)) {
2992 free(cmdStart);
2996 * The child is off and running. Now all we can do is wait...
2997 * Block until child has terminated, or a signal is received.
2999 while (ProcWait(&ps) < 0) {
3000 CompatInterrupt(); /* check on the signal */
3004 * Decode and report the reason child exited, then
3005 * indicate how we handled it.
3007 if (WIFEXITED(ps.child_status)) {
3008 status = WEXITSTATUS(ps.child_status);
3009 if (status == 0) {
3010 return (0);
3011 } else {
3012 printf("*** Error code %d", status);
3014 } else if (WIFSTOPPED(ps.child_status)) {
3015 /* can't happen since WUNTRACED isn't set */
3016 status = WSTOPSIG(ps.child_status);
3017 } else {
3018 status = WTERMSIG(ps.child_status);
3019 printf("*** Signal %d", status);
3022 if (ps.errCheck) {
3023 gn->made = ERROR;
3024 if (keepgoing) {
3026 * Abort the current
3027 * target, but let
3028 * others continue.
3030 printf(" (continuing)\n");
3032 return (status);
3033 } else {
3035 * Continue executing
3036 * commands for this target.
3037 * If we return 0, this will
3038 * happen...
3040 printf(" (ignored)\n");
3041 return (0);
3047 * CompatMake
3048 * Make a target, given the parent, to abort if necessary.
3050 * Side Effects:
3051 * If an error is detected and not being ignored, the process exits.
3053 static void
3054 CompatMake(GNode *gn, GNode *pgn, GNode *ENDNode, bool queryFlag)
3056 LstNode *ln;
3058 if (gn->type & OP_USE) {
3059 Make_HandleUse(gn, pgn);
3061 } else if (gn->made == UNMADE) {
3063 * First mark ourselves to be made, then apply whatever
3064 * transformations the suffix module thinks are necessary.
3065 * Once that's done, we can descend and make all our children.
3066 * If any of them has an error but the -k flag was given, our
3067 * 'make' field will be set false again. This is our signal to
3068 * not attempt to do anything but abort our parent as well.
3070 gn->make = true;
3071 gn->made = BEINGMADE;
3072 Suff_FindDeps(gn);
3073 LST_FOREACH(ln, &gn->children)
3074 CompatMake(Lst_Datum(ln), gn, ENDNode, queryFlag);
3075 if (!gn->make) {
3076 gn->made = ABORTED;
3077 pgn->make = false;
3078 return;
3081 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3082 Var_Set(IMPSRC, Var_Value(TARGET, gn), pgn);
3086 * All the children were made ok. Now cmtime contains the
3087 * modification time of the newest child, we need to find out
3088 * if we exist and when we were modified last. The criteria for
3089 * datedness are defined by the Make_OODate function.
3091 DEBUGF(MAKE, ("Examining %s...", gn->name));
3092 if (!Make_OODate(gn)) {
3093 gn->made = UPTODATE;
3094 DEBUGF(MAKE, ("up-to-date.\n"));
3095 return;
3096 } else {
3097 DEBUGF(MAKE, ("out-of-date.\n"));
3101 * If the user is just seeing if something is out-of-date,
3102 * exit now to tell him/her "yes".
3104 if (queryFlag) {
3105 exit(1);
3109 * We need to be re-made. We also have to make sure we've got
3110 * a $? variable. To be nice, we also define the $> variable
3111 * using Make_DoAllVar().
3113 Make_DoAllVar(gn);
3116 * Alter our type to tell if errors should be ignored or things
3117 * should not be printed so Compat_RunCommand knows what to do.
3119 if (Targ_Ignore(gn)) {
3120 gn->type |= OP_IGNORE;
3122 if (Targ_Silent(gn)) {
3123 gn->type |= OP_SILENT;
3126 if (JobCheckCommands(gn, Fatal)) {
3128 * Our commands are ok, but we still have to worry
3129 * about the -t flag...
3131 if (touchFlag) {
3132 JobTouch(gn, gn->type & OP_SILENT);
3133 } else {
3134 curTarg = gn;
3135 Compat_RunCmds(gn, ENDNode);
3136 curTarg = NULL;
3138 } else {
3139 gn->made = ERROR;
3142 if (gn->made != ERROR) {
3144 * If the node was made successfully, mark it so, update
3145 * its modification time and timestamp all its parents.
3146 * Note that for .ZEROTIME targets, the timestamping
3147 * isn't done. This is to keep its state from affecting
3148 * that of its parent.
3150 gn->made = MADE;
3151 #ifndef RECHECK
3153 * We can't re-stat the thing, but we can at least take
3154 * care of rules where a target depends on a source that
3155 * actually creates the target, but only if it has
3156 * changed, e.g.
3158 * parse.h : parse.o
3160 * parse.o : parse.y
3161 * yacc -d parse.y
3162 * cc -c y.tab.c
3163 * mv y.tab.o parse.o
3164 * cmp -s y.tab.h parse.h || mv y.tab.h parse.h
3166 * In this case, if the definitions produced by yacc
3167 * haven't changed from before, parse.h won't have been
3168 * updated and gn->mtime will reflect the current
3169 * modification time for parse.h. This is something of a
3170 * kludge, I admit, but it's a useful one..
3172 * XXX: People like to use a rule like
3174 * FRC:
3176 * To force things that depend on FRC to be made, so we
3177 * have to check for gn->children being empty as well...
3179 if (!Lst_IsEmpty(&gn->commands) ||
3180 Lst_IsEmpty(&gn->children)) {
3181 gn->mtime = now;
3183 #else
3185 * This is what Make does and it's actually a good
3186 * thing, as it allows rules like
3188 * cmp -s y.tab.h parse.h || cp y.tab.h parse.h
3190 * to function as intended. Unfortunately, thanks to
3191 * the stateless nature of NFS (and the speed of this
3192 * program), there are times when the modification time
3193 * of a file created on a remote machine will not be
3194 * modified before the stat() implied by the Dir_MTime
3195 * occurs, thus leading us to believe that the file
3196 * is unchanged, wrecking havoc with files that depend
3197 * on this one.
3199 * I have decided it is better to make too much than to
3200 * make too little, so this stuff is commented out
3201 * unless you're sure it's ok.
3202 * -- ardeb 1/12/88
3204 if (noExecute || Dir_MTime(gn) == 0) {
3205 gn->mtime = now;
3207 if (gn->cmtime > gn->mtime)
3208 gn->mtime = gn->cmtime;
3209 DEBUGF(MAKE, ("update time: %s\n",
3210 Targ_FmtTime(gn->mtime)));
3211 #endif
3212 if (!(gn->type & OP_EXEC)) {
3213 pgn->childMade = true;
3214 Make_TimeStamp(pgn, gn);
3217 } else if (keepgoing) {
3218 pgn->make = false;
3220 } else {
3221 printf("\n\nStop in %s.\n", Var_Value(".CURDIR", gn));
3222 exit(1);
3224 } else if (gn->made == ERROR) {
3226 * Already had an error when making this beastie. Tell the
3227 * parent to abort.
3229 pgn->make = false;
3230 } else {
3231 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3232 Var_Set(IMPSRC, Var_Value(TARGET, gn), pgn);
3234 switch(gn->made) {
3235 case BEINGMADE:
3236 Error("Graph cycles through %s\n", gn->name);
3237 gn->made = ERROR;
3238 pgn->make = false;
3239 break;
3240 case MADE:
3241 if ((gn->type & OP_EXEC) == 0) {
3242 pgn->childMade = true;
3243 Make_TimeStamp(pgn, gn);
3245 break;
3246 case UPTODATE:
3247 if ((gn->type & OP_EXEC) == 0) {
3248 Make_TimeStamp(pgn, gn);
3250 break;
3251 default:
3252 break;
3258 * Start making given a list of target nodes. Returns what the exit
3259 * status of make should be.
3261 * @note Obviously some function we call is exiting since the code only
3262 * returns 0. We will fix that bug eventually.
3265 Compat_Run(Lst *targs, bool queryFlag)
3267 int error_cnt; /* Number of targets not remade due to errors */
3268 GNode *deferred;
3270 deferred = Targ_NewGN("Deferred");
3273 * If the user has defined a .BEGIN target, execute the commands
3274 * attached to it.
3276 if (queryFlag == false) {
3277 GNode *gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
3278 if (gn != NULL) {
3279 Compat_RunCmds(gn, deferred);
3280 if (gn->made == ERROR) {
3281 printf("\n\nStop.\n");
3282 return (1); /* Failed .BEGIN target */
3288 * For each entry in the list of targets to create, call CompatMake on
3289 * it to create the thing. CompatMake will leave the 'made' field of gn
3290 * in one of several states:
3291 * UPTODATE gn was already up-to-date
3292 * MADE gn was recreated successfully
3293 * ERROR An error occurred while gn was being created
3294 * ABORTED gn was not remade because one of its inferiors
3295 * could not be made due to errors.
3297 error_cnt = 0;
3298 while (!Lst_IsEmpty(targs)) {
3299 GNode *gn = Lst_DeQueue(targs);
3301 CompatMake(gn, gn, deferred, queryFlag);
3302 if (gn->made == UPTODATE) {
3303 printf("`%s' is up to date.\n", gn->name);
3304 } else if (gn->made == ABORTED) {
3305 printf("`%s' not remade because of errors.\n",
3306 gn->name);
3307 error_cnt += 1;
3311 if ((error_cnt == 0) && (queryFlag == false)) {
3312 GNode *gn;
3315 * If the user has deferred commands using "..." run them.
3317 Compat_RunCmds(deferred, NULL);
3318 if (deferred->made == ERROR) {
3319 printf("\n\nStop.\n");
3320 return (1); /* Failed "deferred" target */
3324 * If the user has defined a .END target, run its commands.
3326 gn = Targ_FindNode(".END", TARG_NOCREATE);
3327 if (gn != NULL) {
3328 Compat_RunCmds(gn, NULL);
3329 if (gn->made == ERROR) {
3330 printf("\n\nStop.\n");
3331 return (1); /* Failed .END target */
3336 return (0); /* Successful completion */