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.65 2005/04/24 12:42:22 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)
464 typedef struct ProcStuff {
470 static void JobRestart(Job *);
471 static int JobStart(GNode *, int, Job *);
472 static void JobDoOutput(Job *, Boolean);
473 static struct Shell *JobMatchShell(const char *);
474 static void JobInterrupt(int, int);
475 static void JobRestartJobs(void);
476 static void ProcExec(ProcStuff *, char *[]) __dead2;
479 * Replace the current process.
482 ProcExec(ProcStuff *ps, char *argv[])
484 if (ps->merge_errors) {
486 * Send stderr to parent process too.
488 if (dup2(STDOUT_FILENO, STDERR_FILENO) == -1)
489 Punt("Cannot dup2: %s", strerror(errno));
495 * Become a process group leader, so we can kill it and all
496 * its descendants in one fell swoop, by killing its process
497 * family, but not commit suicide.
502 setpgid(0, getpid());
504 #endif /* USE_PGRP */
507 if (ps->searchpath) {
508 execvp(argv[0], argv);
510 write(STDERR_FILENO, argv[0], strlen(argv[0]));
511 write(STDERR_FILENO, ":", 1);
512 write(STDERR_FILENO, strerror(errno), strlen(strerror(errno)));
513 write(STDERR_FILENO, "\n", 1);
515 execv(shellPath, argv);
518 "Could not execute shell\n",
519 sizeof("Could not execute shell"));
523 * Since we are the child process, exit without flushing buffers.
530 * Got a signal. Set global variables and hope that someone will
534 JobCatchSig(int signo)
542 * Pass a signal on to all local jobs if
543 * USE_PGRP is defined, then die ourselves.
546 * We die by the same signal.
549 JobPassSig(int signo)
552 sigset_t nmask, omask;
553 struct sigaction act;
556 sigaddset(&nmask, signo);
557 sigprocmask(SIG_SETMASK, &nmask, &omask);
559 DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
560 TAILQ_FOREACH(job, &jobs, link) {
561 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
562 signo, (intmax_t)job->pid));
563 KILL(job->pid, signo);
567 * Deal with proper cleanup based on the signal received. We only run
568 * the .INTERRUPT target if the signal was in fact an interrupt.
569 * The other three termination signals are more of a "get out *now*"
572 if (signo == SIGINT) {
573 JobInterrupt(TRUE, signo);
574 } else if (signo == SIGHUP || signo == SIGTERM || signo == SIGQUIT) {
575 JobInterrupt(FALSE, signo);
579 * Leave gracefully if SIGQUIT, rather than core dumping.
581 if (signo == SIGQUIT) {
586 * Send ourselves the signal now we've given the message to everyone
587 * else. Note we block everything else possible while we're getting
588 * the signal. This ensures that all our jobs get continued when we
589 * wake up before we take any other signal.
590 * XXX this comment seems wrong.
592 act.sa_handler = SIG_DFL;
593 sigemptyset(&act.sa_mask);
595 sigaction(signo, &act, NULL);
597 DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
598 ~0 & ~(1 << (signo - 1))));
599 signal(signo, SIG_DFL);
601 KILL(getpid(), signo);
604 TAILQ_FOREACH(job, &jobs, link) {
605 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
606 signo, (intmax_t)job->pid));
607 KILL(job->pid, signo);
610 sigprocmask(SIG_SETMASK, &omask, NULL);
611 sigprocmask(SIG_SETMASK, &omask, NULL);
612 act.sa_handler = JobPassSig;
613 sigaction(signo, &act, NULL);
618 * Put out another command for the given job. If the command starts
619 * with an @ or a - we process it specially. In the former case,
620 * so long as the -s and -n flags weren't given to make, we stick
621 * a shell-specific echoOff command in the script. In the latter,
622 * we ignore errors for the entire job, unless the shell has error
624 * If the command is just "..." we take all future commands for this
625 * job to be commands to be executed once the entire graph has been
626 * made and return non-zero to signal that the end of the commands
627 * was reached. These commands are later attached to the postCommands
628 * node and executed by Job_Finish when all things are done.
629 * This function is called from JobStart via LST_FOREACH.
632 * Always 0, unless the command was "..."
635 * If the command begins with a '-' and the shell has no error control,
636 * the JOB_IGNERR flag is set in the job descriptor.
637 * If the command is "..." and we're not ignoring such things,
638 * tailCmds is set to the successor node of the cmd.
639 * numCommands is incremented if the command is actually printed.
642 JobPrintCommand(char *cmd, Job *job)
644 Boolean noSpecials; /* true if we shouldn't worry about
645 * inserting special commands into
646 * the input stream. */
647 Boolean shutUp = FALSE; /* true if we put a no echo command
648 * into the command file */
649 Boolean errOff = FALSE; /* true if we turned error checking
650 * off before printing the command
651 * and need to turn it back on */
652 const char *cmdTemplate;/* Template to use when printing the command */
653 char *cmdStart; /* Start of expanded command */
654 LstNode *cmdNode; /* Node for replacing the command */
656 noSpecials = (noExecute && !(job->node->type & OP_MAKE));
658 if (strcmp(cmd, "...") == 0) {
659 job->node->type |= OP_SAVE_CMDS;
660 if ((job->flags & JOB_IGNDOTS) == 0) {
662 Lst_Succ(Lst_Member(&job->node->commands, cmd));
668 #define DBPRINTF(fmt, arg) \
669 DEBUGF(JOB, (fmt, arg)); \
670 fprintf(job->cmdFILE, fmt, arg); \
671 fflush(job->cmdFILE);
676 * For debugging, we replace each command with the result of expanding
677 * the variables in the command.
679 cmdNode = Lst_Member(&job->node->commands, cmd);
681 cmd = Buf_Peel(Var_Subst(cmd, job->node, FALSE));
684 Lst_Replace(cmdNode, cmdStart);
686 cmdTemplate = "%s\n";
689 * Check for leading @', -' or +'s to control echoing, error checking,
690 * and execution on -n.
692 while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
696 shutUp = DEBUG(LOUD) ? FALSE : TRUE;
706 * We're not actually exececuting anything...
707 * but this one needs to be - use compat mode
710 Compat_RunCommand(cmd, job->node);
718 while (isspace((unsigned char)*cmd))
722 if (!(job->flags & JOB_SILENT) && !noSpecials &&
723 commandShell->hasEchoCtl) {
724 DBPRINTF("%s\n", commandShell->echoOff);
731 if (!(job->flags & JOB_IGNERR) && !noSpecials) {
732 if (commandShell->hasErrCtl) {
734 * We don't want the error-control commands
735 * showing up either, so we turn off echoing
736 * while executing them. We could put another
737 * field in the shell structure to tell
738 * JobDoOutput to look for this string too,
739 * but why make it any more complex than
742 if (!(job->flags & JOB_SILENT) && !shutUp &&
743 commandShell->hasEchoCtl) {
744 DBPRINTF("%s\n", commandShell->echoOff);
745 DBPRINTF("%s\n", commandShell->ignErr);
746 DBPRINTF("%s\n", commandShell->echoOn);
748 DBPRINTF("%s\n", commandShell->ignErr);
750 } else if (commandShell->ignErr &&
751 *commandShell->ignErr != '\0') {
753 * The shell has no error control, so we need to
754 * be weird to get it to ignore any errors from
755 * the command. If echoing is turned on, we turn
756 * it off and use the errCheck template to echo
757 * the command. Leave echoing off so the user
758 * doesn't see the weirdness we go through to
759 * ignore errors. Set cmdTemplate to use the
760 * weirdness instead of the simple "%s\n"
763 if (!(job->flags & JOB_SILENT) && !shutUp &&
764 commandShell->hasEchoCtl) {
765 DBPRINTF("%s\n", commandShell->echoOff);
766 DBPRINTF(commandShell->errCheck, cmd);
769 cmdTemplate = commandShell->ignErr;
771 * The error ignoration (hee hee) is already
772 * taken care of by the ignErr template, so
773 * pretend error checking is still on.
784 DBPRINTF(cmdTemplate, cmd);
788 * If echoing is already off, there's no point in issuing the
789 * echoOff command. Otherwise we issue it and pretend it was on
790 * for the whole command...
792 if (!shutUp && !(job->flags & JOB_SILENT) &&
793 commandShell->hasEchoCtl) {
794 DBPRINTF("%s\n", commandShell->echoOff);
797 DBPRINTF("%s\n", commandShell->errCheck);
800 DBPRINTF("%s\n", commandShell->echoOn);
807 * Called to close both input and output pipes when a job is finished.
810 * The file descriptors associated with the job are closed.
817 #if !defined(USE_KQUEUE)
818 FD_CLR(job->inPipe, &outputs);
820 if (job->outPipe != job->inPipe) {
823 JobDoOutput(job, TRUE);
827 JobDoOutput(job, TRUE);
833 * Do final processing for the given job including updating
834 * parents and starting new jobs as available/necessary. Note
835 * that we pay no attention to the JOB_IGNERR flag here.
836 * This is because when we're called because of a noexecute flag
837 * or something, jstat.w_status is 0 and when called from
838 * Job_CatchChildren, the status is zeroed if it s/b ignored.
841 * Some nodes may be put on the toBeMade queue.
842 * Final commands for the job are placed on postCommands.
844 * If we got an error and are aborting (aborting == ABORT_ERROR) and
845 * the job list is now empty, we are done for the day.
846 * If we recognized an error (errors !=0), we set the aborting flag
847 * to ABORT_ERROR so no more jobs will be started.
850 JobFinish(Job *job, int *status)
855 if ((WIFEXITED(*status) && WEXITSTATUS(*status) != 0 &&
856 !(job->flags & JOB_IGNERR)) ||
857 (WIFSIGNALED(*status) && WTERMSIG(*status) != SIGCONT)) {
859 * If it exited non-zero and either we're doing things our
860 * way or we're not ignoring errors, the job is finished.
861 * Similarly, if the shell died because of a signal
862 * the job is also finished. In these cases, finish out the
863 * job's output before printing the exit status...
866 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
867 fclose(job->cmdFILE);
871 } else if (WIFEXITED(*status)) {
873 * Deal with ignored errors in -B mode. We need to print a
874 * message telling of the ignored error as well as setting
875 * status.w_status to 0 so the next command gets run. To do
876 * this, we set done to be TRUE if in -B mode and the job
879 done = WEXITSTATUS(*status) != 0;
882 * Old comment said: "Note we don't want to close down any of
883 * the streams until we know we're at the end." But we do.
884 * Otherwise when are we going to print the rest of the stuff?
889 * No need to close things down or anything.
894 if (done || WIFSTOPPED(*status) ||
895 (WIFSIGNALED(*status) && WTERMSIG(*status) == SIGCONT) ||
899 if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
901 * If output is going to a file and this job is ignoring
902 * errors, arrange to have the exit status sent to the
903 * output file as well.
905 out = fdopen(job->outFd, "w");
907 Punt("Cannot fdopen");
912 if (WIFEXITED(*status)) {
913 DEBUGF(JOB, ("Process %jd exited.\n",
914 (intmax_t)job->pid));
915 if (WEXITSTATUS(*status) != 0) {
916 if (usePipes && job->node != lastNode) {
917 MESSAGE(out, job->node);
918 lastNode = job->node;
920 fprintf(out, "*** Error code %d%s\n",
921 WEXITSTATUS(*status),
922 (job->flags & JOB_IGNERR) ?
925 if (job->flags & JOB_IGNERR) {
928 } else if (DEBUG(JOB)) {
929 if (usePipes && job->node != lastNode) {
930 MESSAGE(out, job->node);
931 lastNode = job->node;
933 fprintf(out, "*** Completed successfully\n");
936 } else if (WIFSTOPPED(*status)) {
937 DEBUGF(JOB, ("Process %jd stopped.\n",
938 (intmax_t)job->pid));
939 if (usePipes && job->node != lastNode) {
940 MESSAGE(out, job->node);
941 lastNode = job->node;
943 fprintf(out, "*** Stopped -- signal %d\n",
945 job->flags |= JOB_RESUME;
946 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
950 } else if (WTERMSIG(*status) == SIGCONT) {
952 * If the beastie has continued, shift the Job from
953 * the stopped list to the running one (or re-stop it
954 * if concurrency is exceeded) and go and get another
957 if (job->flags & (JOB_RESUME | JOB_RESTART)) {
958 if (usePipes && job->node != lastNode) {
959 MESSAGE(out, job->node);
960 lastNode = job->node;
962 fprintf(out, "*** Continued\n");
964 if (!(job->flags & JOB_CONTINUING)) {
965 DEBUGF(JOB, ("Warning: process %jd was not "
966 "continuing.\n", (intmax_t)job->pid));
969 * We don't really want to restart a job from
970 * scratch just because it continued, especially
971 * not without killing the continuing process!
972 * That's why this is ifdef'ed out.
978 job->flags &= ~JOB_CONTINUING;
979 TAILQ_INSERT_TAIL(&jobs, job, link);
981 DEBUGF(JOB, ("Process %jd is continuing locally.\n",
982 (intmax_t)job->pid));
983 if (nJobs == maxJobs) {
985 DEBUGF(JOB, ("Job queue is full.\n"));
991 if (usePipes && job->node != lastNode) {
992 MESSAGE(out, job->node);
993 lastNode = job->node;
995 fprintf(out, "*** Signal %d\n", WTERMSIG(*status));
1002 * Now handle the -B-mode stuff. If the beast still isn't finished,
1003 * try and restart the job on the next command. If JobStart says it's
1004 * ok, it's ok. If there's an error, this puppy is done.
1006 if (compatMake && WIFEXITED(*status) &&
1007 Lst_Succ(job->node->compat_command) != NULL) {
1008 switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
1014 W_SETEXITSTATUS(status, 1);
1018 * If we got back a JOB_FINISHED code, JobStart has
1019 * already called Make_Update and freed the job
1020 * descriptor. We set done to false here to avoid fake
1021 * cycles and double frees. JobStart needs to do the
1022 * update so we can proceed up the graph when given
1034 if (done && aborting != ABORT_ERROR &&
1035 aborting != ABORT_INTERRUPT && *status == 0) {
1037 * As long as we aren't aborting and the job didn't return a
1038 * non-zero status that we shouldn't ignore, we call
1039 * Make_Update to update the parents. In addition, any saved
1040 * commands for the node are placed on the .END target.
1042 for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
1043 Lst_AtEnd(&postCommands->commands,
1045 Var_Subst(Lst_Datum(ln), job->node, FALSE)));
1048 job->node->made = MADE;
1049 Make_Update(job->node);
1052 } else if (*status != 0) {
1060 * Set aborting if any error.
1062 if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
1064 * If we found any errors in this batch of children and the -k
1065 * flag wasn't given, we set the aborting flag so no more jobs
1068 aborting = ABORT_ERROR;
1071 if (aborting == ABORT_ERROR && Job_Empty()) {
1073 * If we are aborting and the job table is now empty, we finish.
1081 * Touch the given target. Called by JobStart when the -t flag was
1082 * given. Prints messages unless told to be silent.
1085 * The data modification of the file is changed. In addition, if the
1086 * file did not exist, it is created.
1089 Job_Touch(GNode *gn, Boolean silent)
1091 int streamID; /* ID of stream opened to do the touch */
1092 struct utimbuf times; /* Times for utime() call */
1094 if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
1096 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
1097 * targets and, as such, shouldn't really be created.
1103 fprintf(stdout, "touch %s\n", gn->name);
1111 if (gn->type & OP_ARCHV) {
1113 } else if (gn->type & OP_LIB) {
1116 char *file = gn->path ? gn->path : gn->name;
1118 times.actime = times.modtime = now;
1119 if (utime(file, ×) < 0) {
1120 streamID = open(file, O_RDWR | O_CREAT, 0666);
1122 if (streamID >= 0) {
1126 * Read and write a byte to the file to change
1127 * the modification time, then close the file.
1129 if (read(streamID, &c, 1) == 1) {
1130 lseek(streamID, (off_t)0, SEEK_SET);
1131 write(streamID, &c, 1);
1136 fprintf(stdout, "*** couldn't touch %s: %s",
1137 file, strerror(errno));
1146 * Make sure the given node has all the commands it needs.
1149 * TRUE if the commands list is/was ok.
1152 * The node will have commands from the .DEFAULT rule added to it
1156 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1159 if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
1160 (gn->type & OP_LIB) == 0) {
1162 * No commands. Look for .DEFAULT rule from which we might infer
1165 if (DEFAULT != NULL && !Lst_IsEmpty(&DEFAULT->commands)) {
1168 * Make only looks for a .DEFAULT if the node was
1169 * never the target of an operator, so that's what we
1170 * do too. If a .DEFAULT was given, we substitute its
1171 * commands for gn's commands and set the IMPSRC
1172 * variable to be the target's name The DEFAULT node
1173 * acts like a transformation rule, in that gn also
1174 * inherits any attributes or sources attached to
1177 Make_HandleUse(DEFAULT, gn);
1178 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn);
1181 } else if (Dir_MTime(gn) == 0) {
1183 * The node wasn't the target of an operator we have
1184 * no .DEFAULT rule to go on and the target doesn't
1185 * already exist. There's nothing more we can do for
1186 * this branch. If the -k flag wasn't given, we stop
1187 * in our tracks, otherwise we just don't update
1188 * this node's parents so they never get examined.
1190 static const char msg[] =
1191 "make: don't know how to make";
1193 if (gn->type & OP_OPTIONAL) {
1194 fprintf(stdout, "%s %s(ignored)\n",
1197 } else if (keepgoing) {
1198 fprintf(stdout, "%s %s(continuing)\n",
1204 if (strcmp(gn->name,"love") == 0)
1205 (*abortProc)("Not war.");
1208 (*abortProc)("%s %s. Stop",
1219 * Execute the shell for the given job. Called from JobStart and
1223 * A shell is executed, outputs is altered and the Job structure added
1227 JobExec(Job *job, char **argv)
1229 pid_t cpid; /* ID of new child */
1234 DEBUGF(JOB, ("Running %s\n", job->node->name));
1235 DEBUGF(JOB, ("\tCommand: "));
1236 for (i = 0; argv[i] != NULL; i++) {
1237 DEBUGF(JOB, ("%s ", argv[i]));
1239 DEBUGF(JOB, ("\n"));
1243 * Some jobs produce no output and it's disconcerting to have
1244 * no feedback of their running (since they produce no output, the
1245 * banner with their name in it never appears). This is an attempt to
1246 * provide that feedback, even if nothing follows it.
1248 if (lastNode != job->node && (job->flags & JOB_FIRST) &&
1249 !(job->flags & JOB_SILENT)) {
1250 MESSAGE(stdout, job->node);
1251 lastNode = job->node;
1254 if ((cpid = vfork()) == -1) {
1255 Punt("Cannot fork");
1257 } else if (cpid == 0) {
1266 * Must duplicate the input stream down to the child's input and
1267 * reset it to the beginning (again). Since the stream was
1268 * marked close-on-exec, we must clear that bit in the new
1271 if (dup2(FILENO(job->cmdFILE), 0) == -1)
1272 Punt("Cannot dup2: %s", strerror(errno));
1273 fcntl(0, F_SETFD, 0);
1274 lseek(0, (off_t)0, SEEK_SET);
1278 * Set up the child's output to be routed through the
1279 * pipe we've created for it.
1281 if (dup2(job->outPipe, 1) == -1)
1282 Punt("Cannot dup2: %s", strerror(errno));
1285 * We're capturing output in a file, so we duplicate the
1286 * descriptor to the temporary file into the standard
1289 if (dup2(job->outFd, 1) == -1)
1290 Punt("Cannot dup2: %s", strerror(errno));
1293 * The output channels are marked close on exec. This bit was
1294 * duplicated by the dup2 (on some systems), so we have to clear
1295 * it before routing the shell's error output to the same place
1296 * as its standard output.
1298 fcntl(1, F_SETFD, 0);
1300 ps.merge_errors = 1;
1303 ProcExec(&ps, argv);
1312 if (usePipes && (job->flags & JOB_FIRST)) {
1314 * The first time a job is run for a node, we set the
1315 * current position in the buffer to the beginning and
1316 * mark another stream to watch in the outputs mask.
1319 struct kevent kev[2];
1323 #if defined(USE_KQUEUE)
1324 EV_SET(&kev[0], job->inPipe, EVFILT_READ, EV_ADD, 0, 0, job);
1325 EV_SET(&kev[1], job->pid, EVFILT_PROC,
1326 EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
1327 if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1329 * kevent() will fail if the job is already
1332 if (errno != EINTR && errno != EBADF && errno != ESRCH)
1333 Punt("kevent: %s", strerror(errno));
1336 FD_SET(job->inPipe, &outputs);
1337 #endif /* USE_KQUEUE */
1340 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1341 fclose(job->cmdFILE);
1342 job->cmdFILE = NULL;
1346 * Now the job is actually running, add it to the table.
1349 TAILQ_INSERT_TAIL(&jobs, job, link);
1350 if (nJobs == maxJobs) {
1358 * Create the argv needed to execute the shell for a given job.
1361 JobMakeArgv(Job *job, char **argv)
1364 static char args[10]; /* For merged arguments */
1366 argv[0] = shellName;
1369 if ((commandShell->exit && *commandShell->exit != '-') ||
1370 (commandShell->echo && *commandShell->echo != '-')) {
1372 * At least one of the flags doesn't have a minus before it, so
1373 * merge them together. Have to do this because the *(&(@*#*&#$#
1374 * Bourne shell thinks its second argument is a file to source.
1375 * Grrrr. Note the ten-character limitation on the combined
1378 sprintf(args, "-%s%s", (job->flags & JOB_IGNERR) ? "" :
1379 commandShell->exit ? commandShell->exit : "",
1380 (job->flags & JOB_SILENT) ? "" :
1381 commandShell->echo ? commandShell->echo : "");
1388 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1389 argv[argc] = commandShell->exit;
1392 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1393 argv[argc] = commandShell->echo;
1402 * Restart a job that stopped for some reason. The job must be neither
1403 * on the jobs nor on the stoppedJobs list.
1406 * jobFull will be set if the job couldn't be run.
1409 JobRestart(Job *job)
1412 if (job->flags & JOB_RESTART) {
1414 * Set up the control arguments to the shell. This is based on
1415 * the flags set earlier for this job. If the JOB_IGNERR flag
1416 * is clear, the 'exit' flag of the commandShell is used to
1417 * cause it to exit upon receiving an error. If the JOB_SILENT
1418 * flag is clear, the 'echo' flag of the commandShell is used
1419 * to get it to start echoing as soon as it starts
1420 * processing commands.
1424 JobMakeArgv(job, argv);
1426 DEBUGF(JOB, ("Restarting %s...", job->node->name));
1427 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL)) {
1429 * Not allowed to run -- put it back on the hold
1430 * queue and mark the table full
1432 DEBUGF(JOB, ("holding\n"));
1433 TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1435 DEBUGF(JOB, ("Job queue is full.\n"));
1439 * Job may be run locally.
1441 DEBUGF(JOB, ("running locally\n"));
1447 * The job has stopped and needs to be restarted.
1448 * Why it stopped, we don't know...
1450 DEBUGF(JOB, ("Resuming %s...", job->node->name));
1451 if ((nJobs < maxJobs || ((job->flags & JOB_SPECIAL) &&
1452 maxJobs == 0)) && nJobs != maxJobs) {
1454 * If we haven't reached the concurrency limit already
1455 * (or the job must be run and maxJobs is 0), it's ok
1461 error = (KILL(job->pid, SIGCONT) != 0);
1465 * Make sure the user knows we've continued
1466 * the beast and actually put the thing in the
1469 job->flags |= JOB_CONTINUING;
1471 W_SETTERMSIG(&status, SIGCONT);
1472 JobFinish(job, &status);
1474 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1475 DEBUGF(JOB, ("done\n"));
1477 Error("couldn't resume %s: %s",
1478 job->node->name, strerror(errno));
1480 W_SETEXITSTATUS(&status, 1);
1481 JobFinish(job, &status);
1485 * Job cannot be restarted. Mark the table as full and
1486 * place the job back on the list of stopped jobs.
1488 DEBUGF(JOB, ("table full\n"));
1489 TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1491 DEBUGF(JOB, ("Job queue is full.\n"));
1498 * Start a target-creation process going for the target described
1499 * by the graph node gn.
1502 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1503 * if there isn't actually anything left to do for the job and
1504 * JOB_RUNNING if the job has been started.
1507 * A new Job node is created and added to the list of running
1508 * jobs. PMake is forked and a child shell created.
1511 JobStart(GNode *gn, int flags, Job *previous)
1513 Job *job; /* new job descriptor */
1514 char *argv[4]; /* Argument vector to shell */
1515 Boolean cmdsOK; /* true if the nodes commands were all right */
1516 Boolean noExec; /* Set true if we decide not to run the job */
1517 int tfd; /* File descriptor for temp file */
1519 char tfile[sizeof(TMPPAT)];
1522 JobPassSig(interrupted);
1525 if (previous != NULL) {
1526 previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1529 job = emalloc(sizeof(Job));
1534 job->tailCmds = NULL;
1537 * Set the initial value of the flags for this job based on the global
1538 * ones and the node's attributes... Any flags supplied by the caller
1539 * are also added to the field.
1542 if (Targ_Ignore(gn)) {
1543 job->flags |= JOB_IGNERR;
1545 if (Targ_Silent(gn)) {
1546 job->flags |= JOB_SILENT;
1548 job->flags |= flags;
1551 * Check the commands now so any attributes from .DEFAULT have a chance
1552 * to migrate to the node.
1554 if (!compatMake && (job->flags & JOB_FIRST)) {
1555 cmdsOK = Job_CheckCommands(gn, Error);
1561 * If the -n flag wasn't given, we open up OUR (not the child's)
1562 * temporary file to stuff commands in it. The thing is rd/wr so we
1563 * don't need to reopen it to feed it to the shell. If the -n flag
1564 * *was* given, we just set the file to be stdout. Cute, huh?
1566 if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1568 * We're serious here, but if the commands were bogus, we're
1575 strcpy(tfile, TMPPAT);
1576 if ((tfd = mkstemp(tfile)) == -1)
1577 Punt("Cannot create temp file: %s", strerror(errno));
1578 job->cmdFILE = fdopen(tfd, "w+");
1580 if (job->cmdFILE == NULL) {
1582 Punt("Could not open %s", tfile);
1584 fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1586 * Send the commands to the command file, flush all its
1587 * buffers then rewind and remove the thing.
1592 * Used to be backwards; replace when start doing multiple
1593 * commands per shell.
1597 * Be compatible: If this is the first time for this
1598 * node, verify its commands are ok and open the
1599 * commands list for sequential access by later
1600 * invocations of JobStart. Once that is done, we take
1601 * the next command off the list and print it to the
1602 * command file. If the command was an ellipsis, note
1603 * that there's nothing more to execute.
1605 if (job->flags & JOB_FIRST)
1606 gn->compat_command = Lst_First(&gn->commands);
1608 gn->compat_command =
1609 Lst_Succ(gn->compat_command);
1611 if (gn->compat_command == NULL ||
1612 JobPrintCommand(Lst_Datum(gn->compat_command), job))
1615 if (noExec && !(job->flags & JOB_FIRST)) {
1617 * If we're not going to execute anything, the
1618 * job is done and we need to close down the
1619 * various file descriptors we've opened for
1620 * output, then call JobDoOutput to catch the
1621 * final characters or send the file to the
1622 * screen... Note that the i/o streams are only
1623 * open if this isn't the first job. Note also
1624 * that this could not be done in
1625 * Job_CatchChildren b/c it wasn't clear if
1626 * there were more commands to execute or not...
1632 * We can do all the commands at once. hooray for sanity
1635 LST_FOREACH(ln, &gn->commands) {
1636 if (JobPrintCommand(Lst_Datum(ln), job))
1641 * If we didn't print out any commands to the shell
1642 * script, there's not much point in executing the
1645 if (numCommands == 0) {
1650 } else if (noExecute) {
1652 * Not executing anything -- just print all the commands to
1653 * stdout in one fell swoop. This will still set up
1654 * job->tailCmds correctly.
1656 if (lastNode != gn) {
1657 MESSAGE(stdout, gn);
1660 job->cmdFILE = stdout;
1663 * Only print the commands if they're ok, but don't die if
1664 * they're not -- just let the user know they're bad and keep
1665 * going. It doesn't do any harm in this case and may do
1669 LST_FOREACH(ln, &gn->commands) {
1670 if (JobPrintCommand(Lst_Datum(ln), job))
1675 * Don't execute the shell, thank you.
1681 * Just touch the target and note that no shell should be
1682 * executed. Set cmdFILE to stdout to make life easier. Check
1683 * the commands, too, but don't die if they're no good -- it
1684 * does no harm to keep working up the graph.
1686 job->cmdFILE = stdout;
1687 Job_Touch(gn, job->flags & JOB_SILENT);
1692 * If we're not supposed to execute a shell, don't.
1696 * Unlink and close the command file if we opened one
1698 if (job->cmdFILE != stdout) {
1699 if (job->cmdFILE != NULL)
1700 fclose(job->cmdFILE);
1706 * We only want to work our way up the graph if we aren't here
1707 * because the commands for the job were no good.
1710 if (aborting == 0) {
1711 for (ln = job->tailCmds; ln != NULL;
1712 ln = LST_NEXT(ln)) {
1713 Lst_AtEnd(&postCommands->commands,
1714 Buf_Peel(Var_Subst(Lst_Datum(ln),
1715 job->node, FALSE)));
1717 job->node->made = MADE;
1718 Make_Update(job->node);
1721 return(JOB_FINISHED);
1727 fflush(job->cmdFILE);
1731 * Set up the control arguments to the shell. This is based on the flags
1732 * set earlier for this job.
1734 JobMakeArgv(job, argv);
1737 * If we're using pipes to catch output, create the pipe by which we'll
1738 * get the shell's output. If we're using files, print out that we're
1739 * starting a job and then set up its temporary-file name.
1741 if (!compatMake || (job->flags & JOB_FIRST)) {
1746 Punt("Cannot create pipe: %s", strerror(errno));
1747 job->inPipe = fd[0];
1748 job->outPipe = fd[1];
1749 fcntl(job->inPipe, F_SETFD, 1);
1750 fcntl(job->outPipe, F_SETFD, 1);
1752 fprintf(stdout, "Remaking `%s'\n", gn->name);
1754 strcpy(job->outFile, TMPPAT);
1755 if ((job->outFd = mkstemp(job->outFile)) == -1)
1756 Punt("cannot create temp file: %s",
1758 fcntl(job->outFd, F_SETFD, 1);
1762 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL) && maxJobs != 0) {
1764 * We've hit the limit of concurrency, so put the job on hold
1765 * until some other job finishes. Note that the special jobs
1766 * (.BEGIN, .INTERRUPT and .END) may be run even when the
1767 * limit has been reached (e.g. when maxJobs == 0).
1771 DEBUGF(JOB, ("Can only run job locally.\n"));
1772 job->flags |= JOB_RESTART;
1773 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1775 if (nJobs >= maxJobs) {
1777 * If we're running this job as a special case
1778 * (see above), at least say the table is full.
1781 DEBUGF(JOB, ("Local job queue is full.\n"));
1785 return (JOB_RUNNING);
1789 JobOutput(Job *job, char *cp, char *endp, int msg)
1793 if (commandShell->noPrint) {
1794 ecp = strstr(cp, commandShell->noPrint);
1795 while (ecp != NULL) {
1798 if (msg && job->node != lastNode) {
1799 MESSAGE(stdout, job->node);
1800 lastNode = job->node;
1803 * The only way there wouldn't be a newline
1804 * after this line is if it were the last in
1805 * the buffer. However, since the non-printable
1806 * comes after it, there must be a newline, so
1807 * we don't print one.
1809 fprintf(stdout, "%s", cp);
1812 cp = ecp + strlen(commandShell->noPrint);
1815 * Still more to print, look again after
1816 * skipping the whitespace following the
1817 * non-printable command....
1820 while (*cp == ' ' || *cp == '\t' ||
1824 ecp = strstr(cp, commandShell->noPrint);
1835 * This function is called at different times depending on
1836 * whether the user has specified that output is to be collected
1837 * via pipes or temporary files. In the former case, we are called
1838 * whenever there is something to read on the pipe. We collect more
1839 * output from the given job and store it in the job's outBuf. If
1840 * this makes up a line, we print it tagged by the job's identifier,
1842 * If output has been collected in a temporary file, we open the
1843 * file and read it line by line, transfering it to our own
1844 * output channel until the file is empty. At which point we
1845 * remove the temporary file.
1846 * In both cases, however, we keep our figurative eye out for the
1847 * 'noPrint' line for the shell from which the output came. If
1848 * we recognize a line, we don't print it. If the command is not
1849 * alone on the line (the character after it is not \0 or \n), we
1850 * do print whatever follows it.
1853 * curPos may be shifted as may the contents of outBuf.
1856 JobDoOutput(Job *job, Boolean finish)
1858 Boolean gotNL = FALSE; /* true if got a newline */
1859 Boolean fbuf; /* true if our buffer filled up */
1860 int nr; /* number of bytes read */
1861 int i; /* auxiliary index into outBuf */
1862 int max; /* limit for i (end of current data) */
1863 int nRead; /* (Temporary) number of bytes read */
1864 FILE *oFILE; /* Stream pointer to shell's output file */
1869 * Read as many bytes as will fit in the buffer.
1875 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1876 JOB_BUFSIZE - job->curPos);
1878 * Check for interrupt here too, because the above read may
1879 * block when the child process is stopped. In this case the
1880 * interrupt will unblock it (we don't use SA_RESTART).
1883 JobPassSig(interrupted);
1886 DEBUGF(JOB, ("JobDoOutput(piperead)"));
1893 * If we hit the end-of-file (the job is dead), we must flush
1894 * its remaining output, so pretend we read a newline if
1895 * there's any output remaining in the buffer.
1896 * Also clear the 'finish' flag so we stop looping.
1898 if (nr == 0 && job->curPos != 0) {
1899 job->outBuf[job->curPos] = '\n';
1902 } else if (nr == 0) {
1907 * Look for the last newline in the bytes we just got. If there
1908 * is one, break out of the loop with 'i' as its index and
1911 max = job->curPos + nr;
1912 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1913 if (job->outBuf[i] == '\n') {
1916 } else if (job->outBuf[i] == '\0') {
1920 job->outBuf[i] = ' ';
1926 if (job->curPos == JOB_BUFSIZE) {
1928 * If we've run out of buffer space, we have
1929 * no choice but to print the stuff. sigh.
1935 if (gotNL || fbuf) {
1937 * Need to send the output to the screen. Null terminate
1938 * it first, overwriting the newline character if there
1939 * was one. So long as the line isn't one we should
1940 * filter (according to the shell description), we print
1941 * the line, preceded by a target banner if this target
1942 * isn't the same as the one for which we last printed
1943 * something. The rest of the data in the buffer are
1944 * then shifted down to the start of the buffer and
1945 * curPos is set accordingly.
1947 job->outBuf[i] = '\0';
1948 if (i >= job->curPos) {
1951 cp = JobOutput(job, job->outBuf,
1952 &job->outBuf[i], FALSE);
1955 * There's still more in that buffer. This time,
1956 * though, we know there's no newline at the
1957 * end, so we add one of our own free will.
1960 if (job->node != lastNode) {
1961 MESSAGE(stdout, job->node);
1962 lastNode = job->node;
1964 fprintf(stdout, "%s%s", cp,
1970 /* shift the remaining characters down */
1971 memcpy(job->outBuf, &job->outBuf[i + 1],
1973 job->curPos = max - (i + 1);
1977 * We have written everything out, so we just
1978 * start over from the start of the buffer.
1979 * No copying. No nothing.
1986 * If the finish flag is true, we must loop until we hit
1987 * end-of-file on the pipe. This is guaranteed to happen
1988 * eventually since the other end of the pipe is now
1989 * closed (we closed it explicitly and the child has
1990 * exited). When we do get an EOF, finish will be set
1991 * FALSE and we'll fall through and out.
1998 * We've been called to retrieve the output of the job from the
1999 * temporary file where it's been squirreled away. This consists
2000 * of opening the file, reading the output line by line, being
2001 * sure not to print the noPrint line for the shell we used,
2002 * then close and remove the temporary file. Very simple.
2004 * Change to read in blocks and do FindSubString type things
2005 * as for pipes? That would allow for "@echo -n..."
2007 oFILE = fopen(job->outFile, "r");
2008 if (oFILE != NULL) {
2009 fprintf(stdout, "Results of making %s:\n",
2013 while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2014 char *cp, *endp, *oendp;
2017 oendp = endp = inLine + strlen(inLine);
2018 if (endp[-1] == '\n') {
2021 cp = JobOutput(job, inLine, endp, FALSE);
2024 * There's still more in that buffer. This time,
2025 * though, we know there's no newline at the
2026 * end, so we add one of our own free will.
2028 fprintf(stdout, "%s", cp);
2030 if (endp != oendp) {
2031 fprintf(stdout, "\n");
2036 eunlink(job->outFile);
2043 * Handle the exit of a child. Called from Make_Make.
2046 * The job descriptor is removed from the list of children.
2049 * We do waits, blocking or not, according to the wisdom of our
2050 * caller, until there are no more children to report. For each
2051 * job, call JobFinish to finish things off. This will take care of
2052 * putting jobs on the stoppedJobs queue.
2055 Job_CatchChildren(Boolean block)
2057 pid_t pid; /* pid of dead child */
2058 Job *job; /* job descriptor for dead child */
2059 int status; /* Exit/termination status */
2062 * Don't even bother if we know there's no one around.
2069 pid = waitpid((pid_t)-1, &status,
2070 (block ? 0 : WNOHANG) | WUNTRACED);
2074 DEBUGF(JOB, ("Process %jd exited or stopped.\n",
2077 TAILQ_FOREACH(job, &jobs, link) {
2078 if (job->pid == pid)
2083 if (WIFSIGNALED(status) &&
2084 (WTERMSIG(status) == SIGCONT)) {
2085 TAILQ_FOREACH(job, &jobs, link) {
2086 if (job->pid == pid)
2090 Error("Resumed child (%jd) "
2091 "not in table", (intmax_t)pid);
2094 TAILQ_REMOVE(&stoppedJobs, job, link);
2096 Error("Child (%jd) not in table?",
2101 TAILQ_REMOVE(&jobs, job, link);
2103 if (fifoFd >= 0 && maxJobs > 1) {
2104 write(fifoFd, "+", 1);
2106 if (nJobs >= maxJobs)
2111 DEBUGF(JOB, ("Job queue is no longer full.\n"));
2116 JobFinish(job, &status);
2119 JobPassSig(interrupted);
2124 * Catch the output from our children, if we're using
2125 * pipes do so. Otherwise just block time until we get a
2126 * signal(most likely a SIGCHLD) since there's no point in
2127 * just spinning when there's nothing to do and the reaping
2128 * of a child can wait for a while.
2131 * Output is read from pipes if we're piping.
2132 * -----------------------------------------------------------------------
2136 Job_CatchOutput(int flag __unused)
2138 Job_CatchOutput(int flag)
2144 struct kevent kev[KEV_SIZE];
2147 struct timeval timeout;
2156 if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
2158 Punt("kevent: %s", strerror(errno));
2160 JobPassSig(interrupted);
2162 for (i = 0; i < nfds; i++) {
2163 if (kev[i].flags & EV_ERROR) {
2164 warnc(kev[i].data, "kevent");
2167 switch (kev[i].filter) {
2169 JobDoOutput(kev[i].udata, FALSE);
2173 * Just wake up and let
2174 * Job_CatchChildren() collect the
2183 timeout.tv_sec = SEL_SEC;
2184 timeout.tv_usec = SEL_USEC;
2185 if (flag && jobFull && fifoFd >= 0)
2186 FD_SET(fifoFd, &readfds);
2188 nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
2189 (fd_set *)NULL, &timeout);
2192 JobPassSig(interrupted);
2195 if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2199 job = TAILQ_FIRST(&jobs);
2200 while (nfds != 0 && job != NULL) {
2201 if (FD_ISSET(job->inPipe, &readfds)) {
2202 JobDoOutput(job, FALSE);
2205 job = TAILQ_NEXT(job, link);
2207 #endif /* !USE_KQUEUE */
2213 * Start the creation of a target. Basically a front-end for
2214 * JobStart used by the Make module.
2217 * Another job is started.
2223 JobStart(gn, 0, NULL);
2228 * Make a new copy of the shell structure including a copy of the strings
2229 * in it. This also defaults some fields in case they are NULL.
2232 * The function returns a pointer to the new shell structure.
2234 static struct Shell *
2235 JobCopyShell(const struct Shell *osh)
2239 nsh = emalloc(sizeof(*nsh));
2240 nsh->name = estrdup(osh->name);
2242 if (osh->echoOff != NULL)
2243 nsh->echoOff = estrdup(osh->echoOff);
2245 nsh->echoOff = NULL;
2246 if (osh->echoOn != NULL)
2247 nsh->echoOn = estrdup(osh->echoOn);
2250 nsh->hasEchoCtl = osh->hasEchoCtl;
2252 if (osh->noPrint != NULL)
2253 nsh->noPrint = estrdup(osh->noPrint);
2255 nsh->noPrint = NULL;
2257 nsh->hasErrCtl = osh->hasErrCtl;
2258 if (osh->errCheck == NULL)
2259 nsh->errCheck = estrdup("");
2261 nsh->errCheck = estrdup(osh->errCheck);
2262 if (osh->ignErr == NULL)
2263 nsh->ignErr = estrdup("%s");
2265 nsh->ignErr = estrdup(osh->ignErr);
2267 if (osh->echo == NULL)
2268 nsh->echo = estrdup("");
2270 nsh->echo = estrdup(osh->echo);
2272 if (osh->exit == NULL)
2273 nsh->exit = estrdup("");
2275 nsh->exit = estrdup(osh->exit);
2282 * Free a shell structure and all associated strings.
2285 JobFreeShell(struct Shell *sh)
2305 if (commandShell == NULL)
2306 commandShell = JobMatchShell(shells[DEFSHELL].name);
2308 if (shellPath == NULL) {
2310 * The user didn't specify a shell to use, so we are using the
2311 * default one... Both the absolute path and the last component
2312 * must be set. The last component is taken from the 'name'
2313 * field of the default shell description pointed-to by
2314 * commandShell. All default shells are located in
2317 shellName = commandShell->name;
2318 shellPath = str_concat(PATH_DEFSHELLDIR, shellName,
2325 * Initialize the process module, given a maximum number of jobs.
2328 * lists and counters are initialized
2331 Job_Init(int maxproc)
2333 GNode *begin; /* node for commands to do at the very start */
2335 struct sigaction sa;
2338 env = getenv("MAKE_JOBS_FIFO");
2340 if (env == NULL && maxproc > 1) {
2342 * We did not find the environment variable so we are the
2343 * leader. Create the fifo, open it, write one char per
2344 * allowed job into the pipe.
2347 if (!mkfifo(fifoName, 0600)) {
2348 fifoFd = open(fifoName, O_RDWR | O_NONBLOCK, 0);
2351 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2353 setenv("MAKE_JOBS_FIFO", env, 1);
2354 while (maxproc-- > 0) {
2355 write(fifoFd, "+", 1);
2357 /* The master make does not get a magic token */
2366 } else if (env != NULL) {
2368 * We had the environment variable so we are a slave.
2369 * Open fifo and give ourselves a magic token which represents
2370 * the token our parent make has grabbed to start his make
2371 * process. Otherwise the sub-makes would gobble up tokens and
2372 * the proper number of tokens to specify to -j would depend
2373 * on the depth of the tree and the order of execution.
2375 fifoFd = open(env, O_RDWR, 0);
2377 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2394 if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2396 * If only one job can run at a time, there's no need for a
2397 * banner, no is there?
2407 * Catch the four signals that POSIX specifies if they aren't ignored.
2408 * JobCatchSignal will just set global variables and hope someone
2409 * else is going to handle the interrupt.
2411 sa.sa_handler = JobCatchSig;
2412 sigemptyset(&sa.sa_mask);
2415 if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2416 sigaction(SIGINT, &sa, NULL);
2418 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2419 sigaction(SIGHUP, &sa, NULL);
2421 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2422 sigaction(SIGQUIT, &sa, NULL);
2424 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2425 sigaction(SIGTERM, &sa, NULL);
2428 * There are additional signals that need to be caught and passed if
2429 * either the export system wants to be told directly of signals or if
2430 * we're giving each job its own process group (since then it won't get
2431 * signals from the terminal driver as we own the terminal)
2433 #if defined(USE_PGRP)
2434 if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2435 sigaction(SIGTSTP, &sa, NULL);
2437 if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2438 sigaction(SIGTTOU, &sa, NULL);
2440 if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2441 sigaction(SIGTTIN, &sa, NULL);
2443 if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2444 sigaction(SIGWINCH, &sa, NULL);
2449 if ((kqfd = kqueue()) == -1) {
2450 Punt("kqueue: %s", strerror(errno));
2454 begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2456 if (begin != NULL) {
2457 JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2460 Job_CatchChildren(!usePipes);
2463 postCommands = Targ_FindNode(".END", TARG_CREATE);
2468 * See if the job table is full. It is considered full if it is OR
2469 * if we are in the process of aborting OR if we have
2470 * reached/exceeded our local quota. This prevents any more jobs
2474 * TRUE if the job table is full, FALSE otherwise
2484 if (fifoFd >= 0 && jobFull) {
2485 i = read(fifoFd, &c, 1);
2496 * See if the job table is empty. Because the local concurrency may
2497 * be set to 0, it is possible for the job table to become empty,
2498 * while the list of stoppedJobs remains non-empty. In such a case,
2499 * we want to restart as many jobs as we can.
2502 * TRUE if it is. FALSE if it ain't.
2508 if (!TAILQ_EMPTY(&stoppedJobs) && !aborting) {
2510 * The job table is obviously not full if it has no
2511 * jobs in it...Try and restart the stopped jobs.
2526 * Find a matching shell in 'shells' given its final component.
2529 * A pointer to a freshly allocated Shell structure with a copy
2530 * of the static structure or NULL if no shell with the given name
2533 static struct Shell *
2534 JobMatchShell(const char *name)
2536 const struct CShell *sh; /* Pointer into shells table */
2539 for (sh = shells; sh < shells + __arysize(shells); sh++)
2540 if (strcmp(sh->name, name) == 0)
2543 if (sh == shells + __arysize(shells))
2547 nsh = emalloc(sizeof(*nsh));
2549 nsh->name = estrdup(sh->name);
2550 nsh->echoOff = estrdup(sh->echoOff);
2551 nsh->echoOn = estrdup(sh->echoOn);
2552 nsh->hasEchoCtl = sh->hasEchoCtl;
2553 nsh->noPrint = estrdup(sh->noPrint);
2554 nsh->hasErrCtl = sh->hasErrCtl;
2555 nsh->errCheck = estrdup(sh->errCheck);
2556 nsh->ignErr = estrdup(sh->ignErr);
2557 nsh->echo = estrdup(sh->echo);
2558 nsh->exit = estrdup(sh->exit);
2565 * Parse a shell specification and set up commandShell, shellPath
2566 * and shellName appropriately.
2569 * FAILURE if the specification was incorrect.
2572 * commandShell points to a Shell structure (either predefined or
2573 * created from the shell spec), shellPath is the full path of the
2574 * shell described by commandShell, while shellName is just the
2575 * final component of shellPath.
2578 * A shell specification consists of a .SHELL target, with dependency
2579 * operator, followed by a series of blank-separated words. Double
2580 * quotes can be used to use blanks in words. A backslash escapes
2581 * anything (most notably a double-quote and a space) and
2582 * provides the functionality it does in C. Each word consists of
2583 * keyword and value separated by an equal sign. There should be no
2584 * unnecessary spaces in the word. The keywords are as follows:
2585 * name Name of shell.
2586 * path Location of shell. Overrides "name" if given
2587 * quiet Command to turn off echoing.
2588 * echo Command to turn echoing on
2589 * filter Result of turning off echoing that shouldn't be
2591 * echoFlag Flag to turn echoing on at the start
2592 * errFlag Flag to turn error checking on at the start
2593 * hasErrCtl True if shell has error checking control
2594 * check Command to turn on error checking if hasErrCtl
2595 * is TRUE or template of command to echo a command
2596 * for which error checking is off if hasErrCtl is
2598 * ignore Command to turn off error checking if hasErrCtl
2599 * is TRUE or template of command to execute a
2600 * command so as to ignore any errors it returns if
2601 * hasErrCtl is FALSE.
2604 Job_ParseShell(char *line)
2612 Boolean fullSpec = FALSE;
2613 struct Shell newShell;
2616 while (isspace((unsigned char)*line)) {
2619 words = brk_string(line, &wordCount, TRUE);
2621 memset(&newShell, 0, sizeof(newShell));
2625 * Parse the specification by keyword but skip the first word - it
2626 * is not set by brk_string.
2631 for (argc = wordCount, argv = words; argc != 0; argc--, argv++) {
2633 * Split keyword and value
2635 if ((eq = strchr(*argv, '=')) == NULL) {
2636 Parse_Error(PARSE_FATAL, "missing '=' in shell "
2637 "specification keyword '%s'", *argv);
2642 if (strcmp(*argv, "path") == 0) {
2644 } else if (strcmp(*argv, "name") == 0) {
2646 } else if (strcmp(*argv, "quiet") == 0) {
2647 newShell.echoOff = eq;
2649 } else if (strcmp(*argv, "echo") == 0) {
2650 newShell.echoOn = eq;
2652 } else if (strcmp(*argv, "filter") == 0) {
2653 newShell.noPrint = eq;
2655 } else if (strcmp(*argv, "echoFlag") == 0) {
2658 } else if (strcmp(*argv, "errFlag") == 0) {
2661 } else if (strcmp(*argv, "hasErrCtl") == 0) {
2662 newShell.hasErrCtl = (*eq == 'Y' || *eq == 'y' ||
2663 *eq == 'T' || *eq == 't');
2665 } else if (strcmp(*argv, "check") == 0) {
2666 newShell.errCheck = eq;
2668 } else if (strcmp(*argv, "ignore") == 0) {
2669 newShell.ignErr = eq;
2672 Parse_Error(PARSE_FATAL, "unknown keyword in shell "
2673 "specification '%s'", *argv);
2679 * Some checks (could be more)
2682 if ((newShell.echoOn != NULL) ^ (newShell.echoOff != NULL))
2683 Parse_Error(PARSE_FATAL, "Shell must have either both "
2684 "echoOff and echoOn or none of them");
2686 if (newShell.echoOn != NULL && newShell.echoOff)
2687 newShell.hasEchoCtl = TRUE;
2692 * If no path was given, the user wants one of the pre-defined
2693 * shells, yes? So we find the one s/he wants with the help of
2694 * JobMatchShell and set things up the right way. shellPath
2695 * will be set up by Job_Init.
2697 if (newShell.name == NULL) {
2698 Parse_Error(PARSE_FATAL,
2699 "Neither path nor name specified");
2702 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2703 Parse_Error(PARSE_FATAL, "%s: no matching shell",
2710 * The user provided a path. If s/he gave nothing else
2711 * (fullSpec is FALSE), try and find a matching shell in the
2712 * ones we know of. Else we just take the specification at its
2713 * word and copy it to a new location. In either case, we need
2714 * to record the path the user gave for the shell.
2717 shellPath = estrdup(path);
2718 if (newShell.name == NULL) {
2719 /* get the base name as the name */
2720 path = strrchr(path, '/');
2726 newShell.name = path;
2730 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2731 Parse_Error(PARSE_FATAL,
2732 "%s: no matching shell", newShell.name);
2736 sh = JobCopyShell(&newShell);
2740 /* set the new shell */
2741 JobFreeShell(commandShell);
2744 shellName = commandShell->name;
2751 * Handle the receipt of an interrupt.
2754 * All children are killed. Another job will be started if the
2755 * .INTERRUPT target was given.
2758 JobInterrupt(int runINTERRUPT, int signo)
2760 Job *job; /* job descriptor in that element */
2761 GNode *interrupt; /* the node describing the .INTERRUPT target */
2763 aborting = ABORT_INTERRUPT;
2765 TAILQ_FOREACH(job, &jobs, link) {
2766 if (!Targ_Precious(job->node)) {
2767 char *file = (job->node->path == NULL ?
2768 job->node->name : job->node->path);
2770 if (!noExecute && eunlink(file) != -1) {
2771 Error("*** %s removed", file);
2775 DEBUGF(JOB, ("JobInterrupt passing signal to child "
2776 "%jd.\n", (intmax_t)job->pid));
2777 KILL(job->pid, signo);
2781 if (runINTERRUPT && !touchFlag) {
2783 * clear the interrupted flag because we would get an
2784 * infinite loop otherwise.
2788 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2789 if (interrupt != NULL) {
2790 ignoreErrors = FALSE;
2792 JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
2795 Job_CatchChildren(!usePipes);
2803 * Do final processing such as the running of the commands
2804 * attached to the .END target.
2807 * Number of errors reported.
2813 if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
2815 Error("Errors reported so .END ignored");
2817 JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
2821 Job_CatchChildren(!usePipes);
2836 * Waits for all running jobs to finish and returns. Sets 'aborting'
2837 * to ABORT_WAIT to prevent other jobs from starting.
2840 * Currently running jobs finish.
2846 aborting = ABORT_WAIT;
2847 while (nJobs != 0) {
2849 Job_CatchChildren(!usePipes);
2856 * Abort all currently running jobs without handling output or anything.
2857 * This function is to be called only in the event of a major
2858 * error. Most definitely NOT to be called from JobInterrupt.
2861 * All children are killed, not just the firstborn
2866 Job *job; /* the job descriptor in that element */
2869 aborting = ABORT_ERROR;
2872 TAILQ_FOREACH(job, &jobs, link) {
2874 * kill the child process with increasingly drastic
2875 * signals to make darn sure it's dead.
2877 KILL(job->pid, SIGINT);
2878 KILL(job->pid, SIGKILL);
2883 * Catch as many children as want to report in at first, then give up
2885 while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2891 * Tries to restart stopped jobs if there are slots available.
2892 * Note that this tries to restart them regardless of pending errors.
2893 * It's not good to leave stopped jobs lying around!
2896 * Resumes(and possibly migrates) jobs.
2899 JobRestartJobs(void)
2903 while (!jobFull && (job = TAILQ_FIRST(&stoppedJobs)) != NULL) {
2904 DEBUGF(JOB, ("Job queue is not full. "
2905 "Restarting a stopped job.\n"));
2906 TAILQ_REMOVE(&stoppedJobs, job, link);
2913 * Execute the command in cmd, and return the output of that command
2917 * A string containing the output of the command, or the empty string
2918 * If error is not NULL, it contains the reason for the command failure
2921 * The string must be freed by the caller.
2924 Cmd_Exec(const char *cmd, const char **error)
2926 int fds[2]; /* Pipe streams */
2927 int cpid; /* Child PID */
2928 int pid; /* PID from wait() */
2929 int status; /* command exit status */
2930 Buffer *buf; /* buffer to store the result */
2936 if (shellPath == NULL)
2939 * Open a pipe for fetching its output
2941 if (pipe(fds) == -1) {
2942 *error = "Couldn't create pipe for \"%s\"";
2949 if ((cpid = vfork()) == -1) {
2950 *error = "Couldn't exec \"%s\"";
2952 } else if (cpid == 0) {
2956 /* Set up arguments for shell */
2957 argv[0] = shellName;
2963 * Close input side of pipe
2968 * Duplicate the output stream to the shell's output, then
2969 * shut the extra thing down.
2974 /* Note we don't fetch the error stream...why not? Why? */
2975 ps.merge_errors = 0;
2978 ProcExec(&ps, argv);
2983 * No need for the writing half
2988 char result[BUFSIZ];
2990 rcnt = read(fds[0], result, sizeof(result));
2992 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
2993 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
2996 *error = "Error reading shell's output for \"%s\"";
2999 * Close the input side of the pipe.
3004 * Wait for the process to exit.
3006 while (((pid = wait(&status)) != cpid) && (pid >= 0))
3010 *error = "\"%s\" returned non-zero status";
3012 Buf_StripNewlines(buf);
3021 * The routines in this file implement the full-compatibility
3022 * mode of PMake. Most of the special functionality of PMake
3023 * is available in this mode. Things not supported:
3024 * - different shells.
3025 * - friendly variable substitution.
3028 * Compat_Run Initialize things for this module and recreate
3029 * thems as need creatin'
3033 * The following array is used to make a fast determination of which
3034 * characters are interpreted specially by the shell. If a command
3035 * contains any of these characters, it is executed by the shell, not
3038 static char meta[256];
3040 static GNode *curTarg = NULL;
3041 static GNode *ENDNode;
3042 static sig_atomic_t interrupted;
3047 const char *cp; /* Pointer to string of shell meta-characters */
3049 for (cp = "#=|^(){};&<>*?[]:$`\\\n"; *cp != '\0'; cp++) {
3050 meta[(unsigned char)*cp] = 1;
3053 * The null character serves as a sentinel in the string.
3059 * Interrupt handler - set flag and defer handling to the main code
3062 CompatCatchSig(int signo)
3065 interrupted = signo;
3069 *-----------------------------------------------------------------------
3070 * CompatInterrupt --
3071 * Interrupt the creation of the current target and remove it if
3072 * it ain't precious.
3078 * The target is removed and the process exits. If .INTERRUPT exists,
3079 * its commands are run first WITH INTERRUPTS IGNORED..
3081 *-----------------------------------------------------------------------
3084 CompatInterrupt(int signo)
3087 sigset_t nmask, omask;
3090 sigemptyset(&nmask);
3091 sigaddset(&nmask, SIGINT);
3092 sigaddset(&nmask, SIGTERM);
3093 sigaddset(&nmask, SIGHUP);
3094 sigaddset(&nmask, SIGQUIT);
3095 sigprocmask(SIG_SETMASK, &nmask, &omask);
3097 /* prevent recursion in evaluation of .INTERRUPT */
3100 if (curTarg != NULL && !Targ_Precious(curTarg)) {
3102 char *file = Var_Value(TARGET, curTarg, &p1);
3104 if (!noExecute && eunlink(file) != -1) {
3105 printf("*** %s removed\n", file);
3111 * Run .INTERRUPT only if hit with interrupt signal
3113 if (signo == SIGINT) {
3114 gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
3116 LST_FOREACH(ln, &gn->commands) {
3117 if (Compat_RunCommand(Lst_Datum(ln), gn))
3123 sigprocmask(SIG_SETMASK, &omask, NULL);
3125 if (signo == SIGQUIT)
3127 signal(signo, SIG_DFL);
3128 kill(getpid(), signo);
3132 *-----------------------------------------------------------------------
3136 * Returns 1 if a specified line must be executed by the shell,
3137 * and 0 if it can be run via execvp().
3140 * Uses brk_string so destroys the contents of argv.
3142 *-----------------------------------------------------------------------
3145 shellneed(char *cmd)
3147 static const char *sh_builtin[] = {
3148 "alias", "cd", "eval", "exec",
3149 "exit", "read", "set", "ulimit",
3150 "unalias", "umask", "unset", "wait",
3156 av = brk_string(cmd, NULL, TRUE);
3157 for (p = sh_builtin; *p != 0; p++)
3158 if (strcmp(av[1], *p) == 0)
3164 *-----------------------------------------------------------------------
3165 * Compat_RunCommand --
3166 * Execute the next command for a target. If the command returns an
3167 * error, the node's made field is set to ERROR and creation stops.
3168 * The node from which the command came is also given.
3171 * 0 if the command succeeded, 1 if an error occurred.
3174 * The node's 'made' field may be set to ERROR.
3176 *-----------------------------------------------------------------------
3179 Compat_RunCommand(char *cmd, GNode *gn)
3181 char *cmdStart; /* Start of expanded command */
3183 Boolean silent; /* Don't print command */
3184 Boolean doit; /* Execute even in -n */
3185 Boolean errCheck; /* Check errors */
3186 int reason; /* Reason for child's death */
3187 int status; /* Description of child's death */
3188 int cpid; /* Child actually found */
3189 ReturnStatus rstat; /* Status of fork */
3190 LstNode *cmdNode; /* Node where current command is located */
3191 char **av; /* Argument vector for thing to exec */
3192 char *cmd_save; /* saved cmd */
3195 * Avoid clobbered variable warnings by forcing the compiler
3196 * to ``unregister'' variables
3202 silent = gn->type & OP_SILENT;
3203 errCheck = !(gn->type & OP_IGNORE);
3206 cmdNode = Lst_Member(&gn->commands, cmd);
3207 cmdStart = Buf_Peel(Var_Subst(cmd, gn, FALSE));
3210 * brk_string will return an argv with a NULL in av[0], thus causing
3211 * execvp() to choke and die horribly. Besides, how can we execute a
3212 * null command? In any case, we warn the user that the command
3213 * expanded to nothing (is this the right thing to do?).
3215 if (*cmdStart == '\0') {
3217 Error("%s expands to empty string", cmd);
3222 Lst_Replace(cmdNode, cmdStart);
3224 if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
3225 Lst_AtEnd(&ENDNode->commands, cmdStart);
3227 } else if (strcmp(cmdStart, "...") == 0) {
3228 gn->type |= OP_SAVE_CMDS;
3232 while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
3236 silent = DEBUG(LOUD) ? FALSE : TRUE;
3245 if (!meta[0]) /* we came here from jobs */
3252 while (isspace((unsigned char)*cmd))
3256 * Search for meta characters in the command. If there are no meta
3257 * characters, there's no need to execute a shell to execute the
3260 for (cp = cmd; !meta[(unsigned char)*cp]; cp++)
3264 * Print the command before echoing if we're not supposed to be quiet
3265 * for this one. We also print the command if -n given, but not if '+'.
3267 if (!silent || (noExecute && !doit)) {
3268 printf("%s\n", cmd);
3273 * If we're not supposed to execute any commands, this is as far as
3276 if (!doit && noExecute) {
3282 * If *cp isn't the null character, we hit a "meta" character
3283 * and need to pass the command off to the shell. We give the
3284 * shell the -e flag as well as -c if it's supposed to exit
3285 * when it hits an error.
3287 static char *shargv[4];
3289 shargv[0] = shellPath;
3290 shargv[1] = (errCheck ? "-ec" : "-c");
3295 } else if (shellneed(cmd)) {
3297 * This command must be passed by the shell for other reasons..
3298 * or.. possibly not at all.
3300 static char *shargv[4];
3302 shargv[0] = shellPath;
3303 shargv[1] = (errCheck ? "-ec" : "-c");
3310 * No meta-characters, so no need to exec a shell. Break the
3311 * command into words to form an argument vector we can execute.
3312 * brk_string sticks our name in av[0], so we have to
3315 av = brk_string(cmd, NULL, TRUE);
3320 * Fork and execute the single command. If the fork fails, we abort.
3322 if ((cpid = vfork()) == -1) {
3323 Fatal("Could not fork");
3325 } else if (cpid == 0) {
3328 ps.merge_errors = 0;
3336 * we need to print out the command associated with this
3337 * Gnode in Targ_PrintCmd from Targ_PrintGraph when debugging
3338 * at level g2, in main(), Fatal() and DieHorribly(),
3339 * therefore do not free it when debugging.
3341 if (!DEBUG(GRAPH2)) {
3343 Lst_Replace(cmdNode, cmd_save);
3346 * The child is off and running. Now all we can do is wait...
3349 while ((rstat = wait(&reason)) != cpid) {
3350 if (interrupted || (rstat == -1 && errno != EINTR)) {
3355 CompatInterrupt(interrupted);
3358 if (WIFSTOPPED(reason)) {
3360 status = WSTOPSIG(reason);
3361 } else if (WIFEXITED(reason)) {
3363 status = WEXITSTATUS(reason);
3365 printf("*** Error code %d",
3370 status = WTERMSIG(reason);
3371 printf("*** Signal %d", status);
3374 if (!WIFEXITED(reason) || status != 0) {
3383 printf(" (continuing)\n");
3387 * Continue executing
3388 * commands for this target.
3389 * If we return 0, this will
3392 printf(" (ignored)\n");
3398 Fatal("error in wait: %d", rstat);
3408 *-----------------------------------------------------------------------
3410 * Make a target, given the parent, to abort if necessary.
3413 * If an error is detected and not being ignored, the process exits.
3415 *-----------------------------------------------------------------------
3418 CompatMake(GNode *gn, GNode *pgn)
3422 if (gn->type & OP_USE) {
3423 Make_HandleUse(gn, pgn);
3425 } else if (gn->made == UNMADE) {
3427 * First mark ourselves to be made, then apply whatever
3428 * transformations the suffix module thinks are necessary.
3429 * Once that's done, we can descend and make all our children.
3430 * If any of them has an error but the -k flag was given, our
3431 * 'make' field will be set FALSE again. This is our signal to
3432 * not attempt to do anything but abort our parent as well.
3435 gn->made = BEINGMADE;
3437 LST_FOREACH(ln, &gn->children)
3438 CompatMake(Lst_Datum(ln), gn);
3445 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3447 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
3452 * All the children were made ok. Now cmtime contains the
3453 * modification time of the newest child, we need to find out
3454 * if we exist and when we were modified last. The criteria for
3455 * datedness are defined by the Make_OODate function.
3457 DEBUGF(MAKE, ("Examining %s...", gn->name));
3458 if (!Make_OODate(gn)) {
3459 gn->made = UPTODATE;
3460 DEBUGF(MAKE, ("up-to-date.\n"));
3463 DEBUGF(MAKE, ("out-of-date.\n"));
3467 * If the user is just seeing if something is out-of-date,
3468 * exit now to tell him/her "yes".
3475 * We need to be re-made. We also have to make sure we've got
3476 * a $? variable. To be nice, we also define the $> variable
3477 * using Make_DoAllVar().
3482 * Alter our type to tell if errors should be ignored or things
3483 * should not be printed so Compat_RunCommand knows what to do.
3485 if (Targ_Ignore(gn)) {
3486 gn->type |= OP_IGNORE;
3488 if (Targ_Silent(gn)) {
3489 gn->type |= OP_SILENT;
3492 if (Job_CheckCommands(gn, Fatal)) {
3494 * Our commands are ok, but we still have to worry
3495 * about the -t flag...
3499 LST_FOREACH(ln, &gn->commands) {
3500 if (Compat_RunCommand(Lst_Datum(ln),
3506 Job_Touch(gn, gn->type & OP_SILENT);
3512 if (gn->made != ERROR) {
3514 * If the node was made successfully, mark it so, update
3515 * its modification time and timestamp all its parents.
3516 * Note that for .ZEROTIME targets, the timestamping
3517 * isn't done. This is to keep its state from affecting
3518 * that of its parent.
3523 * We can't re-stat the thing, but we can at least take
3524 * care of rules where a target depends on a source that
3525 * actually creates the target, but only if it has
3533 * mv y.tab.o parse.o
3534 * cmp -s y.tab.h parse.h || mv y.tab.h parse.h
3536 * In this case, if the definitions produced by yacc
3537 * haven't changed from before, parse.h won't have been
3538 * updated and gn->mtime will reflect the current
3539 * modification time for parse.h. This is something of a
3540 * kludge, I admit, but it's a useful one..
3542 * XXX: People like to use a rule like
3546 * To force things that depend on FRC to be made, so we
3547 * have to check for gn->children being empty as well...
3549 if (!Lst_IsEmpty(&gn->commands) ||
3550 Lst_IsEmpty(&gn->children)) {
3555 * This is what Make does and it's actually a good
3556 * thing, as it allows rules like
3558 * cmp -s y.tab.h parse.h || cp y.tab.h parse.h
3560 * to function as intended. Unfortunately, thanks to
3561 * the stateless nature of NFS (and the speed of this
3562 * program), there are times when the modification time
3563 * of a file created on a remote machine will not be
3564 * modified before the stat() implied by the Dir_MTime
3565 * occurs, thus leading us to believe that the file
3566 * is unchanged, wreaking havoc with files that depend
3569 * I have decided it is better to make too much than to
3570 * make too little, so this stuff is commented out
3571 * unless you're sure it's ok.
3574 if (noExecute || Dir_MTime(gn) == 0) {
3577 if (gn->cmtime > gn->mtime)
3578 gn->mtime = gn->cmtime;
3579 DEBUGF(MAKE, ("update time: %s\n",
3580 Targ_FmtTime(gn->mtime)));
3582 if (!(gn->type & OP_EXEC)) {
3583 pgn->childMade = TRUE;
3584 Make_TimeStamp(pgn, gn);
3587 } else if (keepgoing) {
3593 printf("\n\nStop in %s.\n",
3594 Var_Value(".CURDIR", gn, &p1));
3598 } else if (gn->made == ERROR) {
3600 * Already had an error when making this beastie. Tell the
3605 if (Lst_Member(&gn->iParents, pgn) != NULL) {
3607 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
3612 Error("Graph cycles through %s\n", gn->name);
3617 if ((gn->type & OP_EXEC) == 0) {
3618 pgn->childMade = TRUE;
3619 Make_TimeStamp(pgn, gn);
3623 if ((gn->type & OP_EXEC) == 0) {
3624 Make_TimeStamp(pgn, gn);
3636 *-----------------------------------------------------------------------
3638 * Start making again, given a list of target nodes.
3646 *-----------------------------------------------------------------------
3649 Compat_Run(Lst *targs)
3651 GNode *gn = NULL; /* Current root target */
3652 int error_cnt; /* Number of targets not remade due to errors */
3656 Shell_Init(); /* Set up shell. */
3658 if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
3659 signal(SIGINT, CompatCatchSig);
3661 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
3662 signal(SIGTERM, CompatCatchSig);
3664 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
3665 signal(SIGHUP, CompatCatchSig);
3667 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
3668 signal(SIGQUIT, CompatCatchSig);
3671 ENDNode = Targ_FindNode(".END", TARG_CREATE);
3673 * If the user has defined a .BEGIN target, execute the commands
3677 gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
3679 LST_FOREACH(ln, &gn->commands) {
3680 if (Compat_RunCommand(Lst_Datum(ln), gn))
3683 if (gn->made == ERROR) {
3684 printf("\n\nStop.\n");
3691 * For each entry in the list of targets to create, call CompatMake on
3692 * it to create the thing. CompatMake will leave the 'made' field of gn
3693 * in one of several states:
3694 * UPTODATE gn was already up-to-date
3695 * MADE gn was recreated successfully
3696 * ERROR An error occurred while gn was being created
3697 * ABORTED gn was not remade because one of its inferiors
3698 * could not be made due to errors.
3701 while (!Lst_IsEmpty(targs)) {
3702 gn = Lst_DeQueue(targs);
3705 if (gn->made == UPTODATE) {
3706 printf("`%s' is up to date.\n", gn->name);
3707 } else if (gn->made == ABORTED) {
3708 printf("`%s' not remade because of errors.\n",
3715 * If the user has defined a .END target, run its commands.
3717 if (error_cnt == 0) {
3718 LST_FOREACH(ln, &ENDNode->commands) {
3719 if (Compat_RunCommand(Lst_Datum(ln), gn))