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
8 * This code is derived from software contributed to Berkeley by
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
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.77 2005/04/26 10:21:48 okumoto Exp $
50 * handle the creation etc. of our child processes.
53 * Job_Make Start the creation of the given target.
56 * Check for and handle the termination of any children.
57 * This must be called reasonably frequently to keep the
58 * whole make going at a decent clip, since job table
59 * entries aren't removed until their process is caught
60 * this way. Its single argument is TRUE if the function
61 * should block waiting for a child to terminate.
63 * Job_CatchOutput Print any output our children have produced. Should
64 * also be called fairly frequently to keep the user
65 * informed of what's going on. If no output is waiting,
66 * it will block for a time given by the SEL_* constants,
67 * below, or until output is ready.
69 * Job_Init Called to 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.
74 * Job_Full Return TRUE if the job table is filled.
76 * Job_Empty Return TRUE if the job table is completely empty.
78 * Job_ParseShell Given the line following a .SHELL target, parse the
79 * line as a shell specification. Returns FAILURE if the
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.
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.
92 * Verify that the commands for a target are ok. Provide
93 * them if necessary and possible.
95 * Job_Touch Update a target without really updating it.
97 * Job_Wait Wait for all currently-running jobs to finish.
100 #include <sys/queue.h>
101 #include <sys/types.h>
102 #include <sys/select.h>
103 #include <sys/stat.h>
105 #include <sys/event.h>
107 #include <sys/wait.h>
111 #include <inttypes.h>
127 #include "pathnames.h"
134 #define TMPPAT "/tmp/makeXXXXXXXXXX"
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
144 #endif /* !USE_KQUEUE */
147 * Job Table definitions.
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.
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.
157 #define JOB_BUFSIZE 1024
159 pid_t pid; /* The child's process ID */
161 struct GNode *node; /* The target the child is making */
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.
170 * An FILE* for writing out the commands. This is only
171 * used before the job is actually started.
176 * A word of flags which determine how the module handles errors,
177 * echoing, etc. for the job
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
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,
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 */
194 /* union for handling shell's output */
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
205 * Input side of pipe associated with
206 * job's output channel
211 * Output side of pipe associated with job's
217 * Buffer for storing the output of the
220 char op_outBuf[JOB_BUFSIZE + 1];
222 /* Current position in op_outBuf */
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.
232 /* Name of file to which shell output was rerouted */
233 char of_outFile[sizeof(TMPPAT)];
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
243 } output; /* Data for tracking a shell's output */
245 TAILQ_ENTRY(Job) link; /* list link */
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
255 TAILQ_HEAD(JobList, Job);
258 * Shell Specifications:
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.
267 #define DEF_SHELL_STRUCT(TAG, CONST) \
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. \
277 /* True if both echoOff and echoOn defined */ \
278 Boolean hasEchoCtl; \
280 CONST char *echoOff; /* command to turn off echo */ \
281 CONST char *echoOn; /* command to turn it back on */\
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 \
289 CONST char *noPrint; \
291 /* set if can control error checking for individual commands */ \
294 /* string to turn error checking on */ \
295 CONST char *errCheck; \
297 /* string to turn off error checking */ \
298 CONST char *ignErr; \
300 CONST char *echo; /* command line flag: echo commands */ \
301 CONST char *exit; /* command line flag: exit on error */ \
304 DEF_SHELL_STRUCT(Shell,);
305 DEF_SHELL_STRUCT(CShell, const);
308 * error handling variables
310 static int errors = 0; /* number of errors reported */
311 static 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 */
317 * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
318 * is a char! So when we go above 127 we turn negative!
320 #define FILENO(a) ((unsigned)fileno(a))
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
327 static GNode *postCommands;
330 * The number of commands actually printed for a target. Should this
331 * number be 0, no shell will be executed.
333 static int numCommands;
336 * Return values from JobStart.
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 */
344 * Descriptions for various shells.
346 static const struct CShell shells[] = {
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.
354 TRUE, "unset verbose", "set verbose", "unset verbose",
355 FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"",
359 * SH description. Echo control is also possible and, under
360 * sun UNIX anyway, one can even control error checking.
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",
372 * KSH description. The Korn shell has a superset of
373 * the Bourne shell's functionality.
377 TRUE, "set -", "set -v", "set -",
378 TRUE, "set -e", "set +e",
384 * This is the shell to which we pass all commands in the Makefile.
385 * It is set by the Job_ParseShell function.
387 static struct Shell *commandShell = NULL;
388 static char *shellPath = NULL; /* full pathname of executable image */
389 static char *shellName = NULL; /* last component of shell */
391 int maxJobs; /* The most children we can run at once */
392 static int nJobs; /* The number of children currently running */
394 /* The structures that describe them */
395 static struct JobList jobs = TAILQ_HEAD_INITIALIZER(jobs);
397 static 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 */
401 static int kqfd; /* File descriptor obtained by kqueue() */
403 static fd_set outputs; /* Set of descriptors of pipes connected to
404 * the output channels of children */
407 static GNode *lastNode; /* The node for which output was most recently
409 static const char *targFmt; /* Format string to use to head output from a
410 * job when it's not the most-recent job heard
413 #define TARG_FMT "--- %s ---\n" /* Default format */
414 #define MESSAGE(fp, gn) \
415 fprintf(fp, targFmt, gn->name);
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.
423 * Lst of Job structures describing jobs that were stopped due to
424 * concurrency limits or externally
426 static struct JobList stoppedJobs = TAILQ_HEAD_INITIALIZER(stoppedJobs);
428 static int fifoFd; /* Fd of our job fifo */
429 static char fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
430 static int fifoMaster;
432 static sig_atomic_t interrupted;
435 #if defined(USE_PGRP) && defined(SYSV)
436 # define KILL(pid, sig) killpg(-(pid), (sig))
438 # if defined(USE_PGRP)
439 # define KILL(pid, sig) killpg((pid), (sig))
441 # define KILL(pid, sig) kill((pid), (sig))
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.
451 #define W_SETMASKED(st, val, fun) \
454 int mask = fun(sh); \
456 for (sh = 0; ((mask >> sh) & 1) == 0; sh++) \
458 *(st) = (*(st) & ~mask) | ((val) << sh); \
461 #define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
462 #define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
465 * Information used to create a new process.
467 typedef struct ProcStuff {
468 int in; /* stdin for new process */
469 int out; /* stdout for new process */
470 int err; /* stderr for new process */
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 */
479 static void JobRestart(Job *);
480 static int JobStart(GNode *, int, Job *);
481 static void JobDoOutput(Job *, Boolean);
482 static struct Shell *JobMatchShell(const char *);
483 static void JobInterrupt(int, int);
484 static void JobRestartJobs(void);
485 static void ProcExec(ProcStuff *) __dead2;
488 * Replace the current process.
491 ProcExec(ProcStuff *ps)
493 if (ps->in != STDIN_FILENO) {
495 * Redirect the child's stdin to the input fd
496 * and reset it to the beginning (again).
498 if (dup2(ps->in, STDIN_FILENO) == -1)
499 Punt("Cannot dup2: %s", strerror(errno));
500 lseek(STDIN_FILENO, (off_t)0, SEEK_SET);
503 if (ps->out != STDOUT_FILENO) {
505 * Redirect the child's stdout to the output fd.
507 if (dup2(ps->out, STDOUT_FILENO) == -1)
508 Punt("Cannot dup2: %s", strerror(errno));
512 if (ps->err != STDERR_FILENO) {
514 * Redirect the child's stderr to the err fd.
516 if (dup2(ps->err, STDERR_FILENO) == -1)
517 Punt("Cannot dup2: %s", strerror(errno));
521 if (ps->merge_errors) {
523 * Send stderr to parent process too.
525 if (dup2(STDOUT_FILENO, STDERR_FILENO) == -1)
526 Punt("Cannot dup2: %s", strerror(errno));
530 * The file descriptors for stdin, stdout, or stderr might
531 * have been marked close-on-exec. Clear the flag on all
534 fcntl(STDIN_FILENO, F_SETFD,
535 fcntl(STDIN_FILENO, F_GETFD) & (~FD_CLOEXEC));
536 fcntl(STDOUT_FILENO, F_SETFD,
537 fcntl(STDOUT_FILENO, F_GETFD) & (~FD_CLOEXEC));
538 fcntl(STDERR_FILENO, F_SETFD,
539 fcntl(STDERR_FILENO, F_GETFD) & (~FD_CLOEXEC));
544 * Become a process group leader, so we can kill it and all
545 * its descendants in one fell swoop, by killing its process
546 * family, but not commit suicide.
551 setpgid(0, getpid());
553 #endif /* USE_PGRP */
556 if (ps->searchpath) {
557 execvp(ps->argv[0], ps->argv);
559 write(STDERR_FILENO, ps->argv[0], strlen(ps->argv[0]));
560 write(STDERR_FILENO, ":", 1);
561 write(STDERR_FILENO, strerror(errno), strlen(strerror(errno)));
562 write(STDERR_FILENO, "\n", 1);
564 execv(shellPath, ps->argv);
567 "Could not execute shell\n",
568 sizeof("Could not execute shell"));
572 * Since we are the child process, exit without flushing buffers.
579 * Got a signal. Set global variables and hope that someone will
583 JobCatchSig(int signo)
591 * Pass a signal on to all local jobs if
592 * USE_PGRP is defined, then die ourselves.
595 * We die by the same signal.
598 JobPassSig(int signo)
601 sigset_t nmask, omask;
602 struct sigaction act;
605 sigaddset(&nmask, signo);
606 sigprocmask(SIG_SETMASK, &nmask, &omask);
608 DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
609 TAILQ_FOREACH(job, &jobs, link) {
610 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
611 signo, (intmax_t)job->pid));
612 KILL(job->pid, signo);
616 * Deal with proper cleanup based on the signal received. We only run
617 * the .INTERRUPT target if the signal was in fact an interrupt.
618 * The other three termination signals are more of a "get out *now*"
621 if (signo == SIGINT) {
622 JobInterrupt(TRUE, signo);
623 } else if (signo == SIGHUP || signo == SIGTERM || signo == SIGQUIT) {
624 JobInterrupt(FALSE, signo);
628 * Leave gracefully if SIGQUIT, rather than core dumping.
630 if (signo == SIGQUIT) {
635 * Send ourselves the signal now we've given the message to everyone
636 * else. Note we block everything else possible while we're getting
637 * the signal. This ensures that all our jobs get continued when we
638 * wake up before we take any other signal.
639 * XXX this comment seems wrong.
641 act.sa_handler = SIG_DFL;
642 sigemptyset(&act.sa_mask);
644 sigaction(signo, &act, NULL);
646 DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
647 ~0 & ~(1 << (signo - 1))));
648 signal(signo, SIG_DFL);
650 KILL(getpid(), signo);
653 TAILQ_FOREACH(job, &jobs, link) {
654 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
655 signo, (intmax_t)job->pid));
656 KILL(job->pid, signo);
659 sigprocmask(SIG_SETMASK, &omask, NULL);
660 sigprocmask(SIG_SETMASK, &omask, NULL);
661 act.sa_handler = JobPassSig;
662 sigaction(signo, &act, NULL);
667 * Put out another command for the given job. If the command starts
668 * with an @ or a - we process it specially. In the former case,
669 * so long as the -s and -n flags weren't given to make, we stick
670 * a shell-specific echoOff command in the script. In the latter,
671 * we ignore errors for the entire job, unless the shell has error
673 * If the command is just "..." we take all future commands for this
674 * job to be commands to be executed once the entire graph has been
675 * made and return non-zero to signal that the end of the commands
676 * was reached. These commands are later attached to the postCommands
677 * node and executed by Job_Finish when all things are done.
678 * This function is called from JobStart via LST_FOREACH.
681 * Always 0, unless the command was "..."
684 * If the command begins with a '-' and the shell has no error control,
685 * the JOB_IGNERR flag is set in the job descriptor.
686 * If the command is "..." and we're not ignoring such things,
687 * tailCmds is set to the successor node of the cmd.
688 * numCommands is incremented if the command is actually printed.
691 JobPrintCommand(char *cmd, Job *job)
693 Boolean noSpecials; /* true if we shouldn't worry about
694 * inserting special commands into
695 * the input stream. */
696 Boolean shutUp = FALSE; /* true if we put a no echo command
697 * into the command file */
698 Boolean errOff = FALSE; /* true if we turned error checking
699 * off before printing the command
700 * and need to turn it back on */
701 const char *cmdTemplate;/* Template to use when printing the command */
702 char *cmdStart; /* Start of expanded command */
703 LstNode *cmdNode; /* Node for replacing the command */
705 noSpecials = (noExecute && !(job->node->type & OP_MAKE));
707 if (strcmp(cmd, "...") == 0) {
708 job->node->type |= OP_SAVE_CMDS;
709 if ((job->flags & JOB_IGNDOTS) == 0) {
711 Lst_Succ(Lst_Member(&job->node->commands, cmd));
717 #define DBPRINTF(fmt, arg) \
718 DEBUGF(JOB, (fmt, arg)); \
719 fprintf(job->cmdFILE, fmt, arg); \
720 fflush(job->cmdFILE);
725 * For debugging, we replace each command with the result of expanding
726 * the variables in the command.
728 cmdNode = Lst_Member(&job->node->commands, cmd);
730 cmd = Buf_Peel(Var_Subst(cmd, job->node, FALSE));
733 Lst_Replace(cmdNode, cmdStart);
735 cmdTemplate = "%s\n";
738 * Check for leading @', -' or +'s to control echoing, error checking,
739 * and execution on -n.
741 while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
745 shutUp = DEBUG(LOUD) ? FALSE : TRUE;
755 * We're not actually exececuting anything...
756 * but this one needs to be - use compat mode
759 Compat_RunCommand(cmd, job->node);
767 while (isspace((unsigned char)*cmd))
771 if (!(job->flags & JOB_SILENT) && !noSpecials &&
772 commandShell->hasEchoCtl) {
773 DBPRINTF("%s\n", commandShell->echoOff);
780 if (!(job->flags & JOB_IGNERR) && !noSpecials) {
781 if (commandShell->hasErrCtl) {
783 * We don't want the error-control commands
784 * showing up either, so we turn off echoing
785 * while executing them. We could put another
786 * field in the shell structure to tell
787 * JobDoOutput to look for this string too,
788 * but why make it any more complex than
791 if (!(job->flags & JOB_SILENT) && !shutUp &&
792 commandShell->hasEchoCtl) {
793 DBPRINTF("%s\n", commandShell->echoOff);
794 DBPRINTF("%s\n", commandShell->ignErr);
795 DBPRINTF("%s\n", commandShell->echoOn);
797 DBPRINTF("%s\n", commandShell->ignErr);
799 } else if (commandShell->ignErr &&
800 *commandShell->ignErr != '\0') {
802 * The shell has no error control, so we need to
803 * be weird to get it to ignore any errors from
804 * the command. If echoing is turned on, we turn
805 * it off and use the errCheck template to echo
806 * the command. Leave echoing off so the user
807 * doesn't see the weirdness we go through to
808 * ignore errors. Set cmdTemplate to use the
809 * weirdness instead of the simple "%s\n"
812 if (!(job->flags & JOB_SILENT) && !shutUp &&
813 commandShell->hasEchoCtl) {
814 DBPRINTF("%s\n", commandShell->echoOff);
815 DBPRINTF(commandShell->errCheck, cmd);
818 cmdTemplate = commandShell->ignErr;
820 * The error ignoration (hee hee) is already
821 * taken care of by the ignErr template, so
822 * pretend error checking is still on.
833 DBPRINTF(cmdTemplate, cmd);
837 * If echoing is already off, there's no point in issuing the
838 * echoOff command. Otherwise we issue it and pretend it was on
839 * for the whole command...
841 if (!shutUp && !(job->flags & JOB_SILENT) &&
842 commandShell->hasEchoCtl) {
843 DBPRINTF("%s\n", commandShell->echoOff);
846 DBPRINTF("%s\n", commandShell->errCheck);
849 DBPRINTF("%s\n", commandShell->echoOn);
856 * Called to close both input and output pipes when a job is finished.
859 * The file descriptors associated with the job are closed.
866 #if !defined(USE_KQUEUE)
867 FD_CLR(job->inPipe, &outputs);
869 if (job->outPipe != job->inPipe) {
872 JobDoOutput(job, TRUE);
876 JobDoOutput(job, TRUE);
882 * Do final processing for the given job including updating
883 * parents and starting new jobs as available/necessary. Note
884 * that we pay no attention to the JOB_IGNERR flag here.
885 * This is because when we're called because of a noexecute flag
886 * or something, jstat.w_status is 0 and when called from
887 * Job_CatchChildren, the status is zeroed if it s/b ignored.
890 * Some nodes may be put on the toBeMade queue.
891 * Final commands for the job are placed on postCommands.
893 * If we got an error and are aborting (aborting == ABORT_ERROR) and
894 * the job list is now empty, we are done for the day.
895 * If we recognized an error (errors !=0), we set the aborting flag
896 * to ABORT_ERROR so no more jobs will be started.
899 JobFinish(Job *job, int *status)
904 if ((WIFEXITED(*status) && WEXITSTATUS(*status) != 0 &&
905 !(job->flags & JOB_IGNERR)) ||
906 (WIFSIGNALED(*status) && WTERMSIG(*status) != SIGCONT)) {
908 * If it exited non-zero and either we're doing things our
909 * way or we're not ignoring errors, the job is finished.
910 * Similarly, if the shell died because of a signal
911 * the job is also finished. In these cases, finish out the
912 * job's output before printing the exit status...
915 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
916 fclose(job->cmdFILE);
920 } else if (WIFEXITED(*status)) {
922 * Deal with ignored errors in -B mode. We need to print a
923 * message telling of the ignored error as well as setting
924 * status.w_status to 0 so the next command gets run. To do
925 * this, we set done to be TRUE if in -B mode and the job
928 done = WEXITSTATUS(*status) != 0;
931 * Old comment said: "Note we don't want to close down any of
932 * the streams until we know we're at the end." But we do.
933 * Otherwise when are we going to print the rest of the stuff?
938 * No need to close things down or anything.
943 if (done || WIFSTOPPED(*status) ||
944 (WIFSIGNALED(*status) && WTERMSIG(*status) == SIGCONT) ||
948 if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
950 * If output is going to a file and this job is ignoring
951 * errors, arrange to have the exit status sent to the
952 * output file as well.
954 out = fdopen(job->outFd, "w");
956 Punt("Cannot fdopen");
961 if (WIFEXITED(*status)) {
962 DEBUGF(JOB, ("Process %jd exited.\n",
963 (intmax_t)job->pid));
964 if (WEXITSTATUS(*status) != 0) {
965 if (usePipes && job->node != lastNode) {
966 MESSAGE(out, job->node);
967 lastNode = job->node;
969 fprintf(out, "*** Error code %d%s\n",
970 WEXITSTATUS(*status),
971 (job->flags & JOB_IGNERR) ?
974 if (job->flags & JOB_IGNERR) {
977 } else if (DEBUG(JOB)) {
978 if (usePipes && job->node != lastNode) {
979 MESSAGE(out, job->node);
980 lastNode = job->node;
982 fprintf(out, "*** Completed successfully\n");
985 } else if (WIFSTOPPED(*status)) {
986 DEBUGF(JOB, ("Process %jd stopped.\n",
987 (intmax_t)job->pid));
988 if (usePipes && job->node != lastNode) {
989 MESSAGE(out, job->node);
990 lastNode = job->node;
992 fprintf(out, "*** Stopped -- signal %d\n",
994 job->flags |= JOB_RESUME;
995 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
999 } else if (WTERMSIG(*status) == SIGCONT) {
1001 * If the beastie has continued, shift the Job from
1002 * the stopped list to the running one (or re-stop it
1003 * if concurrency is exceeded) and go and get another
1006 if (job->flags & (JOB_RESUME | JOB_RESTART)) {
1007 if (usePipes && job->node != lastNode) {
1008 MESSAGE(out, job->node);
1009 lastNode = job->node;
1011 fprintf(out, "*** Continued\n");
1013 if (!(job->flags & JOB_CONTINUING)) {
1014 DEBUGF(JOB, ("Warning: process %jd was not "
1015 "continuing.\n", (intmax_t)job->pid));
1018 * We don't really want to restart a job from
1019 * scratch just because it continued, especially
1020 * not without killing the continuing process!
1021 * That's why this is ifdef'ed out.
1027 job->flags &= ~JOB_CONTINUING;
1028 TAILQ_INSERT_TAIL(&jobs, job, link);
1030 DEBUGF(JOB, ("Process %jd is continuing locally.\n",
1031 (intmax_t)job->pid));
1032 if (nJobs == maxJobs) {
1034 DEBUGF(JOB, ("Job queue is full.\n"));
1040 if (usePipes && job->node != lastNode) {
1041 MESSAGE(out, job->node);
1042 lastNode = job->node;
1044 fprintf(out, "*** Signal %d\n", WTERMSIG(*status));
1051 * Now handle the -B-mode stuff. If the beast still isn't finished,
1052 * try and restart the job on the next command. If JobStart says it's
1053 * ok, it's ok. If there's an error, this puppy is done.
1055 if (compatMake && WIFEXITED(*status) &&
1056 Lst_Succ(job->node->compat_command) != NULL) {
1057 switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
1063 W_SETEXITSTATUS(status, 1);
1067 * If we got back a JOB_FINISHED code, JobStart has
1068 * already called Make_Update and freed the job
1069 * descriptor. We set done to false here to avoid fake
1070 * cycles and double frees. JobStart needs to do the
1071 * update so we can proceed up the graph when given
1083 if (done && aborting != ABORT_ERROR &&
1084 aborting != ABORT_INTERRUPT && *status == 0) {
1086 * As long as we aren't aborting and the job didn't return a
1087 * non-zero status that we shouldn't ignore, we call
1088 * Make_Update to update the parents. In addition, any saved
1089 * commands for the node are placed on the .END target.
1091 for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
1092 Lst_AtEnd(&postCommands->commands,
1094 Var_Subst(Lst_Datum(ln), job->node, FALSE)));
1097 job->node->made = MADE;
1098 Make_Update(job->node);
1101 } else if (*status != 0) {
1109 * Set aborting if any error.
1111 if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
1113 * If we found any errors in this batch of children and the -k
1114 * flag wasn't given, we set the aborting flag so no more jobs
1117 aborting = ABORT_ERROR;
1120 if (aborting == ABORT_ERROR && Job_Empty()) {
1122 * If we are aborting and the job table is now empty, we finish.
1130 * Touch the given target. Called by JobStart when the -t flag was
1131 * given. Prints messages unless told to be silent.
1134 * The data modification of the file is changed. In addition, if the
1135 * file did not exist, it is created.
1138 Job_Touch(GNode *gn, Boolean silent)
1140 int streamID; /* ID of stream opened to do the touch */
1141 struct utimbuf times; /* Times for utime() call */
1143 if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
1145 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
1146 * targets and, as such, shouldn't really be created.
1152 fprintf(stdout, "touch %s\n", gn->name);
1160 if (gn->type & OP_ARCHV) {
1162 } else if (gn->type & OP_LIB) {
1165 char *file = gn->path ? gn->path : gn->name;
1167 times.actime = times.modtime = now;
1168 if (utime(file, ×) < 0) {
1169 streamID = open(file, O_RDWR | O_CREAT, 0666);
1171 if (streamID >= 0) {
1175 * Read and write a byte to the file to change
1176 * the modification time, then close the file.
1178 if (read(streamID, &c, 1) == 1) {
1179 lseek(streamID, (off_t)0, SEEK_SET);
1180 write(streamID, &c, 1);
1185 fprintf(stdout, "*** couldn't touch %s: %s",
1186 file, strerror(errno));
1195 * Make sure the given node has all the commands it needs.
1198 * TRUE if the commands list is/was ok.
1201 * The node will have commands from the .DEFAULT rule added to it
1205 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1208 if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
1209 (gn->type & OP_LIB) == 0) {
1211 * No commands. Look for .DEFAULT rule from which we might infer
1214 if (DEFAULT != NULL && !Lst_IsEmpty(&DEFAULT->commands)) {
1217 * Make only looks for a .DEFAULT if the node was
1218 * never the target of an operator, so that's what we
1219 * do too. If a .DEFAULT was given, we substitute its
1220 * commands for gn's commands and set the IMPSRC
1221 * variable to be the target's name The DEFAULT node
1222 * acts like a transformation rule, in that gn also
1223 * inherits any attributes or sources attached to
1226 Make_HandleUse(DEFAULT, gn);
1227 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn);
1230 } else if (Dir_MTime(gn) == 0) {
1232 * The node wasn't the target of an operator we have
1233 * no .DEFAULT rule to go on and the target doesn't
1234 * already exist. There's nothing more we can do for
1235 * this branch. If the -k flag wasn't given, we stop
1236 * in our tracks, otherwise we just don't update
1237 * this node's parents so they never get examined.
1239 static const char msg[] =
1240 "make: don't know how to make";
1242 if (gn->type & OP_OPTIONAL) {
1243 fprintf(stdout, "%s %s(ignored)\n",
1246 } else if (keepgoing) {
1247 fprintf(stdout, "%s %s(continuing)\n",
1253 if (strcmp(gn->name,"love") == 0)
1254 (*abortProc)("Not war.");
1257 (*abortProc)("%s %s. Stop",
1268 * Execute the shell for the given job. Called from JobStart and
1272 * A shell is executed, outputs is altered and the Job structure added
1276 JobExec(Job *job, char **argv)
1279 pid_t cpid; /* ID of new child */
1284 DEBUGF(JOB, ("Running %s\n", job->node->name));
1285 DEBUGF(JOB, ("\tCommand: "));
1286 for (i = 0; argv[i] != NULL; i++) {
1287 DEBUGF(JOB, ("%s ", argv[i]));
1289 DEBUGF(JOB, ("\n"));
1293 * Some jobs produce no output and it's disconcerting to have
1294 * no feedback of their running (since they produce no output, the
1295 * banner with their name in it never appears). This is an attempt to
1296 * provide that feedback, even if nothing follows it.
1298 if (lastNode != job->node && (job->flags & JOB_FIRST) &&
1299 !(job->flags & JOB_SILENT)) {
1300 MESSAGE(stdout, job->node);
1301 lastNode = job->node;
1304 ps.in = FILENO(job->cmdFILE);
1307 * Set up the child's output to be routed through the
1308 * pipe we've created for it.
1310 ps.out = job->outPipe;
1313 * We're capturing output in a file, so we duplicate
1314 * the descriptor to the temporary file into the
1317 ps.out = job->outFd;
1319 ps.err = STDERR_FILENO;
1321 ps.merge_errors = 1;
1328 * Fork. Warning since we are doing vfork() instead of fork(),
1329 * do not allocate memory in the child process!
1331 if ((cpid = vfork()) == -1) {
1332 Punt("Cannot fork");
1334 } else if (cpid == 0) {
1350 if (usePipes && (job->flags & JOB_FIRST)) {
1352 * The first time a job is run for a node, we set the
1353 * current position in the buffer to the beginning and
1354 * mark another stream to watch in the outputs mask.
1357 struct kevent kev[2];
1361 #if defined(USE_KQUEUE)
1362 EV_SET(&kev[0], job->inPipe, EVFILT_READ, EV_ADD, 0, 0, job);
1363 EV_SET(&kev[1], job->pid, EVFILT_PROC,
1364 EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
1365 if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1367 * kevent() will fail if the job is already
1370 if (errno != EINTR && errno != EBADF && errno != ESRCH)
1371 Punt("kevent: %s", strerror(errno));
1374 FD_SET(job->inPipe, &outputs);
1375 #endif /* USE_KQUEUE */
1378 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1379 fclose(job->cmdFILE);
1380 job->cmdFILE = NULL;
1384 * Now the job is actually running, add it to the table.
1387 TAILQ_INSERT_TAIL(&jobs, job, link);
1388 if (nJobs == maxJobs) {
1396 * Create the argv needed to execute the shell for a given job.
1399 JobMakeArgv(Job *job, char **argv)
1402 static char args[10]; /* For merged arguments */
1404 argv[0] = shellName;
1407 if ((commandShell->exit && *commandShell->exit != '-') ||
1408 (commandShell->echo && *commandShell->echo != '-')) {
1410 * At least one of the flags doesn't have a minus before it, so
1411 * merge them together. Have to do this because the *(&(@*#*&#$#
1412 * Bourne shell thinks its second argument is a file to source.
1413 * Grrrr. Note the ten-character limitation on the combined
1416 sprintf(args, "-%s%s", (job->flags & JOB_IGNERR) ? "" :
1417 commandShell->exit ? commandShell->exit : "",
1418 (job->flags & JOB_SILENT) ? "" :
1419 commandShell->echo ? commandShell->echo : "");
1426 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1427 argv[argc] = commandShell->exit;
1430 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1431 argv[argc] = commandShell->echo;
1440 * Restart a job that stopped for some reason. The job must be neither
1441 * on the jobs nor on the stoppedJobs list.
1444 * jobFull will be set if the job couldn't be run.
1447 JobRestart(Job *job)
1450 if (job->flags & JOB_RESTART) {
1452 * Set up the control arguments to the shell. This is based on
1453 * the flags set earlier for this job. If the JOB_IGNERR flag
1454 * is clear, the 'exit' flag of the commandShell is used to
1455 * cause it to exit upon receiving an error. If the JOB_SILENT
1456 * flag is clear, the 'echo' flag of the commandShell is used
1457 * to get it to start echoing as soon as it starts
1458 * processing commands.
1462 JobMakeArgv(job, argv);
1464 DEBUGF(JOB, ("Restarting %s...", job->node->name));
1465 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL)) {
1467 * Not allowed to run -- put it back on the hold
1468 * queue and mark the table full
1470 DEBUGF(JOB, ("holding\n"));
1471 TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1473 DEBUGF(JOB, ("Job queue is full.\n"));
1477 * Job may be run locally.
1479 DEBUGF(JOB, ("running locally\n"));
1485 * The job has stopped and needs to be restarted.
1486 * Why it stopped, we don't know...
1488 DEBUGF(JOB, ("Resuming %s...", job->node->name));
1489 if ((nJobs < maxJobs || ((job->flags & JOB_SPECIAL) &&
1490 maxJobs == 0)) && nJobs != maxJobs) {
1492 * If we haven't reached the concurrency limit already
1493 * (or the job must be run and maxJobs is 0), it's ok
1499 error = (KILL(job->pid, SIGCONT) != 0);
1503 * Make sure the user knows we've continued
1504 * the beast and actually put the thing in the
1507 job->flags |= JOB_CONTINUING;
1509 W_SETTERMSIG(&status, SIGCONT);
1510 JobFinish(job, &status);
1512 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1513 DEBUGF(JOB, ("done\n"));
1515 Error("couldn't resume %s: %s",
1516 job->node->name, strerror(errno));
1518 W_SETEXITSTATUS(&status, 1);
1519 JobFinish(job, &status);
1523 * Job cannot be restarted. Mark the table as full and
1524 * place the job back on the list of stopped jobs.
1526 DEBUGF(JOB, ("table full\n"));
1527 TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1529 DEBUGF(JOB, ("Job queue is full.\n"));
1536 * Start a target-creation process going for the target described
1537 * by the graph node gn.
1540 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1541 * if there isn't actually anything left to do for the job and
1542 * JOB_RUNNING if the job has been started.
1545 * A new Job node is created and added to the list of running
1546 * jobs. PMake is forked and a child shell created.
1549 JobStart(GNode *gn, int flags, Job *previous)
1551 Job *job; /* new job descriptor */
1552 char *argv[4]; /* Argument vector to shell */
1553 Boolean cmdsOK; /* true if the nodes commands were all right */
1554 Boolean noExec; /* Set true if we decide not to run the job */
1555 int tfd; /* File descriptor for temp file */
1557 char tfile[sizeof(TMPPAT)];
1560 JobPassSig(interrupted);
1563 if (previous != NULL) {
1564 previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1567 job = emalloc(sizeof(Job));
1572 job->tailCmds = NULL;
1575 * Set the initial value of the flags for this job based on the global
1576 * ones and the node's attributes... Any flags supplied by the caller
1577 * are also added to the field.
1580 if (Targ_Ignore(gn)) {
1581 job->flags |= JOB_IGNERR;
1583 if (Targ_Silent(gn)) {
1584 job->flags |= JOB_SILENT;
1586 job->flags |= flags;
1589 * Check the commands now so any attributes from .DEFAULT have a chance
1590 * to migrate to the node.
1592 if (!compatMake && (job->flags & JOB_FIRST)) {
1593 cmdsOK = Job_CheckCommands(gn, Error);
1599 * If the -n flag wasn't given, we open up OUR (not the child's)
1600 * temporary file to stuff commands in it. The thing is rd/wr so we
1601 * don't need to reopen it to feed it to the shell. If the -n flag
1602 * *was* given, we just set the file to be stdout. Cute, huh?
1604 if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1606 * We're serious here, but if the commands were bogus, we're
1613 strcpy(tfile, TMPPAT);
1614 if ((tfd = mkstemp(tfile)) == -1)
1615 Punt("Cannot create temp file: %s", strerror(errno));
1616 job->cmdFILE = fdopen(tfd, "w+");
1618 if (job->cmdFILE == NULL) {
1620 Punt("Could not open %s", tfile);
1622 fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1624 * Send the commands to the command file, flush all its
1625 * buffers then rewind and remove the thing.
1630 * Used to be backwards; replace when start doing multiple
1631 * commands per shell.
1635 * Be compatible: If this is the first time for this
1636 * node, verify its commands are ok and open the
1637 * commands list for sequential access by later
1638 * invocations of JobStart. Once that is done, we take
1639 * the next command off the list and print it to the
1640 * command file. If the command was an ellipsis, note
1641 * that there's nothing more to execute.
1643 if (job->flags & JOB_FIRST)
1644 gn->compat_command = Lst_First(&gn->commands);
1646 gn->compat_command =
1647 Lst_Succ(gn->compat_command);
1649 if (gn->compat_command == NULL ||
1650 JobPrintCommand(Lst_Datum(gn->compat_command), job))
1653 if (noExec && !(job->flags & JOB_FIRST)) {
1655 * If we're not going to execute anything, the
1656 * job is done and we need to close down the
1657 * various file descriptors we've opened for
1658 * output, then call JobDoOutput to catch the
1659 * final characters or send the file to the
1660 * screen... Note that the i/o streams are only
1661 * open if this isn't the first job. Note also
1662 * that this could not be done in
1663 * Job_CatchChildren b/c it wasn't clear if
1664 * there were more commands to execute or not...
1670 * We can do all the commands at once. hooray for sanity
1673 LST_FOREACH(ln, &gn->commands) {
1674 if (JobPrintCommand(Lst_Datum(ln), job))
1679 * If we didn't print out any commands to the shell
1680 * script, there's not much point in executing the
1683 if (numCommands == 0) {
1688 } else if (noExecute) {
1690 * Not executing anything -- just print all the commands to
1691 * stdout in one fell swoop. This will still set up
1692 * job->tailCmds correctly.
1694 if (lastNode != gn) {
1695 MESSAGE(stdout, gn);
1698 job->cmdFILE = stdout;
1701 * Only print the commands if they're ok, but don't die if
1702 * they're not -- just let the user know they're bad and keep
1703 * going. It doesn't do any harm in this case and may do
1707 LST_FOREACH(ln, &gn->commands) {
1708 if (JobPrintCommand(Lst_Datum(ln), job))
1713 * Don't execute the shell, thank you.
1719 * Just touch the target and note that no shell should be
1720 * executed. Set cmdFILE to stdout to make life easier. Check
1721 * the commands, too, but don't die if they're no good -- it
1722 * does no harm to keep working up the graph.
1724 job->cmdFILE = stdout;
1725 Job_Touch(gn, job->flags & JOB_SILENT);
1730 * If we're not supposed to execute a shell, don't.
1734 * Unlink and close the command file if we opened one
1736 if (job->cmdFILE != stdout) {
1737 if (job->cmdFILE != NULL)
1738 fclose(job->cmdFILE);
1744 * We only want to work our way up the graph if we aren't here
1745 * because the commands for the job were no good.
1748 if (aborting == 0) {
1749 for (ln = job->tailCmds; ln != NULL;
1750 ln = LST_NEXT(ln)) {
1751 Lst_AtEnd(&postCommands->commands,
1752 Buf_Peel(Var_Subst(Lst_Datum(ln),
1753 job->node, FALSE)));
1755 job->node->made = MADE;
1756 Make_Update(job->node);
1759 return(JOB_FINISHED);
1765 fflush(job->cmdFILE);
1769 * Set up the control arguments to the shell. This is based on the flags
1770 * set earlier for this job.
1772 JobMakeArgv(job, argv);
1775 * If we're using pipes to catch output, create the pipe by which we'll
1776 * get the shell's output. If we're using files, print out that we're
1777 * starting a job and then set up its temporary-file name.
1779 if (!compatMake || (job->flags & JOB_FIRST)) {
1784 Punt("Cannot create pipe: %s", strerror(errno));
1785 job->inPipe = fd[0];
1786 job->outPipe = fd[1];
1787 fcntl(job->inPipe, F_SETFD, 1);
1788 fcntl(job->outPipe, F_SETFD, 1);
1790 fprintf(stdout, "Remaking `%s'\n", gn->name);
1792 strcpy(job->outFile, TMPPAT);
1793 if ((job->outFd = mkstemp(job->outFile)) == -1)
1794 Punt("cannot create temp file: %s",
1796 fcntl(job->outFd, F_SETFD, 1);
1800 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL) && maxJobs != 0) {
1802 * We've hit the limit of concurrency, so put the job on hold
1803 * until some other job finishes. Note that the special jobs
1804 * (.BEGIN, .INTERRUPT and .END) may be run even when the
1805 * limit has been reached (e.g. when maxJobs == 0).
1809 DEBUGF(JOB, ("Can only run job locally.\n"));
1810 job->flags |= JOB_RESTART;
1811 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1813 if (nJobs >= maxJobs) {
1815 * If we're running this job as a special case
1816 * (see above), at least say the table is full.
1819 DEBUGF(JOB, ("Local job queue is full.\n"));
1823 return (JOB_RUNNING);
1827 JobOutput(Job *job, char *cp, char *endp, int msg)
1831 if (commandShell->noPrint) {
1832 ecp = strstr(cp, commandShell->noPrint);
1833 while (ecp != NULL) {
1836 if (msg && job->node != lastNode) {
1837 MESSAGE(stdout, job->node);
1838 lastNode = job->node;
1841 * The only way there wouldn't be a newline
1842 * after this line is if it were the last in
1843 * the buffer. However, since the non-printable
1844 * comes after it, there must be a newline, so
1845 * we don't print one.
1847 fprintf(stdout, "%s", cp);
1850 cp = ecp + strlen(commandShell->noPrint);
1853 * Still more to print, look again after
1854 * skipping the whitespace following the
1855 * non-printable command....
1858 while (*cp == ' ' || *cp == '\t' ||
1862 ecp = strstr(cp, commandShell->noPrint);
1873 * This function is called at different times depending on
1874 * whether the user has specified that output is to be collected
1875 * via pipes or temporary files. In the former case, we are called
1876 * whenever there is something to read on the pipe. We collect more
1877 * output from the given job and store it in the job's outBuf. If
1878 * this makes up a line, we print it tagged by the job's identifier,
1880 * If output has been collected in a temporary file, we open the
1881 * file and read it line by line, transfering it to our own
1882 * output channel until the file is empty. At which point we
1883 * remove the temporary file.
1884 * In both cases, however, we keep our figurative eye out for the
1885 * 'noPrint' line for the shell from which the output came. If
1886 * we recognize a line, we don't print it. If the command is not
1887 * alone on the line (the character after it is not \0 or \n), we
1888 * do print whatever follows it.
1891 * curPos may be shifted as may the contents of outBuf.
1894 JobDoOutput(Job *job, Boolean finish)
1896 Boolean gotNL = FALSE; /* true if got a newline */
1897 Boolean fbuf; /* true if our buffer filled up */
1898 int nr; /* number of bytes read */
1899 int i; /* auxiliary index into outBuf */
1900 int max; /* limit for i (end of current data) */
1901 int nRead; /* (Temporary) number of bytes read */
1902 FILE *oFILE; /* Stream pointer to shell's output file */
1907 * Read as many bytes as will fit in the buffer.
1913 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1914 JOB_BUFSIZE - job->curPos);
1916 * Check for interrupt here too, because the above read may
1917 * block when the child process is stopped. In this case the
1918 * interrupt will unblock it (we don't use SA_RESTART).
1921 JobPassSig(interrupted);
1924 DEBUGF(JOB, ("JobDoOutput(piperead)"));
1931 * If we hit the end-of-file (the job is dead), we must flush
1932 * its remaining output, so pretend we read a newline if
1933 * there's any output remaining in the buffer.
1934 * Also clear the 'finish' flag so we stop looping.
1936 if (nr == 0 && job->curPos != 0) {
1937 job->outBuf[job->curPos] = '\n';
1940 } else if (nr == 0) {
1945 * Look for the last newline in the bytes we just got. If there
1946 * is one, break out of the loop with 'i' as its index and
1949 max = job->curPos + nr;
1950 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1951 if (job->outBuf[i] == '\n') {
1954 } else if (job->outBuf[i] == '\0') {
1958 job->outBuf[i] = ' ';
1964 if (job->curPos == JOB_BUFSIZE) {
1966 * If we've run out of buffer space, we have
1967 * no choice but to print the stuff. sigh.
1973 if (gotNL || fbuf) {
1975 * Need to send the output to the screen. Null terminate
1976 * it first, overwriting the newline character if there
1977 * was one. So long as the line isn't one we should
1978 * filter (according to the shell description), we print
1979 * the line, preceded by a target banner if this target
1980 * isn't the same as the one for which we last printed
1981 * something. The rest of the data in the buffer are
1982 * then shifted down to the start of the buffer and
1983 * curPos is set accordingly.
1985 job->outBuf[i] = '\0';
1986 if (i >= job->curPos) {
1989 cp = JobOutput(job, job->outBuf,
1990 &job->outBuf[i], FALSE);
1993 * There's still more in that buffer. This time,
1994 * though, we know there's no newline at the
1995 * end, so we add one of our own free will.
1998 if (job->node != lastNode) {
1999 MESSAGE(stdout, job->node);
2000 lastNode = job->node;
2002 fprintf(stdout, "%s%s", cp,
2008 /* shift the remaining characters down */
2009 memcpy(job->outBuf, &job->outBuf[i + 1],
2011 job->curPos = max - (i + 1);
2015 * We have written everything out, so we just
2016 * start over from the start of the buffer.
2017 * No copying. No nothing.
2024 * If the finish flag is true, we must loop until we hit
2025 * end-of-file on the pipe. This is guaranteed to happen
2026 * eventually since the other end of the pipe is now
2027 * closed (we closed it explicitly and the child has
2028 * exited). When we do get an EOF, finish will be set
2029 * FALSE and we'll fall through and out.
2036 * We've been called to retrieve the output of the job from the
2037 * temporary file where it's been squirreled away. This consists
2038 * of opening the file, reading the output line by line, being
2039 * sure not to print the noPrint line for the shell we used,
2040 * then close and remove the temporary file. Very simple.
2042 * Change to read in blocks and do FindSubString type things
2043 * as for pipes? That would allow for "@echo -n..."
2045 oFILE = fopen(job->outFile, "r");
2046 if (oFILE != NULL) {
2047 fprintf(stdout, "Results of making %s:\n",
2051 while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2052 char *cp, *endp, *oendp;
2055 oendp = endp = inLine + strlen(inLine);
2056 if (endp[-1] == '\n') {
2059 cp = JobOutput(job, inLine, endp, FALSE);
2062 * There's still more in that buffer. This time,
2063 * though, we know there's no newline at the
2064 * end, so we add one of our own free will.
2066 fprintf(stdout, "%s", cp);
2068 if (endp != oendp) {
2069 fprintf(stdout, "\n");
2074 eunlink(job->outFile);
2081 * Handle the exit of a child. Called from Make_Make.
2084 * The job descriptor is removed from the list of children.
2087 * We do waits, blocking or not, according to the wisdom of our
2088 * caller, until there are no more children to report. For each
2089 * job, call JobFinish to finish things off. This will take care of
2090 * putting jobs on the stoppedJobs queue.
2093 Job_CatchChildren(Boolean block)
2095 pid_t pid; /* pid of dead child */
2096 Job *job; /* job descriptor for dead child */
2097 int status; /* Exit/termination status */
2100 * Don't even bother if we know there's no one around.
2107 pid = waitpid((pid_t)-1, &status,
2108 (block ? 0 : WNOHANG) | WUNTRACED);
2112 DEBUGF(JOB, ("Process %jd exited or stopped.\n",
2115 TAILQ_FOREACH(job, &jobs, link) {
2116 if (job->pid == pid)
2121 if (WIFSIGNALED(status) &&
2122 (WTERMSIG(status) == SIGCONT)) {
2123 TAILQ_FOREACH(job, &jobs, link) {
2124 if (job->pid == pid)
2128 Error("Resumed child (%jd) "
2129 "not in table", (intmax_t)pid);
2132 TAILQ_REMOVE(&stoppedJobs, job, link);
2134 Error("Child (%jd) not in table?",
2139 TAILQ_REMOVE(&jobs, job, link);
2141 if (fifoFd >= 0 && maxJobs > 1) {
2142 write(fifoFd, "+", 1);
2144 if (nJobs >= maxJobs)
2149 DEBUGF(JOB, ("Job queue is no longer full.\n"));
2154 JobFinish(job, &status);
2157 JobPassSig(interrupted);
2162 * Catch the output from our children, if we're using
2163 * pipes do so. Otherwise just block time until we get a
2164 * signal(most likely a SIGCHLD) since there's no point in
2165 * just spinning when there's nothing to do and the reaping
2166 * of a child can wait for a while.
2169 * Output is read from pipes if we're piping.
2170 * -----------------------------------------------------------------------
2174 Job_CatchOutput(int flag __unused)
2176 Job_CatchOutput(int flag)
2182 struct kevent kev[KEV_SIZE];
2185 struct timeval timeout;
2194 if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
2196 Punt("kevent: %s", strerror(errno));
2198 JobPassSig(interrupted);
2200 for (i = 0; i < nfds; i++) {
2201 if (kev[i].flags & EV_ERROR) {
2202 warnc(kev[i].data, "kevent");
2205 switch (kev[i].filter) {
2207 JobDoOutput(kev[i].udata, FALSE);
2211 * Just wake up and let
2212 * Job_CatchChildren() collect the
2221 timeout.tv_sec = SEL_SEC;
2222 timeout.tv_usec = SEL_USEC;
2223 if (flag && jobFull && fifoFd >= 0)
2224 FD_SET(fifoFd, &readfds);
2226 nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
2227 (fd_set *)NULL, &timeout);
2230 JobPassSig(interrupted);
2233 if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2237 job = TAILQ_FIRST(&jobs);
2238 while (nfds != 0 && job != NULL) {
2239 if (FD_ISSET(job->inPipe, &readfds)) {
2240 JobDoOutput(job, FALSE);
2243 job = TAILQ_NEXT(job, link);
2245 #endif /* !USE_KQUEUE */
2251 * Start the creation of a target. Basically a front-end for
2252 * JobStart used by the Make module.
2255 * Another job is started.
2261 JobStart(gn, 0, NULL);
2266 * Make a new copy of the shell structure including a copy of the strings
2267 * in it. This also defaults some fields in case they are NULL.
2270 * The function returns a pointer to the new shell structure.
2272 static struct Shell *
2273 JobCopyShell(const struct Shell *osh)
2277 nsh = emalloc(sizeof(*nsh));
2278 nsh->name = estrdup(osh->name);
2280 if (osh->echoOff != NULL)
2281 nsh->echoOff = estrdup(osh->echoOff);
2283 nsh->echoOff = NULL;
2284 if (osh->echoOn != NULL)
2285 nsh->echoOn = estrdup(osh->echoOn);
2288 nsh->hasEchoCtl = osh->hasEchoCtl;
2290 if (osh->noPrint != NULL)
2291 nsh->noPrint = estrdup(osh->noPrint);
2293 nsh->noPrint = NULL;
2295 nsh->hasErrCtl = osh->hasErrCtl;
2296 if (osh->errCheck == NULL)
2297 nsh->errCheck = estrdup("");
2299 nsh->errCheck = estrdup(osh->errCheck);
2300 if (osh->ignErr == NULL)
2301 nsh->ignErr = estrdup("%s");
2303 nsh->ignErr = estrdup(osh->ignErr);
2305 if (osh->echo == NULL)
2306 nsh->echo = estrdup("");
2308 nsh->echo = estrdup(osh->echo);
2310 if (osh->exit == NULL)
2311 nsh->exit = estrdup("");
2313 nsh->exit = estrdup(osh->exit);
2320 * Free a shell structure and all associated strings.
2323 JobFreeShell(struct Shell *sh)
2343 if (commandShell == NULL)
2344 commandShell = JobMatchShell(shells[DEFSHELL].name);
2346 if (shellPath == NULL) {
2348 * The user didn't specify a shell to use, so we are using the
2349 * default one... Both the absolute path and the last component
2350 * must be set. The last component is taken from the 'name'
2351 * field of the default shell description pointed-to by
2352 * commandShell. All default shells are located in
2355 shellName = commandShell->name;
2356 shellPath = str_concat(PATH_DEFSHELLDIR, shellName,
2363 * Initialize the process module, given a maximum number of jobs.
2366 * lists and counters are initialized
2369 Job_Init(int maxproc)
2371 GNode *begin; /* node for commands to do at the very start */
2373 struct sigaction sa;
2376 env = getenv("MAKE_JOBS_FIFO");
2378 if (env == NULL && maxproc > 1) {
2380 * We did not find the environment variable so we are the
2381 * leader. Create the fifo, open it, write one char per
2382 * allowed job into the pipe.
2385 if (!mkfifo(fifoName, 0600)) {
2386 fifoFd = open(fifoName, O_RDWR | O_NONBLOCK, 0);
2389 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2391 setenv("MAKE_JOBS_FIFO", env, 1);
2392 while (maxproc-- > 0) {
2393 write(fifoFd, "+", 1);
2395 /* The master make does not get a magic token */
2404 } else if (env != NULL) {
2406 * We had the environment variable so we are a slave.
2407 * Open fifo and give ourselves a magic token which represents
2408 * the token our parent make has grabbed to start his make
2409 * process. Otherwise the sub-makes would gobble up tokens and
2410 * the proper number of tokens to specify to -j would depend
2411 * on the depth of the tree and the order of execution.
2413 fifoFd = open(env, O_RDWR, 0);
2415 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2432 if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2434 * If only one job can run at a time, there's no need for a
2435 * banner, no is there?
2445 * Catch the four signals that POSIX specifies if they aren't ignored.
2446 * JobCatchSignal will just set global variables and hope someone
2447 * else is going to handle the interrupt.
2449 sa.sa_handler = JobCatchSig;
2450 sigemptyset(&sa.sa_mask);
2453 if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2454 sigaction(SIGINT, &sa, NULL);
2456 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2457 sigaction(SIGHUP, &sa, NULL);
2459 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2460 sigaction(SIGQUIT, &sa, NULL);
2462 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2463 sigaction(SIGTERM, &sa, NULL);
2466 * There are additional signals that need to be caught and passed if
2467 * either the export system wants to be told directly of signals or if
2468 * we're giving each job its own process group (since then it won't get
2469 * signals from the terminal driver as we own the terminal)
2471 #if defined(USE_PGRP)
2472 if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2473 sigaction(SIGTSTP, &sa, NULL);
2475 if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2476 sigaction(SIGTTOU, &sa, NULL);
2478 if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2479 sigaction(SIGTTIN, &sa, NULL);
2481 if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2482 sigaction(SIGWINCH, &sa, NULL);
2487 if ((kqfd = kqueue()) == -1) {
2488 Punt("kqueue: %s", strerror(errno));
2492 begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2494 if (begin != NULL) {
2495 JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2498 Job_CatchChildren(!usePipes);
2501 postCommands = Targ_FindNode(".END", TARG_CREATE);
2506 * See if the job table is full. It is considered full if it is OR
2507 * if we are in the process of aborting OR if we have
2508 * reached/exceeded our local quota. This prevents any more jobs
2512 * TRUE if the job table is full, FALSE otherwise
2522 if (fifoFd >= 0 && jobFull) {
2523 i = read(fifoFd, &c, 1);
2534 * See if the job table is empty. Because the local concurrency may
2535 * be set to 0, it is possible for the job table to become empty,
2536 * while the list of stoppedJobs remains non-empty. In such a case,
2537 * we want to restart as many jobs as we can.
2540 * TRUE if it is. FALSE if it ain't.
2546 if (!TAILQ_EMPTY(&stoppedJobs) && !aborting) {
2548 * The job table is obviously not full if it has no
2549 * jobs in it...Try and restart the stopped jobs.
2564 * Find a matching shell in 'shells' given its final component.
2567 * A pointer to a freshly allocated Shell structure with a copy
2568 * of the static structure or NULL if no shell with the given name
2571 static struct Shell *
2572 JobMatchShell(const char *name)
2574 const struct CShell *sh; /* Pointer into shells table */
2577 for (sh = shells; sh < shells + __arysize(shells); sh++)
2578 if (strcmp(sh->name, name) == 0)
2581 if (sh == shells + __arysize(shells))
2585 nsh = emalloc(sizeof(*nsh));
2587 nsh->name = estrdup(sh->name);
2588 nsh->echoOff = estrdup(sh->echoOff);
2589 nsh->echoOn = estrdup(sh->echoOn);
2590 nsh->hasEchoCtl = sh->hasEchoCtl;
2591 nsh->noPrint = estrdup(sh->noPrint);
2592 nsh->hasErrCtl = sh->hasErrCtl;
2593 nsh->errCheck = estrdup(sh->errCheck);
2594 nsh->ignErr = estrdup(sh->ignErr);
2595 nsh->echo = estrdup(sh->echo);
2596 nsh->exit = estrdup(sh->exit);
2603 * Parse a shell specification and set up commandShell, shellPath
2604 * and shellName appropriately.
2607 * FAILURE if the specification was incorrect.
2610 * commandShell points to a Shell structure (either predefined or
2611 * created from the shell spec), shellPath is the full path of the
2612 * shell described by commandShell, while shellName is just the
2613 * final component of shellPath.
2616 * A shell specification consists of a .SHELL target, with dependency
2617 * operator, followed by a series of blank-separated words. Double
2618 * quotes can be used to use blanks in words. A backslash escapes
2619 * anything (most notably a double-quote and a space) and
2620 * provides the functionality it does in C. Each word consists of
2621 * keyword and value separated by an equal sign. There should be no
2622 * unnecessary spaces in the word. The keywords are as follows:
2623 * name Name of shell.
2624 * path Location of shell. Overrides "name" if given
2625 * quiet Command to turn off echoing.
2626 * echo Command to turn echoing on
2627 * filter Result of turning off echoing that shouldn't be
2629 * echoFlag Flag to turn echoing on at the start
2630 * errFlag Flag to turn error checking on at the start
2631 * hasErrCtl True if shell has error checking control
2632 * check Command to turn on error checking if hasErrCtl
2633 * is TRUE or template of command to echo a command
2634 * for which error checking is off if hasErrCtl is
2636 * ignore Command to turn off error checking if hasErrCtl
2637 * is TRUE or template of command to execute a
2638 * command so as to ignore any errors it returns if
2639 * hasErrCtl is FALSE.
2642 Job_ParseShell(char *line)
2650 Boolean fullSpec = FALSE;
2651 struct Shell newShell;
2654 while (isspace((unsigned char)*line)) {
2657 words = brk_string(line, &wordCount, TRUE);
2659 memset(&newShell, 0, sizeof(newShell));
2663 * Parse the specification by keyword but skip the first word - it
2664 * is not set by brk_string.
2669 for (argc = wordCount, argv = words; argc != 0; argc--, argv++) {
2671 * Split keyword and value
2673 if ((eq = strchr(*argv, '=')) == NULL) {
2674 Parse_Error(PARSE_FATAL, "missing '=' in shell "
2675 "specification keyword '%s'", *argv);
2680 if (strcmp(*argv, "path") == 0) {
2682 } else if (strcmp(*argv, "name") == 0) {
2684 } else if (strcmp(*argv, "quiet") == 0) {
2685 newShell.echoOff = eq;
2687 } else if (strcmp(*argv, "echo") == 0) {
2688 newShell.echoOn = eq;
2690 } else if (strcmp(*argv, "filter") == 0) {
2691 newShell.noPrint = eq;
2693 } else if (strcmp(*argv, "echoFlag") == 0) {
2696 } else if (strcmp(*argv, "errFlag") == 0) {
2699 } else if (strcmp(*argv, "hasErrCtl") == 0) {
2700 newShell.hasErrCtl = (*eq == 'Y' || *eq == 'y' ||
2701 *eq == 'T' || *eq == 't');
2703 } else if (strcmp(*argv, "check") == 0) {
2704 newShell.errCheck = eq;
2706 } else if (strcmp(*argv, "ignore") == 0) {
2707 newShell.ignErr = eq;
2710 Parse_Error(PARSE_FATAL, "unknown keyword in shell "
2711 "specification '%s'", *argv);
2717 * Some checks (could be more)
2720 if ((newShell.echoOn != NULL) ^ (newShell.echoOff != NULL))
2721 Parse_Error(PARSE_FATAL, "Shell must have either both "
2722 "echoOff and echoOn or none of them");
2724 if (newShell.echoOn != NULL && newShell.echoOff)
2725 newShell.hasEchoCtl = TRUE;
2730 * If no path was given, the user wants one of the pre-defined
2731 * shells, yes? So we find the one s/he wants with the help of
2732 * JobMatchShell and set things up the right way. shellPath
2733 * will be set up by Job_Init.
2735 if (newShell.name == NULL) {
2736 Parse_Error(PARSE_FATAL,
2737 "Neither path nor name specified");
2740 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2741 Parse_Error(PARSE_FATAL, "%s: no matching shell",
2748 * The user provided a path. If s/he gave nothing else
2749 * (fullSpec is FALSE), try and find a matching shell in the
2750 * ones we know of. Else we just take the specification at its
2751 * word and copy it to a new location. In either case, we need
2752 * to record the path the user gave for the shell.
2755 shellPath = estrdup(path);
2756 if (newShell.name == NULL) {
2757 /* get the base name as the name */
2758 path = strrchr(path, '/');
2764 newShell.name = path;
2768 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2769 Parse_Error(PARSE_FATAL,
2770 "%s: no matching shell", newShell.name);
2774 sh = JobCopyShell(&newShell);
2778 /* set the new shell */
2779 JobFreeShell(commandShell);
2782 shellName = commandShell->name;
2789 * Handle the receipt of an interrupt.
2792 * All children are killed. Another job will be started if the
2793 * .INTERRUPT target was given.
2796 JobInterrupt(int runINTERRUPT, int signo)
2798 Job *job; /* job descriptor in that element */
2799 GNode *interrupt; /* the node describing the .INTERRUPT target */
2801 aborting = ABORT_INTERRUPT;
2803 TAILQ_FOREACH(job, &jobs, link) {
2804 if (!Targ_Precious(job->node)) {
2805 char *file = (job->node->path == NULL ?
2806 job->node->name : job->node->path);
2808 if (!noExecute && eunlink(file) != -1) {
2809 Error("*** %s removed", file);
2813 DEBUGF(JOB, ("JobInterrupt passing signal to child "
2814 "%jd.\n", (intmax_t)job->pid));
2815 KILL(job->pid, signo);
2819 if (runINTERRUPT && !touchFlag) {
2821 * clear the interrupted flag because we would get an
2822 * infinite loop otherwise.
2826 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2827 if (interrupt != NULL) {
2828 ignoreErrors = FALSE;
2830 JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
2833 Job_CatchChildren(!usePipes);
2841 * Do final processing such as the running of the commands
2842 * attached to the .END target.
2845 * Number of errors reported.
2851 if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
2853 Error("Errors reported so .END ignored");
2855 JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
2859 Job_CatchChildren(!usePipes);
2874 * Waits for all running jobs to finish and returns. Sets 'aborting'
2875 * to ABORT_WAIT to prevent other jobs from starting.
2878 * Currently running jobs finish.
2884 aborting = ABORT_WAIT;
2885 while (nJobs != 0) {
2887 Job_CatchChildren(!usePipes);
2894 * Abort all currently running jobs without handling output or anything.
2895 * This function is to be called only in the event of a major
2896 * error. Most definitely NOT to be called from JobInterrupt.
2899 * All children are killed, not just the firstborn
2904 Job *job; /* the job descriptor in that element */
2907 aborting = ABORT_ERROR;
2910 TAILQ_FOREACH(job, &jobs, link) {
2912 * kill the child process with increasingly drastic
2913 * signals to make darn sure it's dead.
2915 KILL(job->pid, SIGINT);
2916 KILL(job->pid, SIGKILL);
2921 * Catch as many children as want to report in at first, then give up
2923 while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2929 * Tries to restart stopped jobs if there are slots available.
2930 * Note that this tries to restart them regardless of pending errors.
2931 * It's not good to leave stopped jobs lying around!
2934 * Resumes(and possibly migrates) jobs.
2937 JobRestartJobs(void)
2941 while (!jobFull && (job = TAILQ_FIRST(&stoppedJobs)) != NULL) {
2942 DEBUGF(JOB, ("Job queue is not full. "
2943 "Restarting a stopped job.\n"));
2944 TAILQ_REMOVE(&stoppedJobs, job, link);
2951 * Execute the command in cmd, and return the output of that command
2955 * A string containing the output of the command, or the empty string
2956 * If error is not NULL, it contains the reason for the command failure
2957 * Any output sent to stderr in the child process is passed to stderr,
2958 * and not captured in the string.
2961 * The string must be freed by the caller.
2964 Cmd_Exec(const char *cmd, const char **error)
2966 int fds[2]; /* Pipe streams */
2967 int cpid; /* Child PID */
2968 int pid; /* PID from wait() */
2969 int status; /* command exit status */
2970 Buffer *buf; /* buffer to store the result */
2977 if (shellPath == NULL)
2980 * Open a pipe for fetching its output
2982 if (pipe(fds) == -1) {
2983 *error = "Couldn't create pipe for \"%s\"";
2987 ps.in = STDIN_FILENO;
2989 ps.err = STDERR_FILENO;
2991 ps.merge_errors = 0;
2995 /* Set up arguments for shell */
2996 ps.argv = emalloc(4 * sizeof(char *));
2997 ps.argv[0] = strdup(shellName);
2998 ps.argv[1] = strdup("-c");
2999 ps.argv[2] = strdup(cmd);
3003 * Fork. Warning since we are doing vfork() instead of fork(),
3004 * do not allocate memory in the child process!
3006 if ((cpid = vfork()) == -1) {
3007 *error = "Couldn't exec \"%s\"";
3009 } else if (cpid == 0) {
3013 close(fds[0]); /* Close input side of pipe */
3025 * No need for the writing half
3030 char result[BUFSIZ];
3032 rcnt = read(fds[0], result, sizeof(result));
3034 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
3035 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
3038 *error = "Error reading shell's output for \"%s\"";
3041 * Close the input side of the pipe.
3046 * Wait for the process to exit.
3048 while (((pid = wait(&status)) != cpid) && (pid >= 0))
3052 *error = "\"%s\" returned non-zero status";
3054 Buf_StripNewlines(buf);
3063 * The routines in this file implement the full-compatibility
3064 * mode of PMake. Most of the special functionality of PMake
3065 * is available in this mode. Things not supported:
3066 * - different shells.
3067 * - friendly variable substitution.
3070 * Compat_Run Initialize things for this module and recreate
3071 * thems as need creatin'
3075 * The following array is used to make a fast determination of which
3076 * characters are interpreted specially by the shell. If a command
3077 * contains any of these characters, it is executed by the shell, not
3080 static char meta[256];
3082 static GNode *curTarg = NULL;
3083 static GNode *ENDNode;
3088 const char *cp; /* Pointer to string of shell meta-characters */
3090 for (cp = "#=|^(){};&<>*?[]:$`\\\n"; *cp != '\0'; cp++) {
3091 meta[(unsigned char)*cp] = 1;
3094 * The null character serves as a sentinel in the string.
3100 * Interrupt handler - set flag and defer handling to the main code
3103 CompatCatchSig(int signo)
3106 interrupted = signo;
3110 *-----------------------------------------------------------------------
3111 * CompatInterrupt --
3112 * Interrupt the creation of the current target and remove it if
3113 * it ain't precious.
3119 * The target is removed and the process exits. If .INTERRUPT exists,
3120 * its commands are run first WITH INTERRUPTS IGNORED..
3122 *-----------------------------------------------------------------------
3125 CompatInterrupt(int signo)
3128 sigset_t nmask, omask;
3131 sigemptyset(&nmask);
3132 sigaddset(&nmask, SIGINT);
3133 sigaddset(&nmask, SIGTERM);
3134 sigaddset(&nmask, SIGHUP);
3135 sigaddset(&nmask, SIGQUIT);
3136 sigprocmask(SIG_SETMASK, &nmask, &omask);
3138 /* prevent recursion in evaluation of .INTERRUPT */
3141 if (curTarg != NULL && !Targ_Precious(curTarg)) {
3143 char *file = Var_Value(TARGET, curTarg, &p1);
3145 if (!noExecute && eunlink(file) != -1) {
3146 printf("*** %s removed\n", file);
3152 * Run .INTERRUPT only if hit with interrupt signal
3154 if (signo == SIGINT) {
3155 gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
3157 LST_FOREACH(ln, &gn->commands) {
3158 if (Compat_RunCommand(Lst_Datum(ln), gn))
3164 sigprocmask(SIG_SETMASK, &omask, NULL);
3166 if (signo == SIGQUIT)
3168 signal(signo, SIG_DFL);
3169 kill(getpid(), signo);
3173 *-----------------------------------------------------------------------
3174 * Compat_RunCommand --
3175 * Execute the next command for a target. If the command returns an
3176 * error, the node's made field is set to ERROR and creation stops.
3177 * The node from which the command came is also given.
3180 * 0 if the command succeeded, 1 if an error occurred.
3183 * The node's 'made' field may be set to ERROR.
3185 *-----------------------------------------------------------------------
3188 Compat_RunCommand(char *cmd, GNode *gn)
3190 char *cmdStart; /* Start of expanded command */
3192 Boolean silent; /* Don't print command */
3193 Boolean doit; /* Execute even in -n */
3194 Boolean errCheck; /* Check errors */
3195 int reason; /* Reason for child's death */
3196 int status; /* Description of child's death */
3197 int cpid; /* Child actually found */
3198 ReturnStatus rstat; /* Status of fork */
3199 LstNode *cmdNode; /* Node where current command is located */
3200 char **av; /* Argument vector for thing to exec */
3201 char *cmd_save; /* saved cmd */
3205 * Avoid clobbered variable warnings by forcing the compiler
3206 * to ``unregister'' variables
3212 silent = gn->type & OP_SILENT;
3213 errCheck = !(gn->type & OP_IGNORE);
3216 cmdNode = Lst_Member(&gn->commands, cmd);
3217 cmdStart = Buf_Peel(Var_Subst(cmd, gn, FALSE));
3220 * brk_string will return an argv with a NULL in av[0], thus causing
3221 * execvp() to choke and die horribly. Besides, how can we execute a
3222 * null command? In any case, we warn the user that the command
3223 * expanded to nothing (is this the right thing to do?).
3225 if (*cmdStart == '\0') {
3227 Error("%s expands to empty string", cmd);
3232 Lst_Replace(cmdNode, cmdStart);
3234 if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
3235 Lst_AtEnd(&ENDNode->commands, cmdStart);
3237 } else if (strcmp(cmdStart, "...") == 0) {
3238 gn->type |= OP_SAVE_CMDS;
3242 while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
3246 silent = DEBUG(LOUD) ? FALSE : TRUE;
3255 if (!meta[0]) /* we came here from jobs */
3262 while (isspace((unsigned char)*cmd))
3266 * Print the command before echoing if we're not supposed to be quiet
3267 * for this one. We also print the command if -n given, but not if '+'.
3269 if (!silent || (noExecute && !doit)) {
3270 printf("%s\n", cmd);
3275 * If we're not supposed to execute any commands, this is as far as
3278 if (!doit && noExecute) {
3283 * Search for meta characters in the command. If there are no meta
3284 * characters, there's no need to execute a shell to execute the
3287 for (cp = cmd; !meta[(unsigned char)*cp]; cp++)
3292 * If *cp isn't the null character, we hit a "meta" character
3293 * and need to pass the command off to the shell.
3299 const char *sh_builtin[] = {
3300 "alias", "cd", "eval", "exec",
3301 "exit", "read", "set", "ulimit",
3302 "unalias", "umask", "unset", "wait",
3307 * Break the command into words to form an argument
3308 * vector we can execute. brk_string sticks our name
3309 * in av[0], so we have to skip over it...
3311 av = brk_string(cmd, NULL, TRUE);
3314 for (p = sh_builtin; *p != 0; p++) {
3315 if (strcmp(av[0], *p) == 0) {
3317 * This command must be passed by the shell
3318 * for other reasons.. or.. possibly not at
3327 ps.in = STDIN_FILENO;
3328 ps.out = STDOUT_FILENO;
3329 ps.err = STDERR_FILENO;
3331 ps.merge_errors = 0;
3337 * We give the shell the -e flag as well as -c if it's
3338 * supposed to exit when it hits an error.
3340 ps.argv = emalloc(4 * sizeof(char *));
3341 ps.argv[0] = strdup(shellName);
3342 ps.argv[1] = strdup(errCheck ? "-ec" : "-c");
3343 ps.argv[2] = strdup(cmd);
3350 * Fork and execute the single command. If the fork fails, we abort.
3351 * Warning since we are doing vfork() instead of fork(),
3352 * do not allocate memory in the child process!
3354 if ((cpid = vfork()) == -1) {
3355 Fatal("Could not fork");
3357 } else if (cpid == 0) {
3374 * we need to print out the command associated with this
3375 * Gnode in Targ_PrintCmd from Targ_PrintGraph when debugging
3376 * at level g2, in main(), Fatal() and DieHorribly(),
3377 * therefore do not free it when debugging.
3379 if (!DEBUG(GRAPH2)) {
3381 Lst_Replace(cmdNode, cmd_save);
3384 * The child is off and running. Now all we can do is wait...
3387 while ((rstat = wait(&reason)) != cpid) {
3388 if (interrupted || (rstat == -1 && errno != EINTR)) {
3393 CompatInterrupt(interrupted);
3396 if (WIFSTOPPED(reason)) {
3398 status = WSTOPSIG(reason);
3399 } else if (WIFEXITED(reason)) {
3401 status = WEXITSTATUS(reason);
3403 printf("*** Error code %d",
3408 status = WTERMSIG(reason);
3409 printf("*** Signal %d", status);
3412 if (!WIFEXITED(reason) || status != 0) {
3421 printf(" (continuing)\n");
3425 * Continue executing
3426 * commands for this target.
3427 * If we return 0, this will
3430 printf(" (ignored)\n");
3436 Fatal("error in wait: %d", rstat);
3446 *-----------------------------------------------------------------------
3448 * Make a target, given the parent, to abort if necessary.
3451 * If an error is detected and not being ignored, the process exits.
3453 *-----------------------------------------------------------------------
3456 CompatMake(GNode *gn, GNode *pgn)
3460 if (gn->type & OP_USE) {
3461 Make_HandleUse(gn, pgn);
3463 } else if (gn->made == UNMADE) {
3465 * First mark ourselves to be made, then apply whatever
3466 * transformations the suffix module thinks are necessary.
3467 * Once that's done, we can descend and make all our children.
3468 * If any of them has an error but the -k flag was given, our
3469 * 'make' field will be set FALSE again. This is our signal to
3470 * not attempt to do anything but abort our parent as well.
3473 gn->made = BEINGMADE;
3475 LST_FOREACH(ln, &gn->children)
3476 CompatMake(Lst_Datum(ln), gn);
3483 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3485 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
3490 * All the children were made ok. Now cmtime contains the
3491 * modification time of the newest child, we need to find out
3492 * if we exist and when we were modified last. The criteria for
3493 * datedness are defined by the Make_OODate function.
3495 DEBUGF(MAKE, ("Examining %s...", gn->name));
3496 if (!Make_OODate(gn)) {
3497 gn->made = UPTODATE;
3498 DEBUGF(MAKE, ("up-to-date.\n"));
3501 DEBUGF(MAKE, ("out-of-date.\n"));
3505 * If the user is just seeing if something is out-of-date,
3506 * exit now to tell him/her "yes".
3513 * We need to be re-made. We also have to make sure we've got
3514 * a $? variable. To be nice, we also define the $> variable
3515 * using Make_DoAllVar().
3520 * Alter our type to tell if errors should be ignored or things
3521 * should not be printed so Compat_RunCommand knows what to do.
3523 if (Targ_Ignore(gn)) {
3524 gn->type |= OP_IGNORE;
3526 if (Targ_Silent(gn)) {
3527 gn->type |= OP_SILENT;
3530 if (Job_CheckCommands(gn, Fatal)) {
3532 * Our commands are ok, but we still have to worry
3533 * about the -t flag...
3537 LST_FOREACH(ln, &gn->commands) {
3538 if (Compat_RunCommand(Lst_Datum(ln),
3544 Job_Touch(gn, gn->type & OP_SILENT);
3550 if (gn->made != ERROR) {
3552 * If the node was made successfully, mark it so, update
3553 * its modification time and timestamp all its parents.
3554 * Note that for .ZEROTIME targets, the timestamping
3555 * isn't done. This is to keep its state from affecting
3556 * that of its parent.
3561 * We can't re-stat the thing, but we can at least take
3562 * care of rules where a target depends on a source that
3563 * actually creates the target, but only if it has
3571 * mv y.tab.o parse.o
3572 * cmp -s y.tab.h parse.h || mv y.tab.h parse.h
3574 * In this case, if the definitions produced by yacc
3575 * haven't changed from before, parse.h won't have been
3576 * updated and gn->mtime will reflect the current
3577 * modification time for parse.h. This is something of a
3578 * kludge, I admit, but it's a useful one..
3580 * XXX: People like to use a rule like
3584 * To force things that depend on FRC to be made, so we
3585 * have to check for gn->children being empty as well...
3587 if (!Lst_IsEmpty(&gn->commands) ||
3588 Lst_IsEmpty(&gn->children)) {
3593 * This is what Make does and it's actually a good
3594 * thing, as it allows rules like
3596 * cmp -s y.tab.h parse.h || cp y.tab.h parse.h
3598 * to function as intended. Unfortunately, thanks to
3599 * the stateless nature of NFS (and the speed of this
3600 * program), there are times when the modification time
3601 * of a file created on a remote machine will not be
3602 * modified before the stat() implied by the Dir_MTime
3603 * occurs, thus leading us to believe that the file
3604 * is unchanged, wreaking havoc with files that depend
3607 * I have decided it is better to make too much than to
3608 * make too little, so this stuff is commented out
3609 * unless you're sure it's ok.
3612 if (noExecute || Dir_MTime(gn) == 0) {
3615 if (gn->cmtime > gn->mtime)
3616 gn->mtime = gn->cmtime;
3617 DEBUGF(MAKE, ("update time: %s\n",
3618 Targ_FmtTime(gn->mtime)));
3620 if (!(gn->type & OP_EXEC)) {
3621 pgn->childMade = TRUE;
3622 Make_TimeStamp(pgn, gn);
3625 } else if (keepgoing) {
3631 printf("\n\nStop in %s.\n",
3632 Var_Value(".CURDIR", gn, &p1));
3636 } else if (gn->made == ERROR) {
3638 * Already had an error when making this beastie. Tell the
3643 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3645 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
3650 Error("Graph cycles through %s\n", gn->name);
3655 if ((gn->type & OP_EXEC) == 0) {
3656 pgn->childMade = TRUE;
3657 Make_TimeStamp(pgn, gn);
3661 if ((gn->type & OP_EXEC) == 0) {
3662 Make_TimeStamp(pgn, gn);
3674 *-----------------------------------------------------------------------
3676 * Start making again, given a list of target nodes.
3684 *-----------------------------------------------------------------------
3687 Compat_Run(Lst *targs)
3689 GNode *gn = NULL; /* Current root target */
3690 int error_cnt; /* Number of targets not remade due to errors */
3694 Shell_Init(); /* Set up shell. */
3696 if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
3697 signal(SIGINT, CompatCatchSig);
3699 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
3700 signal(SIGTERM, CompatCatchSig);
3702 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
3703 signal(SIGHUP, CompatCatchSig);
3705 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
3706 signal(SIGQUIT, CompatCatchSig);
3709 ENDNode = Targ_FindNode(".END", TARG_CREATE);
3711 * If the user has defined a .BEGIN target, execute the commands
3715 gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
3717 LST_FOREACH(ln, &gn->commands) {
3718 if (Compat_RunCommand(Lst_Datum(ln), gn))
3721 if (gn->made == ERROR) {
3722 printf("\n\nStop.\n");
3729 * For each entry in the list of targets to create, call CompatMake on
3730 * it to create the thing. CompatMake will leave the 'made' field of gn
3731 * in one of several states:
3732 * UPTODATE gn was already up-to-date
3733 * MADE gn was recreated successfully
3734 * ERROR An error occurred while gn was being created
3735 * ABORTED gn was not remade because one of its inferiors
3736 * could not be made due to errors.
3739 while (!Lst_IsEmpty(targs)) {
3740 gn = Lst_DeQueue(targs);
3743 if (gn->made == UPTODATE) {
3744 printf("`%s' is up to date.\n", gn->name);
3745 } else if (gn->made == ABORTED) {
3746 printf("`%s' not remade because of errors.\n",
3753 * If the user has defined a .END target, run its commands.
3755 if (error_cnt == 0) {
3756 LST_FOREACH(ln, &ENDNode->commands) {
3757 if (Compat_RunCommand(Lst_Datum(ln), gn))