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.102 2005/05/19 16:51:45 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 * The routines in this file implement the full-compatibility
101 * mode of PMake. Most of the special functionality of PMake
102 * is available in this mode. Things not supported:
103 * - different shells.
104 * - friendly variable substitution.
107 * Compat_Run Initialize things for this module and recreate
108 * thems as need creatin'
111 #include <sys/queue.h>
112 #include <sys/types.h>
113 #include <sys/select.h>
114 #include <sys/stat.h>
116 #include <sys/event.h>
118 #include <sys/wait.h>
123 #include <inttypes.h>
139 #include "pathnames.h"
146 #define TMPPAT "/tmp/makeXXXXXXXXXX"
147 #define MKLVL_MAXVAL 500
148 #define MKLVL_ENVVAR "__MKLVL__"
152 * The SEL_ constants determine the maximum amount of time spent in select
153 * before coming out to see if a child has finished. SEL_SEC is the number of
154 * seconds and SEL_USEC is the number of micro-seconds
158 #endif /* !USE_KQUEUE */
161 * Job Table definitions.
163 * The job "table" is kept as a linked Lst in 'jobs', with the number of
164 * active jobs maintained in the 'nJobs' variable. At no time will this
165 * exceed the value of 'maxJobs', initialized by the Job_Init function.
167 * When a job is finished, the Make_Update function is called on each of the
168 * parents of the node which was just remade. This takes care of the upward
169 * traversal of the dependency graph.
171 #define JOB_BUFSIZE 1024
173 pid_t pid; /* The child's process ID */
175 struct GNode *node; /* The target the child is making */
178 * A LstNode for the first command to be saved after the job completes.
179 * This is NULL if there was no "..." in the job's commands.
184 * An FILE* for writing out the commands. This is only
185 * used before the job is actually started.
190 * A word of flags which determine how the module handles errors,
191 * echoing, etc. for the job
193 short flags; /* Flags to control treatment of job */
194 #define JOB_IGNERR 0x001 /* Ignore non-zero exits */
195 #define JOB_SILENT 0x002 /* no output */
196 #define JOB_SPECIAL 0x004 /* Target is a special one. i.e. run it locally
197 * if we can't export it and maxLocal is 0 */
198 #define JOB_IGNDOTS 0x008 /* Ignore "..." lines when processing
200 #define JOB_FIRST 0x020 /* Job is first job for the node */
201 #define JOB_RESTART 0x080 /* Job needs to be completely restarted */
202 #define JOB_RESUME 0x100 /* Job needs to be resumed b/c it stopped,
204 #define JOB_CONTINUING 0x200 /* We are in the process of resuming this job.
205 * Used to avoid infinite recursion between
206 * JobFinish and JobRestart */
208 /* union for handling shell's output */
211 * This part is used when usePipes is true.
212 * The output is being caught via a pipe and the descriptors
213 * of our pipe, an array in which output is line buffered and
214 * the current position in that buffer are all maintained for
219 * Input side of pipe associated with
220 * job's output channel
225 * Output side of pipe associated with job's
231 * Buffer for storing the output of the
234 char op_outBuf[JOB_BUFSIZE + 1];
236 /* Current position in op_outBuf */
241 * If usePipes is false the output is routed to a temporary
242 * file and all that is kept is the name of the file and the
243 * descriptor open to the file.
246 /* Name of file to which shell output was rerouted */
247 char of_outFile[sizeof(TMPPAT)];
250 * Stream open to the output file. Used to funnel all
251 * from a single job to one file while still allowing
252 * multiple shell invocations
257 } output; /* Data for tracking a shell's output */
259 TAILQ_ENTRY(Job) link; /* list link */
262 #define outPipe output.o_pipe.op_outPipe
263 #define inPipe output.o_pipe.op_inPipe
264 #define outBuf output.o_pipe.op_outBuf
265 #define curPos output.o_pipe.op_curPos
266 #define outFile output.o_file.of_outFile
267 #define outFd output.o_file.of_outFd
269 TAILQ_HEAD(JobList, Job);
272 * Shell Specifications:
274 * Some special stuff goes on if a shell doesn't have error control. In such
275 * a case, errCheck becomes a printf template for echoing the command,
276 * should echoing be on and ignErr becomes another printf template for
277 * executing the command while ignoring the return status. If either of these
278 * strings is empty when hasErrCtl is FALSE, the command will be executed
279 * anyway as is and if it causes an error, so be it.
281 #define DEF_SHELL_STRUCT(TAG, CONST) \
284 * the name of the shell. For Bourne and C shells, this is used \
285 * only to find the shell description when used as the single \
286 * source of a .SHELL target. For user-defined shells, this is \
287 * the full path of the shell. \
291 /* True if both echoOff and echoOn defined */ \
292 Boolean hasEchoCtl; \
294 CONST char *echoOff; /* command to turn off echo */ \
295 CONST char *echoOn; /* command to turn it back on */\
298 * What the shell prints, and its length, when given the \
299 * echo-off command. This line will not be printed when \
300 * received from the shell. This is usually the command which \
301 * was executed to turn off echoing \
303 CONST char *noPrint; \
305 /* set if can control error checking for individual commands */ \
308 /* string to turn error checking on */ \
309 CONST char *errCheck; \
311 /* string to turn off error checking */ \
312 CONST char *ignErr; \
314 CONST char *echo; /* command line flag: echo commands */ \
315 CONST char *exit; /* command line flag: exit on error */ \
318 DEF_SHELL_STRUCT(Shell,);
319 DEF_SHELL_STRUCT(CShell, const);
322 * error handling variables
324 static int errors = 0; /* number of errors reported */
325 static int aborting = 0; /* why is the make aborting? */
326 #define ABORT_ERROR 1 /* Because of an error */
327 #define ABORT_INTERRUPT 2 /* Because it was interrupted */
328 #define ABORT_WAIT 3 /* Waiting for jobs to finish */
331 * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
332 * is a char! So when we go above 127 we turn negative!
334 #define FILENO(a) ((unsigned)fileno(a))
337 * post-make command processing. The node postCommands is really just the
338 * .END target but we keep it around to avoid having to search for it
341 static GNode *postCommands;
344 * The number of commands actually printed for a target. Should this
345 * number be 0, no shell will be executed.
347 static int numCommands;
350 * Return values from JobStart.
352 #define JOB_RUNNING 0 /* Job is running */
353 #define JOB_ERROR 1 /* Error in starting the job */
354 #define JOB_FINISHED 2 /* The job is already finished */
355 #define JOB_STOPPED 3 /* The job is stopped */
358 * Descriptions for various shells.
360 static const struct CShell shells[] = {
362 * CSH description. The csh can do echo control by playing
363 * with the setting of the 'echo' shell variable. Sadly,
364 * however, it is unable to do error control nicely.
368 TRUE, "unset verbose", "set verbose", "unset verbose",
369 FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"",
373 * SH description. Echo control is also possible and, under
374 * sun UNIX anyway, one can even control error checking.
378 TRUE, "set -", "set -v", "set -",
379 TRUE, "set -e", "set +e",
380 #ifdef OLDBOURNESHELL
381 FALSE, "echo \"%s\"\n", "sh -c '%s || exit 0'\n",
386 * KSH description. The Korn shell has a superset of
387 * the Bourne shell's functionality.
391 TRUE, "set -", "set -v", "set -",
392 TRUE, "set -e", "set +e",
398 * This is the shell to which we pass all commands in the Makefile.
399 * It is set by the Job_ParseShell function.
401 static struct Shell *commandShell = NULL;
402 static char *shellPath = NULL; /* full pathname of executable image */
403 static char *shellName = NULL; /* last component of shell */
406 * The maximum number of jobs that may run. This is initialize from the
407 * -j argument for the leading make and from the FIFO for sub-makes.
411 static int nJobs; /* The number of children currently running */
413 /* The structures that describe them */
414 static struct JobList jobs = TAILQ_HEAD_INITIALIZER(jobs);
416 static Boolean jobFull; /* Flag to tell when the job table is full. It
417 * is set TRUE when (1) the total number of
418 * running jobs equals the maximum allowed */
420 static int kqfd; /* File descriptor obtained by kqueue() */
422 static fd_set outputs; /* Set of descriptors of pipes connected to
423 * the output channels of children */
426 static GNode *lastNode; /* The node for which output was most recently
428 static const char *targFmt; /* Format string to use to head output from a
429 * job when it's not the most-recent job heard
432 #define TARG_FMT "--- %s ---\n" /* Default format */
433 #define MESSAGE(fp, gn) \
434 fprintf(fp, targFmt, gn->name);
437 * When JobStart attempts to run a job but isn't allowed to
438 * or when Job_CatchChildren detects a job that has
439 * been stopped somehow, the job is placed on the stoppedJobs queue to be run
440 * when the next job finishes.
442 * Lst of Job structures describing jobs that were stopped due to
443 * concurrency limits or externally
445 static struct JobList stoppedJobs = TAILQ_HEAD_INITIALIZER(stoppedJobs);
447 static int fifoFd; /* Fd of our job fifo */
448 static char fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
449 static int fifoMaster;
451 static sig_atomic_t interrupted;
454 #if defined(USE_PGRP) && defined(SYSV)
455 # define KILL(pid, sig) killpg(-(pid), (sig))
457 # if defined(USE_PGRP)
458 # define KILL(pid, sig) killpg((pid), (sig))
460 # define KILL(pid, sig) kill((pid), (sig))
465 * Grmpf... There is no way to set bits of the wait structure
466 * anymore with the stupid W*() macros. I liked the union wait
467 * stuff much more. So, we devise our own macros... This is
468 * really ugly, use dramamine sparingly. You have been warned.
470 #define W_SETMASKED(st, val, fun) \
473 int mask = fun(sh); \
475 for (sh = 0; ((mask >> sh) & 1) == 0; sh++) \
477 *(st) = (*(st) & ~mask) | ((val) << sh); \
480 #define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
481 #define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
484 * Information used to create a new process.
486 typedef struct ProcStuff {
487 int in; /* stdin for new process */
488 int out; /* stdout for new process */
489 int err; /* stderr for new process */
491 int merge_errors; /* true if stderr is redirected to stdin */
492 int pgroup; /* true if new process a process leader */
493 int searchpath; /* true if binary should be found via $PATH */
496 int argv_free; /* release argv after use */
502 static void JobRestart(Job *);
503 static int JobStart(GNode *, int, Job *);
504 static void JobDoOutput(Job *, Boolean);
505 static struct Shell *JobMatchShell(const char *);
506 static void JobInterrupt(int, int);
507 static void JobRestartJobs(void);
508 static void ProcExec(const ProcStuff *) __dead2;
509 static int Compat_RunCommand(char *, struct GNode *);
511 static GNode *curTarg = NULL;
512 static GNode *ENDNode;
515 * Create a fifo file with a uniq filename, and returns a file
516 * descriptor to that fifo.
519 mkfifotemp(char *template)
524 const char padchar[] =
525 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
527 if (template[0] == '\0') {
528 errno = EINVAL; /* bad input string */
532 /* Find end of template string. */
533 pathend = strchr(template, '\0');
537 * Starting from the end of the template replace spaces with 'X' in
538 * them with random characters until there are no more 'X'.
540 while (ptr >= template && *ptr == 'X') {
541 uint32_t rand_num = arc4random() % (sizeof(padchar) - 1);
542 *ptr-- = padchar[rand_num];
546 /* Check the target directory. */
547 for (; ptr > template; --ptr) {
552 if (stat(template, &sbuf) != 0)
555 if (!S_ISDIR(sbuf.st_mode)) {
565 if (mkfifo(template, 0600) == 0) {
568 if ((fd = open(template, O_RDWR, 0600)) < 0) {
575 if (errno != EEXIST) {
581 * If we have a collision, cycle through the space of
584 for (ptr = start;;) {
587 if (*ptr == '\0' || ptr == pathend)
590 pad = strchr(padchar, *ptr);
591 if (pad == NULL || *++pad == '\0') {
603 catch_child(int sig __unused)
608 * In lieu of a good way to prevent every possible looping in make(1), stop
609 * there from being more than MKLVL_MAXVAL processes forked by make(1), to
610 * prevent a forkbomb from happening, in a dumb and mechanical way.
613 * Creates or modifies enviornment variable MKLVL_ENVVAR via setenv().
616 check_make_level(void)
618 char *value = getenv(MKLVL_ENVVAR);
619 int level = (value == NULL) ? 0 : atoi(value);
622 errc(2, EAGAIN, "Invalid value for recursion level (%d).",
624 } else if (level > MKLVL_MAXVAL) {
625 errc(2, EAGAIN, "Max recursion level (%d) exceeded.",
629 sprintf(new_value, "%d", level + 1);
630 setenv(MKLVL_ENVVAR, new_value, 1);
640 * Catch SIGCHLD so that we get kicked out of select() when we
641 * need to look at a child. This is only known to matter for the
642 * -j case (perhaps without -P).
644 * XXX this is intentionally misplaced.
648 sigemptyset(&sa.sa_mask);
649 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
650 sa.sa_handler = catch_child;
651 sigaction(SIGCHLD, &sa, NULL);
657 * get rid of resource limit on file descriptors
661 if (getrlimit(RLIMIT_NOFILE, &rl) == -1) {
664 rl.rlim_cur = rl.rlim_max;
665 if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
673 * Turn off ENV to make ksh happier.
680 * Replace the current process.
683 ProcExec(const ProcStuff *ps)
685 if (ps->in != STDIN_FILENO) {
687 * Redirect the child's stdin to the input fd
688 * and reset it to the beginning (again).
690 if (dup2(ps->in, STDIN_FILENO) == -1)
691 Punt("Cannot dup2: %s", strerror(errno));
692 lseek(STDIN_FILENO, (off_t)0, SEEK_SET);
695 if (ps->out != STDOUT_FILENO) {
697 * Redirect the child's stdout to the output fd.
699 if (dup2(ps->out, STDOUT_FILENO) == -1)
700 Punt("Cannot dup2: %s", strerror(errno));
704 if (ps->err != STDERR_FILENO) {
706 * Redirect the child's stderr to the err fd.
708 if (dup2(ps->err, STDERR_FILENO) == -1)
709 Punt("Cannot dup2: %s", strerror(errno));
713 if (ps->merge_errors) {
715 * Send stderr to parent process too.
717 if (dup2(STDOUT_FILENO, STDERR_FILENO) == -1)
718 Punt("Cannot dup2: %s", strerror(errno));
722 * The file descriptors for stdin, stdout, or stderr might
723 * have been marked close-on-exec. Clear the flag on all
726 fcntl(STDIN_FILENO, F_SETFD,
727 fcntl(STDIN_FILENO, F_GETFD) & (~FD_CLOEXEC));
728 fcntl(STDOUT_FILENO, F_SETFD,
729 fcntl(STDOUT_FILENO, F_GETFD) & (~FD_CLOEXEC));
730 fcntl(STDERR_FILENO, F_SETFD,
731 fcntl(STDERR_FILENO, F_GETFD) & (~FD_CLOEXEC));
736 * Become a process group leader, so we can kill it and all
737 * its descendants in one fell swoop, by killing its process
738 * family, but not commit suicide.
743 setpgid(0, getpid());
745 #endif /* USE_PGRP */
748 if (ps->searchpath) {
749 execvp(ps->argv[0], ps->argv);
751 write(STDERR_FILENO, ps->argv[0], strlen(ps->argv[0]));
752 write(STDERR_FILENO, ":", 1);
753 write(STDERR_FILENO, strerror(errno), strlen(strerror(errno)));
754 write(STDERR_FILENO, "\n", 1);
756 execv(shellPath, ps->argv);
759 "Could not execute shell\n",
760 sizeof("Could not execute shell"));
764 * Since we are the child process, exit without flushing buffers.
770 * Wait for child process to terminate.
773 ProcWait(ProcStuff *ps)
779 * Wait for the process to exit.
782 pid = waitpid(ps->child_pid, &status, 0);
783 if (pid == -1 && errno != EINTR) {
784 Fatal("error in wait: %d", pid);
787 if (pid == ps->child_pid) {
800 * Got a signal. Set global variables and hope that someone will
804 JobCatchSig(int signo)
812 * Pass a signal on to all local jobs if
813 * USE_PGRP is defined, then die ourselves.
816 * We die by the same signal.
819 JobPassSig(int signo)
822 sigset_t nmask, omask;
823 struct sigaction act;
826 sigaddset(&nmask, signo);
827 sigprocmask(SIG_SETMASK, &nmask, &omask);
829 DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
830 TAILQ_FOREACH(job, &jobs, link) {
831 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
832 signo, (intmax_t)job->pid));
833 KILL(job->pid, signo);
837 * Deal with proper cleanup based on the signal received. We only run
838 * the .INTERRUPT target if the signal was in fact an interrupt.
839 * The other three termination signals are more of a "get out *now*"
842 if (signo == SIGINT) {
843 JobInterrupt(TRUE, signo);
844 } else if (signo == SIGHUP || signo == SIGTERM || signo == SIGQUIT) {
845 JobInterrupt(FALSE, signo);
849 * Leave gracefully if SIGQUIT, rather than core dumping.
851 if (signo == SIGQUIT) {
856 * Send ourselves the signal now we've given the message to everyone
857 * else. Note we block everything else possible while we're getting
858 * the signal. This ensures that all our jobs get continued when we
859 * wake up before we take any other signal.
860 * XXX this comment seems wrong.
862 act.sa_handler = SIG_DFL;
863 sigemptyset(&act.sa_mask);
865 sigaction(signo, &act, NULL);
867 DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
868 ~0 & ~(1 << (signo - 1))));
869 signal(signo, SIG_DFL);
871 KILL(getpid(), signo);
874 TAILQ_FOREACH(job, &jobs, link) {
875 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
876 signo, (intmax_t)job->pid));
877 KILL(job->pid, signo);
880 sigprocmask(SIG_SETMASK, &omask, NULL);
881 sigprocmask(SIG_SETMASK, &omask, NULL);
882 act.sa_handler = JobPassSig;
883 sigaction(signo, &act, NULL);
888 * Put out another command for the given job. If the command starts
889 * with an @ or a - we process it specially. In the former case,
890 * so long as the -s and -n flags weren't given to make, we stick
891 * a shell-specific echoOff command in the script. In the latter,
892 * we ignore errors for the entire job, unless the shell has error
894 * If the command is just "..." we take all future commands for this
895 * job to be commands to be executed once the entire graph has been
896 * made and return non-zero to signal that the end of the commands
897 * was reached. These commands are later attached to the postCommands
898 * node and executed by Job_Finish when all things are done.
899 * This function is called from JobStart via LST_FOREACH.
902 * Always 0, unless the command was "..."
905 * If the command begins with a '-' and the shell has no error control,
906 * the JOB_IGNERR flag is set in the job descriptor.
907 * If the command is "..." and we're not ignoring such things,
908 * tailCmds is set to the successor node of the cmd.
909 * numCommands is incremented if the command is actually printed.
912 JobPrintCommand(char *cmd, Job *job)
914 Boolean noSpecials; /* true if we shouldn't worry about
915 * inserting special commands into
916 * the input stream. */
917 Boolean shutUp = FALSE; /* true if we put a no echo command
918 * into the command file */
919 Boolean errOff = FALSE; /* true if we turned error checking
920 * off before printing the command
921 * and need to turn it back on */
922 const char *cmdTemplate;/* Template to use when printing the command */
923 char *cmdStart; /* Start of expanded command */
924 LstNode *cmdNode; /* Node for replacing the command */
926 noSpecials = (noExecute && !(job->node->type & OP_MAKE));
928 if (strcmp(cmd, "...") == 0) {
929 job->node->type |= OP_SAVE_CMDS;
930 if ((job->flags & JOB_IGNDOTS) == 0) {
932 Lst_Succ(Lst_Member(&job->node->commands, cmd));
938 #define DBPRINTF(fmt, arg) \
939 DEBUGF(JOB, (fmt, arg)); \
940 fprintf(job->cmdFILE, fmt, arg); \
941 fflush(job->cmdFILE);
946 * For debugging, we replace each command with the result of expanding
947 * the variables in the command.
949 cmdNode = Lst_Member(&job->node->commands, cmd);
951 cmd = Buf_Peel(Var_Subst(cmd, job->node, FALSE));
954 Lst_Replace(cmdNode, cmdStart);
956 cmdTemplate = "%s\n";
959 * Check for leading @', -' or +'s to control echoing, error checking,
960 * and execution on -n.
962 while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
966 shutUp = DEBUG(LOUD) ? FALSE : TRUE;
976 * We're not actually exececuting anything...
977 * but this one needs to be - use compat mode
980 Compat_RunCommand(cmd, job->node);
988 while (isspace((unsigned char)*cmd))
992 if (!(job->flags & JOB_SILENT) && !noSpecials &&
993 commandShell->hasEchoCtl) {
994 DBPRINTF("%s\n", commandShell->echoOff);
1001 if (!(job->flags & JOB_IGNERR) && !noSpecials) {
1002 if (commandShell->hasErrCtl) {
1004 * We don't want the error-control commands
1005 * showing up either, so we turn off echoing
1006 * while executing them. We could put another
1007 * field in the shell structure to tell
1008 * JobDoOutput to look for this string too,
1009 * but why make it any more complex than
1012 if (!(job->flags & JOB_SILENT) && !shutUp &&
1013 commandShell->hasEchoCtl) {
1014 DBPRINTF("%s\n", commandShell->echoOff);
1015 DBPRINTF("%s\n", commandShell->ignErr);
1016 DBPRINTF("%s\n", commandShell->echoOn);
1018 DBPRINTF("%s\n", commandShell->ignErr);
1020 } else if (commandShell->ignErr &&
1021 *commandShell->ignErr != '\0') {
1023 * The shell has no error control, so we need to
1024 * be weird to get it to ignore any errors from
1025 * the command. If echoing is turned on, we turn
1026 * it off and use the errCheck template to echo
1027 * the command. Leave echoing off so the user
1028 * doesn't see the weirdness we go through to
1029 * ignore errors. Set cmdTemplate to use the
1030 * weirdness instead of the simple "%s\n"
1033 if (!(job->flags & JOB_SILENT) && !shutUp &&
1034 commandShell->hasEchoCtl) {
1035 DBPRINTF("%s\n", commandShell->echoOff);
1036 DBPRINTF(commandShell->errCheck, cmd);
1039 cmdTemplate = commandShell->ignErr;
1041 * The error ignoration (hee hee) is already
1042 * taken care of by the ignErr template, so
1043 * pretend error checking is still on.
1054 DBPRINTF(cmdTemplate, cmd);
1058 * If echoing is already off, there's no point in issuing the
1059 * echoOff command. Otherwise we issue it and pretend it was on
1060 * for the whole command...
1062 if (!shutUp && !(job->flags & JOB_SILENT) &&
1063 commandShell->hasEchoCtl) {
1064 DBPRINTF("%s\n", commandShell->echoOff);
1067 DBPRINTF("%s\n", commandShell->errCheck);
1070 DBPRINTF("%s\n", commandShell->echoOn);
1077 * Called to close both input and output pipes when a job is finished.
1080 * The file descriptors associated with the job are closed.
1087 #if !defined(USE_KQUEUE)
1088 FD_CLR(job->inPipe, &outputs);
1090 if (job->outPipe != job->inPipe) {
1091 close(job->outPipe);
1093 JobDoOutput(job, TRUE);
1097 JobDoOutput(job, TRUE);
1103 * Do final processing for the given job including updating
1104 * parents and starting new jobs as available/necessary. Note
1105 * that we pay no attention to the JOB_IGNERR flag here.
1106 * This is because when we're called because of a noexecute flag
1107 * or something, jstat.w_status is 0 and when called from
1108 * Job_CatchChildren, the status is zeroed if it s/b ignored.
1111 * Some nodes may be put on the toBeMade queue.
1112 * Final commands for the job are placed on postCommands.
1114 * If we got an error and are aborting (aborting == ABORT_ERROR) and
1115 * the job list is now empty, we are done for the day.
1116 * If we recognized an error (errors !=0), we set the aborting flag
1117 * to ABORT_ERROR so no more jobs will be started.
1120 JobFinish(Job *job, int *status)
1125 if (WIFEXITED(*status)) {
1126 int job_status = WEXITSTATUS(*status);
1130 * Deal with ignored errors in -B mode. We need to
1131 * print a message telling of the ignored error as
1132 * well as setting status.w_status to 0 so the next
1133 * command gets run. To do this, we set done to be
1134 * TRUE if in -B mode and the job exited non-zero.
1136 if (job_status == 0) {
1139 if (job->flags & JOB_IGNERR) {
1143 * If it exited non-zero and either we're
1144 * doing things our way or we're not ignoring
1145 * errors, the job is finished. Similarly, if
1146 * the shell died because of a signal the job
1147 * is also finished. In these cases, finish
1148 * out the job's output before printing the
1152 if (job->cmdFILE != NULL &&
1153 job->cmdFILE != stdout) {
1154 fclose(job->cmdFILE);
1159 } else if (WIFSIGNALED(*status)) {
1160 if (WTERMSIG(*status) == SIGCONT) {
1162 * No need to close things down or anything.
1167 * If it exited non-zero and either we're
1168 * doing things our way or we're not ignoring
1169 * errors, the job is finished. Similarly, if
1170 * the shell died because of a signal the job
1171 * is also finished. In these cases, finish
1172 * out the job's output before printing the
1176 if (job->cmdFILE != NULL &&
1177 job->cmdFILE != stdout) {
1178 fclose(job->cmdFILE);
1184 * No need to close things down or anything.
1189 if (WIFEXITED(*status)) {
1190 if (done || DEBUG(JOB)) {
1195 (job->flags & JOB_IGNERR)) {
1197 * If output is going to a file and this job
1198 * is ignoring errors, arrange to have the
1199 * exit status sent to the output file as
1202 out = fdopen(job->outFd, "w");
1204 Punt("Cannot fdopen");
1209 DEBUGF(JOB, ("Process %jd exited.\n",
1210 (intmax_t)job->pid));
1212 if (WEXITSTATUS(*status) == 0) {
1214 if (usePipes && job->node != lastNode) {
1215 MESSAGE(out, job->node);
1216 lastNode = job->node;
1219 "*** Completed successfully\n");
1222 if (usePipes && job->node != lastNode) {
1223 MESSAGE(out, job->node);
1224 lastNode = job->node;
1226 fprintf(out, "*** Error code %d%s\n",
1227 WEXITSTATUS(*status),
1228 (job->flags & JOB_IGNERR) ?
1231 if (job->flags & JOB_IGNERR) {
1238 } else if (WIFSIGNALED(*status)) {
1239 if (done || DEBUG(JOB) || (WTERMSIG(*status) == SIGCONT)) {
1244 (job->flags & JOB_IGNERR)) {
1246 * If output is going to a file and this job
1247 * is ignoring errors, arrange to have the
1248 * exit status sent to the output file as
1251 out = fdopen(job->outFd, "w");
1253 Punt("Cannot fdopen");
1258 if (WTERMSIG(*status) == SIGCONT) {
1260 * If the beastie has continued, shift the
1261 * Job from the stopped list to the running
1262 * one (or re-stop it if concurrency is
1263 * exceeded) and go and get another child.
1265 if (job->flags & (JOB_RESUME | JOB_RESTART)) {
1266 if (usePipes && job->node != lastNode) {
1267 MESSAGE(out, job->node);
1268 lastNode = job->node;
1270 fprintf(out, "*** Continued\n");
1272 if (!(job->flags & JOB_CONTINUING)) {
1273 DEBUGF(JOB, ("Warning: process %jd was not "
1274 "continuing.\n", (intmax_t) job->pid));
1277 * We don't really want to restart a
1278 * job from scratch just because it
1279 * continued, especially not without
1280 * killing the continuing process!
1281 * That's why this is ifdef'ed out.
1287 job->flags &= ~JOB_CONTINUING;
1288 TAILQ_INSERT_TAIL(&jobs, job, link);
1290 DEBUGF(JOB, ("Process %jd is continuing locally.\n",
1291 (intmax_t) job->pid));
1292 if (nJobs == maxJobs) {
1294 DEBUGF(JOB, ("Job queue is full.\n"));
1300 if (usePipes && job->node != lastNode) {
1301 MESSAGE(out, job->node);
1302 lastNode = job->node;
1305 "*** Signal %d\n", WTERMSIG(*status));
1313 if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
1315 * If output is going to a file and this job
1316 * is ignoring errors, arrange to have the
1317 * exit status sent to the output file as
1320 out = fdopen(job->outFd, "w");
1322 Punt("Cannot fdopen");
1327 DEBUGF(JOB, ("Process %jd stopped.\n", (intmax_t) job->pid));
1328 if (usePipes && job->node != lastNode) {
1329 MESSAGE(out, job->node);
1330 lastNode = job->node;
1332 fprintf(out, "*** Stopped -- signal %d\n", WSTOPSIG(*status));
1333 job->flags |= JOB_RESUME;
1334 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1340 * Now handle the -B-mode stuff. If the beast still isn't finished,
1341 * try and restart the job on the next command. If JobStart says it's
1342 * ok, it's ok. If there's an error, this puppy is done.
1344 if (compatMake && WIFEXITED(*status) &&
1345 Lst_Succ(job->node->compat_command) != NULL) {
1346 switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
1352 W_SETEXITSTATUS(status, 1);
1356 * If we got back a JOB_FINISHED code, JobStart has
1357 * already called Make_Update and freed the job
1358 * descriptor. We set done to false here to avoid fake
1359 * cycles and double frees. JobStart needs to do the
1360 * update so we can proceed up the graph when given
1372 if (done && aborting != ABORT_ERROR &&
1373 aborting != ABORT_INTERRUPT && *status == 0) {
1375 * As long as we aren't aborting and the job didn't return a
1376 * non-zero status that we shouldn't ignore, we call
1377 * Make_Update to update the parents. In addition, any saved
1378 * commands for the node are placed on the .END target.
1380 for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
1381 Lst_AtEnd(&postCommands->commands,
1383 Var_Subst(Lst_Datum(ln), job->node, FALSE)));
1386 job->node->made = MADE;
1387 Make_Update(job->node);
1390 } else if (*status != 0) {
1398 * Set aborting if any error.
1400 if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
1402 * If we found any errors in this batch of children and the -k
1403 * flag wasn't given, we set the aborting flag so no more jobs
1406 aborting = ABORT_ERROR;
1409 if (aborting == ABORT_ERROR && Job_Empty()) {
1411 * If we are aborting and the job table is now empty, we finish.
1419 * Touch the given target. Called by JobStart when the -t flag was
1420 * given. Prints messages unless told to be silent.
1423 * The data modification of the file is changed. In addition, if the
1424 * file did not exist, it is created.
1427 Job_Touch(GNode *gn, Boolean silent)
1429 int streamID; /* ID of stream opened to do the touch */
1430 struct utimbuf times; /* Times for utime() call */
1432 if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
1434 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
1435 * targets and, as such, shouldn't really be created.
1441 fprintf(stdout, "touch %s\n", gn->name);
1449 if (gn->type & OP_ARCHV) {
1451 } else if (gn->type & OP_LIB) {
1454 char *file = gn->path ? gn->path : gn->name;
1456 times.actime = times.modtime = now;
1457 if (utime(file, ×) < 0) {
1458 streamID = open(file, O_RDWR | O_CREAT, 0666);
1460 if (streamID >= 0) {
1464 * Read and write a byte to the file to change
1465 * the modification time, then close the file.
1467 if (read(streamID, &c, 1) == 1) {
1468 lseek(streamID, (off_t)0, SEEK_SET);
1469 write(streamID, &c, 1);
1474 fprintf(stdout, "*** couldn't touch %s: %s",
1475 file, strerror(errno));
1484 * Make sure the given node has all the commands it needs.
1487 * TRUE if the commands list is/was ok.
1490 * The node will have commands from the .DEFAULT rule added to it
1494 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1497 if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
1498 (gn->type & OP_LIB) == 0) {
1500 * No commands. Look for .DEFAULT rule from which we might infer
1503 if (DEFAULT != NULL && !Lst_IsEmpty(&DEFAULT->commands)) {
1505 * Make only looks for a .DEFAULT if the node was
1506 * never the target of an operator, so that's what we
1507 * do too. If a .DEFAULT was given, we substitute its
1508 * commands for gn's commands and set the IMPSRC
1509 * variable to be the target's name The DEFAULT node
1510 * acts like a transformation rule, in that gn also
1511 * inherits any attributes or sources attached to
1514 Make_HandleUse(DEFAULT, gn);
1515 Var_Set(IMPSRC, Var_Value(TARGET, gn), gn);
1517 } else if (Dir_MTime(gn) == 0) {
1519 * The node wasn't the target of an operator we have
1520 * no .DEFAULT rule to go on and the target doesn't
1521 * already exist. There's nothing more we can do for
1522 * this branch. If the -k flag wasn't given, we stop
1523 * in our tracks, otherwise we just don't update
1524 * this node's parents so they never get examined.
1526 static const char msg[] =
1527 "make: don't know how to make";
1529 if (gn->type & OP_OPTIONAL) {
1530 fprintf(stdout, "%s %s(ignored)\n",
1533 } else if (keepgoing) {
1534 fprintf(stdout, "%s %s(continuing)\n",
1540 if (strcmp(gn->name,"love") == 0)
1541 (*abortProc)("Not war.");
1544 (*abortProc)("%s %s. Stop",
1555 * Execute the shell for the given job. Called from JobStart and
1559 * A shell is executed, outputs is altered and the Job structure added
1563 JobExec(Job *job, char **argv)
1570 DEBUGF(JOB, ("Running %s\n", job->node->name));
1571 DEBUGF(JOB, ("\tCommand: "));
1572 for (i = 0; argv[i] != NULL; i++) {
1573 DEBUGF(JOB, ("%s ", argv[i]));
1575 DEBUGF(JOB, ("\n"));
1579 * Some jobs produce no output and it's disconcerting to have
1580 * no feedback of their running (since they produce no output, the
1581 * banner with their name in it never appears). This is an attempt to
1582 * provide that feedback, even if nothing follows it.
1584 if (lastNode != job->node && (job->flags & JOB_FIRST) &&
1585 !(job->flags & JOB_SILENT)) {
1586 MESSAGE(stdout, job->node);
1587 lastNode = job->node;
1590 ps.in = FILENO(job->cmdFILE);
1593 * Set up the child's output to be routed through the
1594 * pipe we've created for it.
1596 ps.out = job->outPipe;
1599 * We're capturing output in a file, so we duplicate
1600 * the descriptor to the temporary file into the
1603 ps.out = job->outFd;
1605 ps.err = STDERR_FILENO;
1607 ps.merge_errors = 1;
1615 * Fork. Warning since we are doing vfork() instead of fork(),
1616 * do not allocate memory in the child process!
1618 if ((ps.child_pid = vfork()) == -1) {
1619 Punt("Cannot fork");
1621 } else if (ps.child_pid == 0) {
1635 job->pid = ps.child_pid;
1637 if (usePipes && (job->flags & JOB_FIRST)) {
1639 * The first time a job is run for a node, we set the
1640 * current position in the buffer to the beginning and
1641 * mark another stream to watch in the outputs mask.
1644 struct kevent kev[2];
1648 #if defined(USE_KQUEUE)
1649 EV_SET(&kev[0], job->inPipe, EVFILT_READ, EV_ADD, 0, 0, job);
1650 EV_SET(&kev[1], job->pid, EVFILT_PROC,
1651 EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
1652 if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1654 * kevent() will fail if the job is already
1657 if (errno != EINTR && errno != EBADF && errno != ESRCH)
1658 Punt("kevent: %s", strerror(errno));
1661 FD_SET(job->inPipe, &outputs);
1662 #endif /* USE_KQUEUE */
1665 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1666 fclose(job->cmdFILE);
1667 job->cmdFILE = NULL;
1671 * Now the job is actually running, add it to the table.
1674 TAILQ_INSERT_TAIL(&jobs, job, link);
1675 if (nJobs == maxJobs) {
1683 * Create the argv needed to execute the shell for a given job.
1686 JobMakeArgv(Job *job, char **argv)
1689 static char args[10]; /* For merged arguments */
1691 argv[0] = shellName;
1694 if ((commandShell->exit && *commandShell->exit != '-') ||
1695 (commandShell->echo && *commandShell->echo != '-')) {
1697 * At least one of the flags doesn't have a minus before it, so
1698 * merge them together. Have to do this because the *(&(@*#*&#$#
1699 * Bourne shell thinks its second argument is a file to source.
1700 * Grrrr. Note the ten-character limitation on the combined
1703 sprintf(args, "-%s%s", (job->flags & JOB_IGNERR) ? "" :
1704 commandShell->exit ? commandShell->exit : "",
1705 (job->flags & JOB_SILENT) ? "" :
1706 commandShell->echo ? commandShell->echo : "");
1713 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1714 argv[argc] = commandShell->exit;
1717 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1718 argv[argc] = commandShell->echo;
1727 * Restart a job that stopped for some reason. The job must be neither
1728 * on the jobs nor on the stoppedJobs list.
1731 * jobFull will be set if the job couldn't be run.
1734 JobRestart(Job *job)
1737 if (job->flags & JOB_RESTART) {
1739 * Set up the control arguments to the shell. This is based on
1740 * the flags set earlier for this job. If the JOB_IGNERR flag
1741 * is clear, the 'exit' flag of the commandShell is used to
1742 * cause it to exit upon receiving an error. If the JOB_SILENT
1743 * flag is clear, the 'echo' flag of the commandShell is used
1744 * to get it to start echoing as soon as it starts
1745 * processing commands.
1749 JobMakeArgv(job, argv);
1751 DEBUGF(JOB, ("Restarting %s...", job->node->name));
1752 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL)) {
1754 * Not allowed to run -- put it back on the hold
1755 * queue and mark the table full
1757 DEBUGF(JOB, ("holding\n"));
1758 TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1760 DEBUGF(JOB, ("Job queue is full.\n"));
1764 * Job may be run locally.
1766 DEBUGF(JOB, ("running locally\n"));
1772 * The job has stopped and needs to be restarted.
1773 * Why it stopped, we don't know...
1775 DEBUGF(JOB, ("Resuming %s...", job->node->name));
1776 if ((nJobs < maxJobs || ((job->flags & JOB_SPECIAL) &&
1777 maxJobs == 0)) && nJobs != maxJobs) {
1779 * If we haven't reached the concurrency limit already
1780 * (or the job must be run and maxJobs is 0), it's ok
1786 error = (KILL(job->pid, SIGCONT) != 0);
1790 * Make sure the user knows we've continued
1791 * the beast and actually put the thing in the
1794 job->flags |= JOB_CONTINUING;
1796 W_SETTERMSIG(&status, SIGCONT);
1797 JobFinish(job, &status);
1799 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1800 DEBUGF(JOB, ("done\n"));
1802 Error("couldn't resume %s: %s",
1803 job->node->name, strerror(errno));
1805 W_SETEXITSTATUS(&status, 1);
1806 JobFinish(job, &status);
1810 * Job cannot be restarted. Mark the table as full and
1811 * place the job back on the list of stopped jobs.
1813 DEBUGF(JOB, ("table full\n"));
1814 TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1816 DEBUGF(JOB, ("Job queue is full.\n"));
1823 * Start a target-creation process going for the target described
1824 * by the graph node gn.
1827 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1828 * if there isn't actually anything left to do for the job and
1829 * JOB_RUNNING if the job has been started.
1832 * A new Job node is created and added to the list of running
1833 * jobs. PMake is forked and a child shell created.
1836 JobStart(GNode *gn, int flags, Job *previous)
1838 Job *job; /* new job descriptor */
1839 char *argv[4]; /* Argument vector to shell */
1840 Boolean cmdsOK; /* true if the nodes commands were all right */
1841 Boolean noExec; /* Set true if we decide not to run the job */
1842 int tfd; /* File descriptor for temp file */
1844 char tfile[sizeof(TMPPAT)];
1847 JobPassSig(interrupted);
1850 if (previous != NULL) {
1851 previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1854 job = emalloc(sizeof(Job));
1859 job->tailCmds = NULL;
1862 * Set the initial value of the flags for this job based on the global
1863 * ones and the node's attributes... Any flags supplied by the caller
1864 * are also added to the field.
1867 if (Targ_Ignore(gn)) {
1868 job->flags |= JOB_IGNERR;
1870 if (Targ_Silent(gn)) {
1871 job->flags |= JOB_SILENT;
1873 job->flags |= flags;
1876 * Check the commands now so any attributes from .DEFAULT have a chance
1877 * to migrate to the node.
1879 if (!compatMake && (job->flags & JOB_FIRST)) {
1880 cmdsOK = Job_CheckCommands(gn, Error);
1886 * If the -n flag wasn't given, we open up OUR (not the child's)
1887 * temporary file to stuff commands in it. The thing is rd/wr so we
1888 * don't need to reopen it to feed it to the shell. If the -n flag
1889 * *was* given, we just set the file to be stdout. Cute, huh?
1891 if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1893 * We're serious here, but if the commands were bogus, we're
1900 strcpy(tfile, TMPPAT);
1901 if ((tfd = mkstemp(tfile)) == -1)
1902 Punt("Cannot create temp file: %s", strerror(errno));
1903 job->cmdFILE = fdopen(tfd, "w+");
1905 if (job->cmdFILE == NULL) {
1907 Punt("Could not open %s", tfile);
1909 fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1911 * Send the commands to the command file, flush all its
1912 * buffers then rewind and remove the thing.
1917 * Used to be backwards; replace when start doing multiple
1918 * commands per shell.
1922 * Be compatible: If this is the first time for this
1923 * node, verify its commands are ok and open the
1924 * commands list for sequential access by later
1925 * invocations of JobStart. Once that is done, we take
1926 * the next command off the list and print it to the
1927 * command file. If the command was an ellipsis, note
1928 * that there's nothing more to execute.
1930 if (job->flags & JOB_FIRST)
1931 gn->compat_command = Lst_First(&gn->commands);
1933 gn->compat_command =
1934 Lst_Succ(gn->compat_command);
1936 if (gn->compat_command == NULL ||
1937 JobPrintCommand(Lst_Datum(gn->compat_command), job))
1940 if (noExec && !(job->flags & JOB_FIRST)) {
1942 * If we're not going to execute anything, the
1943 * job is done and we need to close down the
1944 * various file descriptors we've opened for
1945 * output, then call JobDoOutput to catch the
1946 * final characters or send the file to the
1947 * screen... Note that the i/o streams are only
1948 * open if this isn't the first job. Note also
1949 * that this could not be done in
1950 * Job_CatchChildren b/c it wasn't clear if
1951 * there were more commands to execute or not...
1957 * We can do all the commands at once. hooray for sanity
1960 LST_FOREACH(ln, &gn->commands) {
1961 if (JobPrintCommand(Lst_Datum(ln), job))
1966 * If we didn't print out any commands to the shell
1967 * script, there's not much point in executing the
1970 if (numCommands == 0) {
1975 } else if (noExecute) {
1977 * Not executing anything -- just print all the commands to
1978 * stdout in one fell swoop. This will still set up
1979 * job->tailCmds correctly.
1981 if (lastNode != gn) {
1982 MESSAGE(stdout, gn);
1985 job->cmdFILE = stdout;
1988 * Only print the commands if they're ok, but don't die if
1989 * they're not -- just let the user know they're bad and keep
1990 * going. It doesn't do any harm in this case and may do
1994 LST_FOREACH(ln, &gn->commands) {
1995 if (JobPrintCommand(Lst_Datum(ln), job))
2000 * Don't execute the shell, thank you.
2006 * Just touch the target and note that no shell should be
2007 * executed. Set cmdFILE to stdout to make life easier. Check
2008 * the commands, too, but don't die if they're no good -- it
2009 * does no harm to keep working up the graph.
2011 job->cmdFILE = stdout;
2012 Job_Touch(gn, job->flags & JOB_SILENT);
2017 * If we're not supposed to execute a shell, don't.
2021 * Unlink and close the command file if we opened one
2023 if (job->cmdFILE != stdout) {
2024 if (job->cmdFILE != NULL)
2025 fclose(job->cmdFILE);
2031 * We only want to work our way up the graph if we aren't here
2032 * because the commands for the job were no good.
2035 if (aborting == 0) {
2036 for (ln = job->tailCmds; ln != NULL;
2037 ln = LST_NEXT(ln)) {
2038 Lst_AtEnd(&postCommands->commands,
2039 Buf_Peel(Var_Subst(Lst_Datum(ln),
2040 job->node, FALSE)));
2042 job->node->made = MADE;
2043 Make_Update(job->node);
2046 return(JOB_FINISHED);
2052 fflush(job->cmdFILE);
2056 * Set up the control arguments to the shell. This is based on the flags
2057 * set earlier for this job.
2059 JobMakeArgv(job, argv);
2062 * If we're using pipes to catch output, create the pipe by which we'll
2063 * get the shell's output. If we're using files, print out that we're
2064 * starting a job and then set up its temporary-file name.
2066 if (!compatMake || (job->flags & JOB_FIRST)) {
2071 Punt("Cannot create pipe: %s", strerror(errno));
2072 job->inPipe = fd[0];
2073 job->outPipe = fd[1];
2074 fcntl(job->inPipe, F_SETFD, 1);
2075 fcntl(job->outPipe, F_SETFD, 1);
2077 fprintf(stdout, "Remaking `%s'\n", gn->name);
2079 strcpy(job->outFile, TMPPAT);
2080 if ((job->outFd = mkstemp(job->outFile)) == -1)
2081 Punt("cannot create temp file: %s",
2083 fcntl(job->outFd, F_SETFD, 1);
2087 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL) && maxJobs != 0) {
2089 * We've hit the limit of concurrency, so put the job on hold
2090 * until some other job finishes. Note that the special jobs
2091 * (.BEGIN, .INTERRUPT and .END) may be run even when the
2092 * limit has been reached (e.g. when maxJobs == 0).
2096 DEBUGF(JOB, ("Can only run job locally.\n"));
2097 job->flags |= JOB_RESTART;
2098 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
2100 if (nJobs >= maxJobs) {
2102 * If we're running this job as a special case
2103 * (see above), at least say the table is full.
2106 DEBUGF(JOB, ("Local job queue is full.\n"));
2110 return (JOB_RUNNING);
2114 JobOutput(Job *job, char *cp, char *endp, int msg)
2118 if (commandShell->noPrint) {
2119 ecp = strstr(cp, commandShell->noPrint);
2120 while (ecp != NULL) {
2123 if (msg && job->node != lastNode) {
2124 MESSAGE(stdout, job->node);
2125 lastNode = job->node;
2128 * The only way there wouldn't be a newline
2129 * after this line is if it were the last in
2130 * the buffer. However, since the non-printable
2131 * comes after it, there must be a newline, so
2132 * we don't print one.
2134 fprintf(stdout, "%s", cp);
2137 cp = ecp + strlen(commandShell->noPrint);
2140 * Still more to print, look again after
2141 * skipping the whitespace following the
2142 * non-printable command....
2145 while (*cp == ' ' || *cp == '\t' ||
2149 ecp = strstr(cp, commandShell->noPrint);
2160 * This function is called at different times depending on
2161 * whether the user has specified that output is to be collected
2162 * via pipes or temporary files. In the former case, we are called
2163 * whenever there is something to read on the pipe. We collect more
2164 * output from the given job and store it in the job's outBuf. If
2165 * this makes up a line, we print it tagged by the job's identifier,
2167 * If output has been collected in a temporary file, we open the
2168 * file and read it line by line, transfering it to our own
2169 * output channel until the file is empty. At which point we
2170 * remove the temporary file.
2171 * In both cases, however, we keep our figurative eye out for the
2172 * 'noPrint' line for the shell from which the output came. If
2173 * we recognize a line, we don't print it. If the command is not
2174 * alone on the line (the character after it is not \0 or \n), we
2175 * do print whatever follows it.
2178 * curPos may be shifted as may the contents of outBuf.
2181 JobDoOutput(Job *job, Boolean finish)
2183 Boolean gotNL = FALSE; /* true if got a newline */
2184 Boolean fbuf; /* true if our buffer filled up */
2185 int nr; /* number of bytes read */
2186 int i; /* auxiliary index into outBuf */
2187 int max; /* limit for i (end of current data) */
2188 int nRead; /* (Temporary) number of bytes read */
2189 FILE *oFILE; /* Stream pointer to shell's output file */
2194 * Read as many bytes as will fit in the buffer.
2200 nRead = read(job->inPipe, &job->outBuf[job->curPos],
2201 JOB_BUFSIZE - job->curPos);
2203 * Check for interrupt here too, because the above read may
2204 * block when the child process is stopped. In this case the
2205 * interrupt will unblock it (we don't use SA_RESTART).
2208 JobPassSig(interrupted);
2211 DEBUGF(JOB, ("JobDoOutput(piperead)"));
2218 * If we hit the end-of-file (the job is dead), we must flush
2219 * its remaining output, so pretend we read a newline if
2220 * there's any output remaining in the buffer.
2221 * Also clear the 'finish' flag so we stop looping.
2223 if (nr == 0 && job->curPos != 0) {
2224 job->outBuf[job->curPos] = '\n';
2227 } else if (nr == 0) {
2232 * Look for the last newline in the bytes we just got. If there
2233 * is one, break out of the loop with 'i' as its index and
2236 max = job->curPos + nr;
2237 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
2238 if (job->outBuf[i] == '\n') {
2241 } else if (job->outBuf[i] == '\0') {
2245 job->outBuf[i] = ' ';
2251 if (job->curPos == JOB_BUFSIZE) {
2253 * If we've run out of buffer space, we have
2254 * no choice but to print the stuff. sigh.
2260 if (gotNL || fbuf) {
2262 * Need to send the output to the screen. Null terminate
2263 * it first, overwriting the newline character if there
2264 * was one. So long as the line isn't one we should
2265 * filter (according to the shell description), we print
2266 * the line, preceded by a target banner if this target
2267 * isn't the same as the one for which we last printed
2268 * something. The rest of the data in the buffer are
2269 * then shifted down to the start of the buffer and
2270 * curPos is set accordingly.
2272 job->outBuf[i] = '\0';
2273 if (i >= job->curPos) {
2276 cp = JobOutput(job, job->outBuf,
2277 &job->outBuf[i], FALSE);
2280 * There's still more in that buffer. This time,
2281 * though, we know there's no newline at the
2282 * end, so we add one of our own free will.
2285 if (job->node != lastNode) {
2286 MESSAGE(stdout, job->node);
2287 lastNode = job->node;
2289 fprintf(stdout, "%s%s", cp,
2295 /* shift the remaining characters down */
2296 memcpy(job->outBuf, &job->outBuf[i + 1],
2298 job->curPos = max - (i + 1);
2302 * We have written everything out, so we just
2303 * start over from the start of the buffer.
2304 * No copying. No nothing.
2311 * If the finish flag is true, we must loop until we hit
2312 * end-of-file on the pipe. This is guaranteed to happen
2313 * eventually since the other end of the pipe is now
2314 * closed (we closed it explicitly and the child has
2315 * exited). When we do get an EOF, finish will be set
2316 * FALSE and we'll fall through and out.
2323 * We've been called to retrieve the output of the job from the
2324 * temporary file where it's been squirreled away. This consists
2325 * of opening the file, reading the output line by line, being
2326 * sure not to print the noPrint line for the shell we used,
2327 * then close and remove the temporary file. Very simple.
2329 * Change to read in blocks and do FindSubString type things
2330 * as for pipes? That would allow for "@echo -n..."
2332 oFILE = fopen(job->outFile, "r");
2333 if (oFILE != NULL) {
2334 fprintf(stdout, "Results of making %s:\n",
2338 while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2339 char *cp, *endp, *oendp;
2342 oendp = endp = inLine + strlen(inLine);
2343 if (endp[-1] == '\n') {
2346 cp = JobOutput(job, inLine, endp, FALSE);
2349 * There's still more in that buffer. This time,
2350 * though, we know there's no newline at the
2351 * end, so we add one of our own free will.
2353 fprintf(stdout, "%s", cp);
2355 if (endp != oendp) {
2356 fprintf(stdout, "\n");
2361 eunlink(job->outFile);
2368 * Handle the exit of a child. Called from Make_Make.
2371 * The job descriptor is removed from the list of children.
2374 * We do waits, blocking or not, according to the wisdom of our
2375 * caller, until there are no more children to report. For each
2376 * job, call JobFinish to finish things off. This will take care of
2377 * putting jobs on the stoppedJobs queue.
2380 Job_CatchChildren(Boolean block)
2382 pid_t pid; /* pid of dead child */
2383 Job *job; /* job descriptor for dead child */
2384 int status; /* Exit/termination status */
2387 * Don't even bother if we know there's no one around.
2394 pid = waitpid((pid_t)-1, &status,
2395 (block ? 0 : WNOHANG) | WUNTRACED);
2399 DEBUGF(JOB, ("Process %jd exited or stopped.\n",
2402 TAILQ_FOREACH(job, &jobs, link) {
2403 if (job->pid == pid)
2408 if (WIFSIGNALED(status) &&
2409 (WTERMSIG(status) == SIGCONT)) {
2410 TAILQ_FOREACH(job, &jobs, link) {
2411 if (job->pid == pid)
2415 Error("Resumed child (%jd) "
2416 "not in table", (intmax_t)pid);
2419 TAILQ_REMOVE(&stoppedJobs, job, link);
2421 Error("Child (%jd) not in table?",
2426 TAILQ_REMOVE(&jobs, job, link);
2428 if (fifoFd >= 0 && maxJobs > 1) {
2429 write(fifoFd, "+", 1);
2431 if (nJobs >= maxJobs)
2436 DEBUGF(JOB, ("Job queue is no longer full.\n"));
2441 JobFinish(job, &status);
2444 JobPassSig(interrupted);
2449 * Catch the output from our children, if we're using
2450 * pipes do so. Otherwise just block time until we get a
2451 * signal(most likely a SIGCHLD) since there's no point in
2452 * just spinning when there's nothing to do and the reaping
2453 * of a child can wait for a while.
2456 * Output is read from pipes if we're piping.
2457 * -----------------------------------------------------------------------
2461 Job_CatchOutput(int flag __unused)
2463 Job_CatchOutput(int flag)
2469 struct kevent kev[KEV_SIZE];
2472 struct timeval timeout;
2481 if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
2483 Punt("kevent: %s", strerror(errno));
2485 JobPassSig(interrupted);
2487 for (i = 0; i < nfds; i++) {
2488 if (kev[i].flags & EV_ERROR) {
2489 warnc(kev[i].data, "kevent");
2492 switch (kev[i].filter) {
2494 JobDoOutput(kev[i].udata, FALSE);
2498 * Just wake up and let
2499 * Job_CatchChildren() collect the
2508 timeout.tv_sec = SEL_SEC;
2509 timeout.tv_usec = SEL_USEC;
2510 if (flag && jobFull && fifoFd >= 0)
2511 FD_SET(fifoFd, &readfds);
2513 nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
2514 (fd_set *)NULL, &timeout);
2517 JobPassSig(interrupted);
2520 if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2524 job = TAILQ_FIRST(&jobs);
2525 while (nfds != 0 && job != NULL) {
2526 if (FD_ISSET(job->inPipe, &readfds)) {
2527 JobDoOutput(job, FALSE);
2530 job = TAILQ_NEXT(job, link);
2532 #endif /* !USE_KQUEUE */
2538 * Start the creation of a target. Basically a front-end for
2539 * JobStart used by the Make module.
2542 * Another job is started.
2548 JobStart(gn, 0, NULL);
2553 * Make a new copy of the shell structure including a copy of the strings
2554 * in it. This also defaults some fields in case they are NULL.
2557 * The function returns a pointer to the new shell structure.
2559 static struct Shell *
2560 JobCopyShell(const struct Shell *osh)
2564 nsh = emalloc(sizeof(*nsh));
2565 nsh->name = estrdup(osh->name);
2567 if (osh->echoOff != NULL)
2568 nsh->echoOff = estrdup(osh->echoOff);
2570 nsh->echoOff = NULL;
2571 if (osh->echoOn != NULL)
2572 nsh->echoOn = estrdup(osh->echoOn);
2575 nsh->hasEchoCtl = osh->hasEchoCtl;
2577 if (osh->noPrint != NULL)
2578 nsh->noPrint = estrdup(osh->noPrint);
2580 nsh->noPrint = NULL;
2582 nsh->hasErrCtl = osh->hasErrCtl;
2583 if (osh->errCheck == NULL)
2584 nsh->errCheck = estrdup("");
2586 nsh->errCheck = estrdup(osh->errCheck);
2587 if (osh->ignErr == NULL)
2588 nsh->ignErr = estrdup("%s");
2590 nsh->ignErr = estrdup(osh->ignErr);
2592 if (osh->echo == NULL)
2593 nsh->echo = estrdup("");
2595 nsh->echo = estrdup(osh->echo);
2597 if (osh->exit == NULL)
2598 nsh->exit = estrdup("");
2600 nsh->exit = estrdup(osh->exit);
2607 * Free a shell structure and all associated strings.
2610 JobFreeShell(struct Shell *sh)
2630 if (commandShell == NULL)
2631 commandShell = JobMatchShell(shells[DEFSHELL].name);
2633 if (shellPath == NULL) {
2635 * The user didn't specify a shell to use, so we are using the
2636 * default one... Both the absolute path and the last component
2637 * must be set. The last component is taken from the 'name'
2638 * field of the default shell description pointed-to by
2639 * commandShell. All default shells are located in
2642 shellName = commandShell->name;
2643 shellPath = str_concat(PATH_DEFSHELLDIR, shellName,
2650 * Initialize the process module, given a maximum number of jobs.
2653 * lists and counters are initialized
2656 Job_Init(int maxproc)
2658 GNode *begin; /* node for commands to do at the very start */
2660 struct sigaction sa;
2663 env = getenv("MAKE_JOBS_FIFO");
2665 if (env == NULL && maxproc > 1) {
2667 * We did not find the environment variable so we are the
2668 * leader. Create the fifo, open it, write one char per
2669 * allowed job into the pipe.
2671 fifoFd = mkfifotemp(fifoName);
2676 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2678 setenv("MAKE_JOBS_FIFO", env, 1);
2679 while (maxproc-- > 0) {
2680 write(fifoFd, "+", 1);
2682 /* The master make does not get a magic token */
2687 } else if (env != NULL) {
2689 * We had the environment variable so we are a slave.
2690 * Open fifo and give ourselves a magic token which represents
2691 * the token our parent make has grabbed to start his make
2692 * process. Otherwise the sub-makes would gobble up tokens and
2693 * the proper number of tokens to specify to -j would depend
2694 * on the depth of the tree and the order of execution.
2696 fifoFd = open(env, O_RDWR, 0);
2698 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2715 if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2717 * If only one job can run at a time, there's no need for a
2718 * banner, no is there?
2728 * Catch the four signals that POSIX specifies if they aren't ignored.
2729 * JobCatchSignal will just set global variables and hope someone
2730 * else is going to handle the interrupt.
2732 sa.sa_handler = JobCatchSig;
2733 sigemptyset(&sa.sa_mask);
2736 if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2737 sigaction(SIGINT, &sa, NULL);
2739 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2740 sigaction(SIGHUP, &sa, NULL);
2742 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2743 sigaction(SIGQUIT, &sa, NULL);
2745 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2746 sigaction(SIGTERM, &sa, NULL);
2749 * There are additional signals that need to be caught and passed if
2750 * either the export system wants to be told directly of signals or if
2751 * we're giving each job its own process group (since then it won't get
2752 * signals from the terminal driver as we own the terminal)
2754 #if defined(USE_PGRP)
2755 if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2756 sigaction(SIGTSTP, &sa, NULL);
2758 if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2759 sigaction(SIGTTOU, &sa, NULL);
2761 if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2762 sigaction(SIGTTIN, &sa, NULL);
2764 if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2765 sigaction(SIGWINCH, &sa, NULL);
2770 if ((kqfd = kqueue()) == -1) {
2771 Punt("kqueue: %s", strerror(errno));
2775 begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2777 if (begin != NULL) {
2778 JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2781 Job_CatchChildren(!usePipes);
2784 postCommands = Targ_FindNode(".END", TARG_CREATE);
2789 * See if the job table is full. It is considered full if it is OR
2790 * if we are in the process of aborting OR if we have
2791 * reached/exceeded our local quota. This prevents any more jobs
2795 * TRUE if the job table is full, FALSE otherwise
2805 if (fifoFd >= 0 && jobFull) {
2806 i = read(fifoFd, &c, 1);
2817 * See if the job table is empty. Because the local concurrency may
2818 * be set to 0, it is possible for the job table to become empty,
2819 * while the list of stoppedJobs remains non-empty. In such a case,
2820 * we want to restart as many jobs as we can.
2823 * TRUE if it is. FALSE if it ain't.
2829 if (!TAILQ_EMPTY(&stoppedJobs) && !aborting) {
2831 * The job table is obviously not full if it has no
2832 * jobs in it...Try and restart the stopped jobs.
2847 * Find a matching shell in 'shells' given its final component.
2850 * A pointer to a freshly allocated Shell structure with a copy
2851 * of the static structure or NULL if no shell with the given name
2854 static struct Shell *
2855 JobMatchShell(const char *name)
2857 const struct CShell *sh; /* Pointer into shells table */
2860 for (sh = shells; sh < shells + __arysize(shells); sh++)
2861 if (strcmp(sh->name, name) == 0)
2864 if (sh == shells + __arysize(shells))
2868 nsh = emalloc(sizeof(*nsh));
2870 nsh->name = estrdup(sh->name);
2871 nsh->echoOff = estrdup(sh->echoOff);
2872 nsh->echoOn = estrdup(sh->echoOn);
2873 nsh->hasEchoCtl = sh->hasEchoCtl;
2874 nsh->noPrint = estrdup(sh->noPrint);
2875 nsh->hasErrCtl = sh->hasErrCtl;
2876 nsh->errCheck = estrdup(sh->errCheck);
2877 nsh->ignErr = estrdup(sh->ignErr);
2878 nsh->echo = estrdup(sh->echo);
2879 nsh->exit = estrdup(sh->exit);
2886 * Parse a shell specification and set up commandShell, shellPath
2887 * and shellName appropriately.
2890 * FAILURE if the specification was incorrect.
2893 * commandShell points to a Shell structure (either predefined or
2894 * created from the shell spec), shellPath is the full path of the
2895 * shell described by commandShell, while shellName is just the
2896 * final component of shellPath.
2899 * A shell specification consists of a .SHELL target, with dependency
2900 * operator, followed by a series of blank-separated words. Double
2901 * quotes can be used to use blanks in words. A backslash escapes
2902 * anything (most notably a double-quote and a space) and
2903 * provides the functionality it does in C. Each word consists of
2904 * keyword and value separated by an equal sign. There should be no
2905 * unnecessary spaces in the word. The keywords are as follows:
2906 * name Name of shell.
2907 * path Location of shell. Overrides "name" if given
2908 * quiet Command to turn off echoing.
2909 * echo Command to turn echoing on
2910 * filter Result of turning off echoing that shouldn't be
2912 * echoFlag Flag to turn echoing on at the start
2913 * errFlag Flag to turn error checking on at the start
2914 * hasErrCtl True if shell has error checking control
2915 * check Command to turn on error checking if hasErrCtl
2916 * is TRUE or template of command to echo a command
2917 * for which error checking is off if hasErrCtl is
2919 * ignore Command to turn off error checking if hasErrCtl
2920 * is TRUE or template of command to execute a
2921 * command so as to ignore any errors it returns if
2922 * hasErrCtl is FALSE.
2925 Job_ParseShell(const char line[])
2932 Boolean fullSpec = FALSE;
2933 struct Shell newShell;
2936 memset(&newShell, 0, sizeof(newShell));
2940 * Parse the specification by keyword but skip the first word
2942 brk_string(&aa, line, TRUE);
2944 for (argc = aa.argc - 1, argv = aa.argv + 1; argc != 0; argc--, argv++)
2947 * Split keyword and value
2949 if ((eq = strchr(*argv, '=')) == NULL) {
2950 Parse_Error(PARSE_FATAL, "missing '=' in shell "
2951 "specification keyword '%s'", *argv);
2957 if (strcmp(*argv, "path") == 0) {
2959 } else if (strcmp(*argv, "name") == 0) {
2961 } else if (strcmp(*argv, "quiet") == 0) {
2962 newShell.echoOff = eq;
2964 } else if (strcmp(*argv, "echo") == 0) {
2965 newShell.echoOn = eq;
2967 } else if (strcmp(*argv, "filter") == 0) {
2968 newShell.noPrint = eq;
2970 } else if (strcmp(*argv, "echoFlag") == 0) {
2973 } else if (strcmp(*argv, "errFlag") == 0) {
2976 } else if (strcmp(*argv, "hasErrCtl") == 0) {
2977 newShell.hasErrCtl = (*eq == 'Y' || *eq == 'y' ||
2978 *eq == 'T' || *eq == 't');
2980 } else if (strcmp(*argv, "check") == 0) {
2981 newShell.errCheck = eq;
2983 } else if (strcmp(*argv, "ignore") == 0) {
2984 newShell.ignErr = eq;
2987 Parse_Error(PARSE_FATAL, "unknown keyword in shell "
2988 "specification '%s'", *argv);
2995 * Some checks (could be more)
2998 if ((newShell.echoOn != NULL) ^ (newShell.echoOff != NULL))
2999 Parse_Error(PARSE_FATAL, "Shell must have either both "
3000 "echoOff and echoOn or none of them");
3002 if (newShell.echoOn != NULL && newShell.echoOff)
3003 newShell.hasEchoCtl = TRUE;
3008 * If no path was given, the user wants one of the pre-defined
3009 * shells, yes? So we find the one s/he wants with the help of
3010 * JobMatchShell and set things up the right way. shellPath
3011 * will be set up by Job_Init.
3013 if (newShell.name == NULL) {
3014 Parse_Error(PARSE_FATAL,
3015 "Neither path nor name specified");
3019 if ((sh = JobMatchShell(newShell.name)) == NULL) {
3020 Parse_Error(PARSE_FATAL, "%s: no matching shell",
3028 * The user provided a path. If s/he gave nothing else
3029 * (fullSpec is FALSE), try and find a matching shell in the
3030 * ones we know of. Else we just take the specification at its
3031 * word and copy it to a new location. In either case, we need
3032 * to record the path the user gave for the shell.
3034 path = estrdup(path);
3035 if (newShell.name == NULL) {
3036 /* get the base name as the name */
3037 if ((newShell.name = strrchr(path, '/')) == NULL) {
3038 newShell.name = path;
3045 if ((sh = JobMatchShell(newShell.name)) == NULL) {
3046 Parse_Error(PARSE_FATAL,
3047 "%s: no matching shell", newShell.name);
3053 sh = JobCopyShell(&newShell);
3059 /* set the new shell */
3060 JobFreeShell(commandShell);
3063 shellName = commandShell->name;
3071 * Handle the receipt of an interrupt.
3074 * All children are killed. Another job will be started if the
3075 * .INTERRUPT target was given.
3078 JobInterrupt(int runINTERRUPT, int signo)
3080 Job *job; /* job descriptor in that element */
3081 GNode *interrupt; /* the node describing the .INTERRUPT target */
3083 aborting = ABORT_INTERRUPT;
3085 TAILQ_FOREACH(job, &jobs, link) {
3086 if (!Targ_Precious(job->node)) {
3087 char *file = (job->node->path == NULL ?
3088 job->node->name : job->node->path);
3090 if (!noExecute && eunlink(file) != -1) {
3091 Error("*** %s removed", file);
3095 DEBUGF(JOB, ("JobInterrupt passing signal to child "
3096 "%jd.\n", (intmax_t)job->pid));
3097 KILL(job->pid, signo);
3101 if (runINTERRUPT && !touchFlag) {
3103 * clear the interrupted flag because we would get an
3104 * infinite loop otherwise.
3108 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
3109 if (interrupt != NULL) {
3110 ignoreErrors = FALSE;
3112 JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
3115 Job_CatchChildren(!usePipes);
3123 * Do final processing such as the running of the commands
3124 * attached to the .END target.
3127 * Number of errors reported.
3133 if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
3135 Error("Errors reported so .END ignored");
3137 JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
3141 Job_CatchChildren(!usePipes);
3156 * Waits for all running jobs to finish and returns. Sets 'aborting'
3157 * to ABORT_WAIT to prevent other jobs from starting.
3160 * Currently running jobs finish.
3166 aborting = ABORT_WAIT;
3167 while (nJobs != 0) {
3169 Job_CatchChildren(!usePipes);
3176 * Abort all currently running jobs without handling output or anything.
3177 * This function is to be called only in the event of a major
3178 * error. Most definitely NOT to be called from JobInterrupt.
3181 * All children are killed, not just the firstborn
3186 Job *job; /* the job descriptor in that element */
3189 aborting = ABORT_ERROR;
3192 TAILQ_FOREACH(job, &jobs, link) {
3194 * kill the child process with increasingly drastic
3195 * signals to make darn sure it's dead.
3197 KILL(job->pid, SIGINT);
3198 KILL(job->pid, SIGKILL);
3203 * Catch as many children as want to report in at first, then give up
3205 while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
3211 * Tries to restart stopped jobs if there are slots available.
3212 * Note that this tries to restart them regardless of pending errors.
3213 * It's not good to leave stopped jobs lying around!
3216 * Resumes(and possibly migrates) jobs.
3219 JobRestartJobs(void)
3223 while (!jobFull && (job = TAILQ_FIRST(&stoppedJobs)) != NULL) {
3224 DEBUGF(JOB, ("Job queue is not full. "
3225 "Restarting a stopped job.\n"));
3226 TAILQ_REMOVE(&stoppedJobs, job, link);
3233 * Execute the command in cmd, and return the output of that command
3237 * A string containing the output of the command, or the empty string
3238 * If error is not NULL, it contains the reason for the command failure
3239 * Any output sent to stderr in the child process is passed to stderr,
3240 * and not captured in the string.
3243 * The string must be freed by the caller.
3246 Cmd_Exec(const char *cmd, const char **error)
3248 int fds[2]; /* Pipe streams */
3249 int status; /* command exit status */
3250 Buffer *buf; /* buffer to store the result */
3257 if (shellPath == NULL)
3260 * Open a pipe for fetching its output
3262 if (pipe(fds) == -1) {
3263 *error = "Couldn't create pipe for \"%s\"";
3267 /* Set close-on-exec on read side of pipe. */
3268 fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC);
3270 ps.in = STDIN_FILENO;
3272 ps.err = STDERR_FILENO;
3274 ps.merge_errors = 0;
3278 /* Set up arguments for shell */
3279 ps.argv = emalloc(4 * sizeof(char *));
3280 ps.argv[0] = strdup(shellName);
3281 ps.argv[1] = strdup("-c");
3282 ps.argv[2] = strdup(cmd);
3287 * Fork. Warning since we are doing vfork() instead of fork(),
3288 * do not allocate memory in the child process!
3290 if ((ps.child_pid = vfork()) == -1) {
3291 *error = "Couldn't exec \"%s\"";
3293 } else if (ps.child_pid == 0) {
3306 close(fds[1]); /* No need for the writing half of the pipe. */
3309 char result[BUFSIZ];
3311 rcnt = read(fds[0], result, sizeof(result));
3313 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
3314 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
3317 *error = "Error reading shell's output for \"%s\"";
3320 * Close the input side of the pipe.
3324 status = ProcWait(&ps);
3326 *error = "\"%s\" returned non-zero status";
3328 Buf_StripNewlines(buf);
3335 * Interrupt handler - set flag and defer handling to the main code
3338 CompatCatchSig(int signo)
3341 interrupted = signo;
3345 *-----------------------------------------------------------------------
3346 * CompatInterrupt --
3347 * Interrupt the creation of the current target and remove it if
3348 * it ain't precious.
3354 * The target is removed and the process exits. If .INTERRUPT exists,
3355 * its commands are run first WITH INTERRUPTS IGNORED..
3357 *-----------------------------------------------------------------------
3360 CompatInterrupt(int signo)
3363 sigset_t nmask, omask;
3366 sigemptyset(&nmask);
3367 sigaddset(&nmask, SIGINT);
3368 sigaddset(&nmask, SIGTERM);
3369 sigaddset(&nmask, SIGHUP);
3370 sigaddset(&nmask, SIGQUIT);
3371 sigprocmask(SIG_SETMASK, &nmask, &omask);
3373 /* prevent recursion in evaluation of .INTERRUPT */
3376 if (curTarg != NULL && !Targ_Precious(curTarg)) {
3377 const char *file = Var_Value(TARGET, curTarg);
3379 if (!noExecute && eunlink(file) != -1) {
3380 printf("*** %s removed\n", file);
3385 * Run .INTERRUPT only if hit with interrupt signal
3387 if (signo == SIGINT) {
3388 gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
3390 LST_FOREACH(ln, &gn->commands) {
3391 if (Compat_RunCommand(Lst_Datum(ln), gn))
3397 sigprocmask(SIG_SETMASK, &omask, NULL);
3399 if (signo == SIGQUIT)
3401 signal(signo, SIG_DFL);
3402 kill(getpid(), signo);
3406 *-----------------------------------------------------------------------
3407 * Compat_RunCommand --
3408 * Execute the next command for a target. If the command returns an
3409 * error, the node's made field is set to ERROR and creation stops.
3410 * The node from which the command came is also given.
3413 * 0 if the command succeeded, 1 if an error occurred.
3416 * The node's 'made' field may be set to ERROR.
3418 *-----------------------------------------------------------------------
3421 Compat_RunCommand(char *cmd, GNode *gn)
3424 char *cmdStart; /* Start of expanded command */
3425 Boolean silent; /* Don't print command */
3426 Boolean doit; /* Execute even in -n */
3427 Boolean errCheck; /* Check errors */
3428 int reason; /* Reason for child's death */
3429 int status; /* Description of child's death */
3430 LstNode *cmdNode; /* Node where current cmd is located */
3431 char **av; /* Argument vector for thing to exec */
3434 silent = gn->type & OP_SILENT;
3435 errCheck = !(gn->type & OP_IGNORE);
3438 cmdNode = Lst_Member(&gn->commands, cmd);
3439 cmdStart = Buf_Peel(Var_Subst(cmd, gn, FALSE));
3441 if (*cmdStart == '\0') {
3443 Error("%s expands to empty string", cmd);
3448 Lst_Replace(cmdNode, cmdStart);
3450 if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
3451 Lst_AtEnd(&ENDNode->commands, cmdStart);
3453 } else if (strcmp(cmdStart, "...") == 0) {
3454 gn->type |= OP_SAVE_CMDS;
3458 while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
3462 silent = DEBUG(LOUD) ? FALSE : TRUE;
3476 while (isspace((unsigned char)*cmd))
3480 * Print the command before echoing if we're not supposed to be quiet
3481 * for this one. We also print the command if -n given, but not if '+'.
3483 if (!silent || (noExecute && !doit)) {
3484 printf("%s\n", cmd);
3489 * If we're not supposed to execute any commands, this is as far as
3492 if (!doit && noExecute) {
3496 if (strpbrk(cmd, "#=|^(){};&<>*?[]:$`\\\n")) {
3498 * We found a "meta" character and need to pass the command
3505 const char *sh_builtin[] = {
3506 "alias", "cd", "eval", "exec",
3507 "exit", "read", "set", "ulimit",
3508 "unalias", "umask", "unset", "wait",
3513 * Break the command into words to form an argument
3514 * vector we can execute.
3516 brk_string(&aa, cmd, TRUE);
3519 for (p = sh_builtin; *p != 0; p++) {
3520 if (strcmp(av[0], *p) == 0) {
3522 * This command must be passed by the shell
3523 * for other reasons.. or.. possibly not at
3532 ps.in = STDIN_FILENO;
3533 ps.out = STDOUT_FILENO;
3534 ps.err = STDERR_FILENO;
3536 ps.merge_errors = 0;
3542 * We give the shell the -e flag as well as -c if it's
3543 * supposed to exit when it hits an error.
3545 ps.argv = emalloc(4 * sizeof(char *));
3546 ps.argv[0] = strdup(shellPath);
3547 ps.argv[1] = strdup(errCheck ? "-ec" : "-c");
3548 ps.argv[2] = strdup(cmd);
3555 ps.errCheck = errCheck;
3558 * Fork and execute the single command. If the fork fails, we abort.
3559 * Warning since we are doing vfork() instead of fork(),
3560 * do not allocate memory in the child process!
3562 if ((ps.child_pid = vfork()) == -1) {
3563 Fatal("Could not fork");
3565 } else if (ps.child_pid == 0) {
3583 * we need to print out the command associated with this
3584 * Gnode in Targ_PrintCmd from Targ_PrintGraph when debugging
3585 * at level g2, in main(), Fatal() and DieHorribly(),
3586 * therefore do not free it when debugging.
3588 if (!DEBUG(GRAPH2)) {
3593 * The child is off and running. Now all we can do is wait...
3595 reason = ProcWait(&ps);
3598 CompatInterrupt(interrupted);
3601 * Decode and report the reason child exited, then
3602 * indicate how we handled it.
3604 if (WIFEXITED(reason)) {
3605 status = WEXITSTATUS(reason);
3609 printf("*** Error code %d", status);
3611 } else if (WIFSTOPPED(reason)) {
3612 status = WSTOPSIG(reason);
3614 status = WTERMSIG(reason);
3615 printf("*** Signal %d", status);
3626 printf(" (continuing)\n");
3631 * Continue executing
3632 * commands for this target.
3633 * If we return 0, this will
3636 printf(" (ignored)\n");
3643 *-----------------------------------------------------------------------
3645 * Make a target, given the parent, to abort if necessary.
3648 * If an error is detected and not being ignored, the process exits.
3650 *-----------------------------------------------------------------------
3653 CompatMake(GNode *gn, GNode *pgn)
3657 if (gn->type & OP_USE) {
3658 Make_HandleUse(gn, pgn);
3660 } else if (gn->made == UNMADE) {
3662 * First mark ourselves to be made, then apply whatever
3663 * transformations the suffix module thinks are necessary.
3664 * Once that's done, we can descend and make all our children.
3665 * If any of them has an error but the -k flag was given, our
3666 * 'make' field will be set FALSE again. This is our signal to
3667 * not attempt to do anything but abort our parent as well.
3670 gn->made = BEINGMADE;
3672 LST_FOREACH(ln, &gn->children)
3673 CompatMake(Lst_Datum(ln), gn);
3680 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3681 Var_Set(IMPSRC, Var_Value(TARGET, gn), pgn);
3685 * All the children were made ok. Now cmtime contains the
3686 * modification time of the newest child, we need to find out
3687 * if we exist and when we were modified last. The criteria for
3688 * datedness are defined by the Make_OODate function.
3690 DEBUGF(MAKE, ("Examining %s...", gn->name));
3691 if (!Make_OODate(gn)) {
3692 gn->made = UPTODATE;
3693 DEBUGF(MAKE, ("up-to-date.\n"));
3696 DEBUGF(MAKE, ("out-of-date.\n"));
3700 * If the user is just seeing if something is out-of-date,
3701 * exit now to tell him/her "yes".
3708 * We need to be re-made. We also have to make sure we've got
3709 * a $? variable. To be nice, we also define the $> variable
3710 * using Make_DoAllVar().
3715 * Alter our type to tell if errors should be ignored or things
3716 * should not be printed so Compat_RunCommand knows what to do.
3718 if (Targ_Ignore(gn)) {
3719 gn->type |= OP_IGNORE;
3721 if (Targ_Silent(gn)) {
3722 gn->type |= OP_SILENT;
3725 if (Job_CheckCommands(gn, Fatal)) {
3727 * Our commands are ok, but we still have to worry
3728 * about the -t flag...
3732 LST_FOREACH(ln, &gn->commands) {
3733 if (Compat_RunCommand(Lst_Datum(ln),
3739 Job_Touch(gn, gn->type & OP_SILENT);
3745 if (gn->made != ERROR) {
3747 * If the node was made successfully, mark it so, update
3748 * its modification time and timestamp all its parents.
3749 * Note that for .ZEROTIME targets, the timestamping
3750 * isn't done. This is to keep its state from affecting
3751 * that of its parent.
3756 * We can't re-stat the thing, but we can at least take
3757 * care of rules where a target depends on a source that
3758 * actually creates the target, but only if it has
3766 * mv y.tab.o parse.o
3767 * cmp -s y.tab.h parse.h || mv y.tab.h parse.h
3769 * In this case, if the definitions produced by yacc
3770 * haven't changed from before, parse.h won't have been
3771 * updated and gn->mtime will reflect the current
3772 * modification time for parse.h. This is something of a
3773 * kludge, I admit, but it's a useful one..
3775 * XXX: People like to use a rule like
3779 * To force things that depend on FRC to be made, so we
3780 * have to check for gn->children being empty as well...
3782 if (!Lst_IsEmpty(&gn->commands) ||
3783 Lst_IsEmpty(&gn->children)) {
3788 * This is what Make does and it's actually a good
3789 * thing, as it allows rules like
3791 * cmp -s y.tab.h parse.h || cp y.tab.h parse.h
3793 * to function as intended. Unfortunately, thanks to
3794 * the stateless nature of NFS (and the speed of this
3795 * program), there are times when the modification time
3796 * of a file created on a remote machine will not be
3797 * modified before the stat() implied by the Dir_MTime
3798 * occurs, thus leading us to believe that the file
3799 * is unchanged, wreaking havoc with files that depend
3802 * I have decided it is better to make too much than to
3803 * make too little, so this stuff is commented out
3804 * unless you're sure it's ok.
3807 if (noExecute || Dir_MTime(gn) == 0) {
3810 if (gn->cmtime > gn->mtime)
3811 gn->mtime = gn->cmtime;
3812 DEBUGF(MAKE, ("update time: %s\n",
3813 Targ_FmtTime(gn->mtime)));
3815 if (!(gn->type & OP_EXEC)) {
3816 pgn->childMade = TRUE;
3817 Make_TimeStamp(pgn, gn);
3820 } else if (keepgoing) {
3824 printf("\n\nStop in %s.\n", Var_Value(".CURDIR", gn));
3827 } else if (gn->made == ERROR) {
3829 * Already had an error when making this beastie. Tell the
3834 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3835 Var_Set(IMPSRC, Var_Value(TARGET, gn), pgn);
3839 Error("Graph cycles through %s\n", gn->name);
3844 if ((gn->type & OP_EXEC) == 0) {
3845 pgn->childMade = TRUE;
3846 Make_TimeStamp(pgn, gn);
3850 if ((gn->type & OP_EXEC) == 0) {
3851 Make_TimeStamp(pgn, gn);
3863 *-----------------------------------------------------------------------
3865 * Start making again, given a list of target nodes.
3873 *-----------------------------------------------------------------------
3876 Compat_Run(Lst *targs)
3878 GNode *gn = NULL; /* Current root target */
3879 int error_cnt; /* Number of targets not remade due to errors */
3882 Shell_Init(); /* Set up shell. */
3884 if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
3885 signal(SIGINT, CompatCatchSig);
3887 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
3888 signal(SIGTERM, CompatCatchSig);
3890 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
3891 signal(SIGHUP, CompatCatchSig);
3893 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
3894 signal(SIGQUIT, CompatCatchSig);
3897 ENDNode = Targ_FindNode(".END", TARG_CREATE);
3899 * If the user has defined a .BEGIN target, execute the commands
3903 gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
3905 LST_FOREACH(ln, &gn->commands) {
3906 if (Compat_RunCommand(Lst_Datum(ln), gn))
3909 if (gn->made == ERROR) {
3910 printf("\n\nStop.\n");
3917 * For each entry in the list of targets to create, call CompatMake on
3918 * it to create the thing. CompatMake will leave the 'made' field of gn
3919 * in one of several states:
3920 * UPTODATE gn was already up-to-date
3921 * MADE gn was recreated successfully
3922 * ERROR An error occurred while gn was being created
3923 * ABORTED gn was not remade because one of its inferiors
3924 * could not be made due to errors.
3927 while (!Lst_IsEmpty(targs)) {
3928 gn = Lst_DeQueue(targs);
3931 if (gn->made == UPTODATE) {
3932 printf("`%s' is up to date.\n", gn->name);
3933 } else if (gn->made == ABORTED) {
3934 printf("`%s' not remade because of errors.\n",
3941 * If the user has defined a .END target, run its commands.
3943 if (error_cnt == 0) {
3944 LST_FOREACH(ln, &ENDNode->commands) {
3945 if (Compat_RunCommand(Lst_Datum(ln), gn))