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