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.54 2005/04/16 10:34:26 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 * Job Table definitions.
136 * The job "table" is kept as a linked Lst in 'jobs', with the number of
137 * active jobs maintained in the 'nJobs' variable. At no time will this
138 * exceed the value of 'maxJobs', initialized by the Job_Init function.
140 * When a job is finished, the Make_Update function is called on each of the
141 * parents of the node which was just remade. This takes care of the upward
142 * traversal of the dependency graph.
144 #define JOB_BUFSIZE 1024
146 pid_t pid; /* The child's process ID */
148 struct GNode *node; /* The target the child is making */
151 * A LstNode for the first command to be saved after the job completes.
152 * This is NULL if there was no "..." in the job's commands.
157 * An FILE* for writing out the commands. This is only
158 * used before the job is actually started.
163 * A word of flags which determine how the module handles errors,
164 * echoing, etc. for the job
166 short flags; /* Flags to control treatment of job */
167 #define JOB_IGNERR 0x001 /* Ignore non-zero exits */
168 #define JOB_SILENT 0x002 /* no output */
169 #define JOB_SPECIAL 0x004 /* Target is a special one. i.e. run it locally
170 * if we can't export it and maxLocal is 0 */
171 #define JOB_IGNDOTS 0x008 /* Ignore "..." lines when processing
173 #define JOB_FIRST 0x020 /* Job is first job for the node */
174 #define JOB_RESTART 0x080 /* Job needs to be completely restarted */
175 #define JOB_RESUME 0x100 /* Job needs to be resumed b/c it stopped,
177 #define JOB_CONTINUING 0x200 /* We are in the process of resuming this job.
178 * Used to avoid infinite recursion between
179 * JobFinish and JobRestart */
181 /* union for handling shell's output */
184 * This part is used when usePipes is true.
185 * The output is being caught via a pipe and the descriptors
186 * of our pipe, an array in which output is line buffered and
187 * the current position in that buffer are all maintained for
192 * Input side of pipe associated with
193 * job's output channel
198 * Output side of pipe associated with job's
204 * Buffer for storing the output of the
207 char op_outBuf[JOB_BUFSIZE + 1];
209 /* Current position in op_outBuf */
214 * If usePipes is false the output is routed to a temporary
215 * file and all that is kept is the name of the file and the
216 * descriptor open to the file.
219 /* Name of file to which shell output was rerouted */
220 char of_outFile[sizeof(TMPPAT)];
223 * Stream open to the output file. Used to funnel all
224 * from a single job to one file while still allowing
225 * multiple shell invocations
230 } output; /* Data for tracking a shell's output */
232 TAILQ_ENTRY(Job) link; /* list link */
235 #define outPipe output.o_pipe.op_outPipe
236 #define inPipe output.o_pipe.op_inPipe
237 #define outBuf output.o_pipe.op_outBuf
238 #define curPos output.o_pipe.op_curPos
239 #define outFile output.o_file.of_outFile
240 #define outFd output.o_file.of_outFd
242 TAILQ_HEAD(JobList, Job);
245 * Shell Specifications:
247 * Some special stuff goes on if a shell doesn't have error control. In such
248 * a case, errCheck becomes a printf template for echoing the command,
249 * should echoing be on and ignErr becomes another printf template for
250 * executing the command while ignoring the return status. If either of these
251 * strings is empty when hasErrCtl is FALSE, the command will be executed
252 * anyway as is and if it causes an error, so be it.
254 #define DEF_SHELL_STRUCT(TAG, CONST) \
257 * the name of the shell. For Bourne and C shells, this is used \
258 * only to find the shell description when used as the single \
259 * source of a .SHELL target. For user-defined shells, this is \
260 * the full path of the shell. \
264 /* True if both echoOff and echoOn defined */ \
265 Boolean hasEchoCtl; \
267 CONST char *echoOff; /* command to turn off echo */ \
268 CONST char *echoOn; /* command to turn it back on */\
271 * What the shell prints, and its length, when given the \
272 * echo-off command. This line will not be printed when \
273 * received from the shell. This is usually the command which \
274 * was executed to turn off echoing \
276 CONST char *noPrint; \
278 /* set if can control error checking for individual commands */ \
281 /* string to turn error checking on */ \
282 CONST char *errCheck; \
284 /* string to turn off error checking */ \
285 CONST char *ignErr; \
287 CONST char *echo; /* command line flag: echo commands */ \
288 CONST char *exit; /* command line flag: exit on error */ \
291 DEF_SHELL_STRUCT(Shell,);
292 DEF_SHELL_STRUCT(CShell, const);
295 * error handling variables
297 static int errors = 0; /* number of errors reported */
298 static int aborting = 0; /* why is the make aborting? */
299 #define ABORT_ERROR 1 /* Because of an error */
300 #define ABORT_INTERRUPT 2 /* Because it was interrupted */
301 #define ABORT_WAIT 3 /* Waiting for jobs to finish */
304 * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
305 * is a char! So when we go above 127 we turn negative!
307 #define FILENO(a) ((unsigned)fileno(a))
310 * post-make command processing. The node postCommands is really just the
311 * .END target but we keep it around to avoid having to search for it
314 static GNode *postCommands;
317 * The number of commands actually printed for a target. Should this
318 * number be 0, no shell will be executed.
320 static int numCommands;
323 * Return values from JobStart.
325 #define JOB_RUNNING 0 /* Job is running */
326 #define JOB_ERROR 1 /* Error in starting the job */
327 #define JOB_FINISHED 2 /* The job is already finished */
328 #define JOB_STOPPED 3 /* The job is stopped */
331 * Descriptions for various shells.
333 static const struct CShell shells[] = {
335 * CSH description. The csh can do echo control by playing
336 * with the setting of the 'echo' shell variable. Sadly,
337 * however, it is unable to do error control nicely.
341 TRUE, "unset verbose", "set verbose", "unset verbose",
342 FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"",
346 * SH description. Echo control is also possible and, under
347 * sun UNIX anyway, one can even control error checking.
351 TRUE, "set -", "set -v", "set -",
352 TRUE, "set -e", "set +e",
353 #ifdef OLDBOURNESHELL
354 FALSE, "echo \"%s\"\n", "sh -c '%s || exit 0'\n",
359 * KSH description. The Korn shell has a superset of
360 * the Bourne shell's functionality.
364 TRUE, "set -", "set -v", "set -",
365 TRUE, "set -e", "set +e",
371 * This is the shell to which we pass all commands in the Makefile.
372 * It is set by the Job_ParseShell function.
374 static struct Shell *commandShell = NULL;
375 char *shellPath = NULL; /* full pathname of executable image */
376 char *shellName = NULL; /* last component of shell */
378 int maxJobs; /* The most children we can run at once */
379 static int nJobs; /* The number of children currently running */
381 /* The structures that describe them */
382 static struct JobList jobs = TAILQ_HEAD_INITIALIZER(jobs);
384 static Boolean jobFull; /* Flag to tell when the job table is full. It
385 * is set TRUE when (1) the total number of
386 * running jobs equals the maximum allowed */
388 static int kqfd; /* File descriptor obtained by kqueue() */
390 static fd_set outputs; /* Set of descriptors of pipes connected to
391 * the output channels of children */
394 static GNode *lastNode; /* The node for which output was most recently
396 static const char *targFmt; /* Format string to use to head output from a
397 * job when it's not the most-recent job heard
400 #define TARG_FMT "--- %s ---\n" /* Default format */
401 #define MESSAGE(fp, gn) \
402 fprintf(fp, targFmt, gn->name);
405 * When JobStart attempts to run a job but isn't allowed to
406 * or when Job_CatchChildren detects a job that has
407 * been stopped somehow, the job is placed on the stoppedJobs queue to be run
408 * when the next job finishes.
410 * Lst of Job structures describing jobs that were stopped due to
411 * concurrency limits or externally
413 static struct JobList stoppedJobs = TAILQ_HEAD_INITIALIZER(stoppedJobs);
415 static int fifoFd; /* Fd of our job fifo */
416 static char fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
417 static int fifoMaster;
419 static sig_atomic_t interrupted;
422 #if defined(USE_PGRP) && defined(SYSV)
423 # define KILL(pid, sig) killpg(-(pid), (sig))
425 # if defined(USE_PGRP)
426 # define KILL(pid, sig) killpg((pid), (sig))
428 # define KILL(pid, sig) kill((pid), (sig))
433 * Grmpf... There is no way to set bits of the wait structure
434 * anymore with the stupid W*() macros. I liked the union wait
435 * stuff much more. So, we devise our own macros... This is
436 * really ugly, use dramamine sparingly. You have been warned.
438 #define W_SETMASKED(st, val, fun) \
441 int mask = fun(sh); \
443 for (sh = 0; ((mask >> sh) & 1) == 0; sh++) \
445 *(st) = (*(st) & ~mask) | ((val) << sh); \
448 #define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
449 #define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
451 static void JobRestart(Job *);
452 static int JobStart(GNode *, int, Job *);
453 static void JobDoOutput(Job *, Boolean);
454 static struct Shell *JobMatchShell(const char *);
455 static void JobInterrupt(int, int);
456 static void JobRestartJobs(void);
460 * Got a signal. Set global variables and hope that someone will
464 JobCatchSig(int signo)
472 * Pass a signal on to all local jobs if
473 * USE_PGRP is defined, then die ourselves.
476 * We die by the same signal.
479 JobPassSig(int signo)
482 sigset_t nmask, omask;
483 struct sigaction act;
486 sigaddset(&nmask, signo);
487 sigprocmask(SIG_SETMASK, &nmask, &omask);
489 DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
490 TAILQ_FOREACH(job, &jobs, link) {
491 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
492 signo, (intmax_t)job->pid));
493 KILL(job->pid, signo);
497 * Deal with proper cleanup based on the signal received. We only run
498 * the .INTERRUPT target if the signal was in fact an interrupt.
499 * The other three termination signals are more of a "get out *now*"
502 if (signo == SIGINT) {
503 JobInterrupt(TRUE, signo);
504 } else if (signo == SIGHUP || signo == SIGTERM || signo == SIGQUIT) {
505 JobInterrupt(FALSE, signo);
509 * Leave gracefully if SIGQUIT, rather than core dumping.
511 if (signo == SIGQUIT) {
516 * Send ourselves the signal now we've given the message to everyone
517 * else. Note we block everything else possible while we're getting
518 * the signal. This ensures that all our jobs get continued when we
519 * wake up before we take any other signal.
520 * XXX this comment seems wrong.
522 act.sa_handler = SIG_DFL;
523 sigemptyset(&act.sa_mask);
525 sigaction(signo, &act, NULL);
527 DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
528 ~0 & ~(1 << (signo - 1))));
529 signal(signo, SIG_DFL);
531 KILL(getpid(), signo);
534 TAILQ_FOREACH(job, &jobs, link) {
535 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
536 signo, (intmax_t)job->pid));
537 KILL(job->pid, signo);
540 sigprocmask(SIG_SETMASK, &omask, NULL);
541 sigprocmask(SIG_SETMASK, &omask, NULL);
542 act.sa_handler = JobPassSig;
543 sigaction(signo, &act, NULL);
548 * Put out another command for the given job. If the command starts
549 * with an @ or a - we process it specially. In the former case,
550 * so long as the -s and -n flags weren't given to make, we stick
551 * a shell-specific echoOff command in the script. In the latter,
552 * we ignore errors for the entire job, unless the shell has error
554 * If the command is just "..." we take all future commands for this
555 * job to be commands to be executed once the entire graph has been
556 * made and return non-zero to signal that the end of the commands
557 * was reached. These commands are later attached to the postCommands
558 * node and executed by Job_Finish when all things are done.
559 * This function is called from JobStart via LST_FOREACH.
562 * Always 0, unless the command was "..."
565 * If the command begins with a '-' and the shell has no error control,
566 * the JOB_IGNERR flag is set in the job descriptor.
567 * If the command is "..." and we're not ignoring such things,
568 * tailCmds is set to the successor node of the cmd.
569 * numCommands is incremented if the command is actually printed.
572 JobPrintCommand(char *cmd, Job *job)
574 Boolean noSpecials; /* true if we shouldn't worry about
575 * inserting special commands into
576 * the input stream. */
577 Boolean shutUp = FALSE; /* true if we put a no echo command
578 * into the command file */
579 Boolean errOff = FALSE; /* true if we turned error checking
580 * off before printing the command
581 * and need to turn it back on */
582 const char *cmdTemplate;/* Template to use when printing the command */
583 char *cmdStart; /* Start of expanded command */
584 LstNode *cmdNode; /* Node for replacing the command */
586 noSpecials = (noExecute && !(job->node->type & OP_MAKE));
588 if (strcmp(cmd, "...") == 0) {
589 job->node->type |= OP_SAVE_CMDS;
590 if ((job->flags & JOB_IGNDOTS) == 0) {
592 Lst_Succ(Lst_Member(&job->node->commands, cmd));
598 #define DBPRINTF(fmt, arg) \
599 DEBUGF(JOB, (fmt, arg)); \
600 fprintf(job->cmdFILE, fmt, arg); \
601 fflush(job->cmdFILE);
606 * For debugging, we replace each command with the result of expanding
607 * the variables in the command.
609 cmdNode = Lst_Member(&job->node->commands, cmd);
611 cmd = Buf_Peel(Var_Subst(cmd, job->node, FALSE));
614 Lst_Replace(cmdNode, cmdStart);
616 cmdTemplate = "%s\n";
619 * Check for leading @', -' or +'s to control echoing, error checking,
620 * and execution on -n.
622 while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
626 shutUp = DEBUG(LOUD) ? FALSE : TRUE;
636 * We're not actually exececuting anything...
637 * but this one needs to be - use compat mode
640 Compat_RunCommand(cmd, job->node);
648 while (isspace((unsigned char)*cmd))
652 if (!(job->flags & JOB_SILENT) && !noSpecials &&
653 commandShell->hasEchoCtl) {
654 DBPRINTF("%s\n", commandShell->echoOff);
661 if (!(job->flags & JOB_IGNERR) && !noSpecials) {
662 if (commandShell->hasErrCtl) {
664 * We don't want the error-control commands
665 * showing up either, so we turn off echoing
666 * while executing them. We could put another
667 * field in the shell structure to tell
668 * JobDoOutput to look for this string too,
669 * but why make it any more complex than
672 if (!(job->flags & JOB_SILENT) && !shutUp &&
673 commandShell->hasEchoCtl) {
674 DBPRINTF("%s\n", commandShell->echoOff);
675 DBPRINTF("%s\n", commandShell->ignErr);
676 DBPRINTF("%s\n", commandShell->echoOn);
678 DBPRINTF("%s\n", commandShell->ignErr);
680 } else if (commandShell->ignErr &&
681 *commandShell->ignErr != '\0') {
683 * The shell has no error control, so we need to
684 * be weird to get it to ignore any errors from
685 * the command. If echoing is turned on, we turn
686 * it off and use the errCheck template to echo
687 * the command. Leave echoing off so the user
688 * doesn't see the weirdness we go through to
689 * ignore errors. Set cmdTemplate to use the
690 * weirdness instead of the simple "%s\n"
693 if (!(job->flags & JOB_SILENT) && !shutUp &&
694 commandShell->hasEchoCtl) {
695 DBPRINTF("%s\n", commandShell->echoOff);
696 DBPRINTF(commandShell->errCheck, cmd);
699 cmdTemplate = commandShell->ignErr;
701 * The error ignoration (hee hee) is already
702 * taken care of by the ignErr template, so
703 * pretend error checking is still on.
714 DBPRINTF(cmdTemplate, cmd);
718 * If echoing is already off, there's no point in issuing the
719 * echoOff command. Otherwise we issue it and pretend it was on
720 * for the whole command...
722 if (!shutUp && !(job->flags & JOB_SILENT) &&
723 commandShell->hasEchoCtl) {
724 DBPRINTF("%s\n", commandShell->echoOff);
727 DBPRINTF("%s\n", commandShell->errCheck);
730 DBPRINTF("%s\n", commandShell->echoOn);
737 * Called to close both input and output pipes when a job is finished.
740 * The file descriptors associated with the job are closed.
747 #if !defined(USE_KQUEUE)
748 FD_CLR(job->inPipe, &outputs);
750 if (job->outPipe != job->inPipe) {
753 JobDoOutput(job, TRUE);
757 JobDoOutput(job, TRUE);
763 * Do final processing for the given job including updating
764 * parents and starting new jobs as available/necessary. Note
765 * that we pay no attention to the JOB_IGNERR flag here.
766 * This is because when we're called because of a noexecute flag
767 * or something, jstat.w_status is 0 and when called from
768 * Job_CatchChildren, the status is zeroed if it s/b ignored.
771 * Some nodes may be put on the toBeMade queue.
772 * Final commands for the job are placed on postCommands.
774 * If we got an error and are aborting (aborting == ABORT_ERROR) and
775 * the job list is now empty, we are done for the day.
776 * If we recognized an error (errors !=0), we set the aborting flag
777 * to ABORT_ERROR so no more jobs will be started.
780 JobFinish(Job *job, int *status)
785 if ((WIFEXITED(*status) && WEXITSTATUS(*status) != 0 &&
786 !(job->flags & JOB_IGNERR)) ||
787 (WIFSIGNALED(*status) && WTERMSIG(*status) != SIGCONT)) {
789 * If it exited non-zero and either we're doing things our
790 * way or we're not ignoring errors, the job is finished.
791 * Similarly, if the shell died because of a signal
792 * the job is also finished. In these cases, finish out the
793 * job's output before printing the exit status...
796 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
797 fclose(job->cmdFILE);
801 } else if (WIFEXITED(*status)) {
803 * Deal with ignored errors in -B mode. We need to print a
804 * message telling of the ignored error as well as setting
805 * status.w_status to 0 so the next command gets run. To do
806 * this, we set done to be TRUE if in -B mode and the job
809 done = WEXITSTATUS(*status) != 0;
812 * Old comment said: "Note we don't want to close down any of
813 * the streams until we know we're at the end." But we do.
814 * Otherwise when are we going to print the rest of the stuff?
819 * No need to close things down or anything.
824 if (done || WIFSTOPPED(*status) ||
825 (WIFSIGNALED(*status) && WTERMSIG(*status) == SIGCONT) ||
829 if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
831 * If output is going to a file and this job is ignoring
832 * errors, arrange to have the exit status sent to the
833 * output file as well.
835 out = fdopen(job->outFd, "w");
837 Punt("Cannot fdopen");
842 if (WIFEXITED(*status)) {
843 DEBUGF(JOB, ("Process %jd exited.\n",
844 (intmax_t)job->pid));
845 if (WEXITSTATUS(*status) != 0) {
846 if (usePipes && job->node != lastNode) {
847 MESSAGE(out, job->node);
848 lastNode = job->node;
850 fprintf(out, "*** Error code %d%s\n",
851 WEXITSTATUS(*status),
852 (job->flags & JOB_IGNERR) ?
855 if (job->flags & JOB_IGNERR) {
858 } else if (DEBUG(JOB)) {
859 if (usePipes && job->node != lastNode) {
860 MESSAGE(out, job->node);
861 lastNode = job->node;
863 fprintf(out, "*** Completed successfully\n");
866 } else if (WIFSTOPPED(*status)) {
867 DEBUGF(JOB, ("Process %jd stopped.\n",
868 (intmax_t)job->pid));
869 if (usePipes && job->node != lastNode) {
870 MESSAGE(out, job->node);
871 lastNode = job->node;
873 fprintf(out, "*** Stopped -- signal %d\n",
875 job->flags |= JOB_RESUME;
876 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
880 } else if (WTERMSIG(*status) == SIGCONT) {
882 * If the beastie has continued, shift the Job from
883 * the stopped list to the running one (or re-stop it
884 * if concurrency is exceeded) and go and get another
887 if (job->flags & (JOB_RESUME | JOB_RESTART)) {
888 if (usePipes && job->node != lastNode) {
889 MESSAGE(out, job->node);
890 lastNode = job->node;
892 fprintf(out, "*** Continued\n");
894 if (!(job->flags & JOB_CONTINUING)) {
895 DEBUGF(JOB, ("Warning: process %jd was not "
896 "continuing.\n", (intmax_t)job->pid));
899 * We don't really want to restart a job from
900 * scratch just because it continued, especially
901 * not without killing the continuing process!
902 * That's why this is ifdef'ed out.
908 job->flags &= ~JOB_CONTINUING;
909 TAILQ_INSERT_TAIL(&jobs, job, link);
911 DEBUGF(JOB, ("Process %jd is continuing locally.\n",
912 (intmax_t)job->pid));
913 if (nJobs == maxJobs) {
915 DEBUGF(JOB, ("Job queue is full.\n"));
921 if (usePipes && job->node != lastNode) {
922 MESSAGE(out, job->node);
923 lastNode = job->node;
925 fprintf(out, "*** Signal %d\n", WTERMSIG(*status));
932 * Now handle the -B-mode stuff. If the beast still isn't finished,
933 * try and restart the job on the next command. If JobStart says it's
934 * ok, it's ok. If there's an error, this puppy is done.
936 if (compatMake && WIFEXITED(*status) &&
937 Lst_Succ(job->node->compat_command) != NULL) {
938 switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
944 W_SETEXITSTATUS(status, 1);
948 * If we got back a JOB_FINISHED code, JobStart has
949 * already called Make_Update and freed the job
950 * descriptor. We set done to false here to avoid fake
951 * cycles and double frees. JobStart needs to do the
952 * update so we can proceed up the graph when given
964 if (done && aborting != ABORT_ERROR &&
965 aborting != ABORT_INTERRUPT && *status == 0) {
967 * As long as we aren't aborting and the job didn't return a
968 * non-zero status that we shouldn't ignore, we call
969 * Make_Update to update the parents. In addition, any saved
970 * commands for the node are placed on the .END target.
972 for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
973 Lst_AtEnd(&postCommands->commands,
975 Var_Subst(Lst_Datum(ln), job->node, FALSE)));
978 job->node->made = MADE;
979 Make_Update(job->node);
982 } else if (*status != 0) {
990 * Set aborting if any error.
992 if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
994 * If we found any errors in this batch of children and the -k
995 * flag wasn't given, we set the aborting flag so no more jobs
998 aborting = ABORT_ERROR;
1001 if (aborting == ABORT_ERROR && Job_Empty()) {
1003 * If we are aborting and the job table is now empty, we finish.
1011 * Touch the given target. Called by JobStart when the -t flag was
1012 * given. Prints messages unless told to be silent.
1015 * The data modification of the file is changed. In addition, if the
1016 * file did not exist, it is created.
1019 Job_Touch(GNode *gn, Boolean silent)
1021 int streamID; /* ID of stream opened to do the touch */
1022 struct utimbuf times; /* Times for utime() call */
1024 if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
1026 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
1027 * targets and, as such, shouldn't really be created.
1033 fprintf(stdout, "touch %s\n", gn->name);
1041 if (gn->type & OP_ARCHV) {
1043 } else if (gn->type & OP_LIB) {
1046 char *file = gn->path ? gn->path : gn->name;
1048 times.actime = times.modtime = now;
1049 if (utime(file, ×) < 0) {
1050 streamID = open(file, O_RDWR | O_CREAT, 0666);
1052 if (streamID >= 0) {
1056 * Read and write a byte to the file to change
1057 * the modification time, then close the file.
1059 if (read(streamID, &c, 1) == 1) {
1060 lseek(streamID, (off_t)0, SEEK_SET);
1061 write(streamID, &c, 1);
1066 fprintf(stdout, "*** couldn't touch %s: %s",
1067 file, strerror(errno));
1076 * Make sure the given node has all the commands it needs.
1079 * TRUE if the commands list is/was ok.
1082 * The node will have commands from the .DEFAULT rule added to it
1086 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1089 if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
1090 (gn->type & OP_LIB) == 0) {
1092 * No commands. Look for .DEFAULT rule from which we might infer
1095 if (DEFAULT != NULL && !Lst_IsEmpty(&DEFAULT->commands)) {
1098 * Make only looks for a .DEFAULT if the node was
1099 * never the target of an operator, so that's what we
1100 * do too. If a .DEFAULT was given, we substitute its
1101 * commands for gn's commands and set the IMPSRC
1102 * variable to be the target's name The DEFAULT node
1103 * acts like a transformation rule, in that gn also
1104 * inherits any attributes or sources attached to
1107 Make_HandleUse(DEFAULT, gn);
1108 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn);
1111 } else if (Dir_MTime(gn) == 0) {
1113 * The node wasn't the target of an operator we have
1114 * no .DEFAULT rule to go on and the target doesn't
1115 * already exist. There's nothing more we can do for
1116 * this branch. If the -k flag wasn't given, we stop
1117 * in our tracks, otherwise we just don't update
1118 * this node's parents so they never get examined.
1120 static const char msg[] =
1121 "make: don't know how to make";
1123 if (gn->type & OP_OPTIONAL) {
1124 fprintf(stdout, "%s %s(ignored)\n",
1127 } else if (keepgoing) {
1128 fprintf(stdout, "%s %s(continuing)\n",
1134 if (strcmp(gn->name,"love") == 0)
1135 (*abortProc)("Not war.");
1138 (*abortProc)("%s %s. Stop",
1149 * Execute the shell for the given job. Called from JobStart and
1153 * A shell is executed, outputs is altered and the Job structure added
1157 JobExec(Job *job, char **argv)
1159 pid_t cpid; /* ID of new child */
1164 DEBUGF(JOB, ("Running %s\n", job->node->name));
1165 DEBUGF(JOB, ("\tCommand: "));
1166 for (i = 0; argv[i] != NULL; i++) {
1167 DEBUGF(JOB, ("%s ", argv[i]));
1169 DEBUGF(JOB, ("\n"));
1173 * Some jobs produce no output and it's disconcerting to have
1174 * no feedback of their running (since they produce no output, the
1175 * banner with their name in it never appears). This is an attempt to
1176 * provide that feedback, even if nothing follows it.
1178 if (lastNode != job->node && (job->flags & JOB_FIRST) &&
1179 !(job->flags & JOB_SILENT)) {
1180 MESSAGE(stdout, job->node);
1181 lastNode = job->node;
1184 if ((cpid = vfork()) == -1)
1185 Punt("Cannot fork");
1195 * Must duplicate the input stream down to the child's input and
1196 * reset it to the beginning (again). Since the stream was
1197 * marked close-on-exec, we must clear that bit in the new
1200 if (dup2(FILENO(job->cmdFILE), 0) == -1)
1201 Punt("Cannot dup2: %s", strerror(errno));
1202 fcntl(0, F_SETFD, 0);
1203 lseek(0, (off_t)0, SEEK_SET);
1207 * Set up the child's output to be routed through the
1208 * pipe we've created for it.
1210 if (dup2(job->outPipe, 1) == -1)
1211 Punt("Cannot dup2: %s", strerror(errno));
1214 * We're capturing output in a file, so we duplicate the
1215 * descriptor to the temporary file into the standard
1218 if (dup2(job->outFd, 1) == -1)
1219 Punt("Cannot dup2: %s", strerror(errno));
1222 * The output channels are marked close on exec. This bit was
1223 * duplicated by the dup2 (on some systems), so we have to clear
1224 * it before routing the shell's error output to the same place
1225 * as its standard output.
1227 fcntl(1, F_SETFD, 0);
1228 if (dup2(1, 2) == -1)
1229 Punt("Cannot dup2: %s", strerror(errno));
1233 * We want to switch the child into a different process family
1234 * so we can kill it and all its descendants in one fell swoop,
1235 * by killing its process family, but not commit suicide.
1240 setpgid(0, getpid());
1242 #endif /* USE_PGRP */
1244 execv(shellPath, argv);
1246 write(STDERR_FILENO, "Could not execute shell\n",
1247 sizeof("Could not execute shell"));
1256 if (usePipes && (job->flags & JOB_FIRST)) {
1258 * The first time a job is run for a node, we set the
1259 * current position in the buffer to the beginning and
1260 * mark another stream to watch in the outputs mask.
1263 struct kevent kev[2];
1267 #if defined(USE_KQUEUE)
1268 EV_SET(&kev[0], job->inPipe, EVFILT_READ, EV_ADD, 0, 0, job);
1269 EV_SET(&kev[1], job->pid, EVFILT_PROC,
1270 EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
1271 if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1273 * kevent() will fail if the job is already
1276 if (errno != EINTR && errno != EBADF && errno != ESRCH)
1277 Punt("kevent: %s", strerror(errno));
1280 FD_SET(job->inPipe, &outputs);
1281 #endif /* USE_KQUEUE */
1284 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1285 fclose(job->cmdFILE);
1286 job->cmdFILE = NULL;
1290 * Now the job is actually running, add it to the table.
1293 TAILQ_INSERT_TAIL(&jobs, job, link);
1294 if (nJobs == maxJobs) {
1301 * Create the argv needed to execute the shell for a given job.
1304 JobMakeArgv(Job *job, char **argv)
1307 static char args[10]; /* For merged arguments */
1309 argv[0] = shellName;
1312 if ((commandShell->exit && *commandShell->exit != '-') ||
1313 (commandShell->echo && *commandShell->echo != '-')) {
1315 * At least one of the flags doesn't have a minus before it, so
1316 * merge them together. Have to do this because the *(&(@*#*&#$#
1317 * Bourne shell thinks its second argument is a file to source.
1318 * Grrrr. Note the ten-character limitation on the combined
1321 sprintf(args, "-%s%s", (job->flags & JOB_IGNERR) ? "" :
1322 commandShell->exit ? commandShell->exit : "",
1323 (job->flags & JOB_SILENT) ? "" :
1324 commandShell->echo ? commandShell->echo : "");
1331 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1332 argv[argc] = commandShell->exit;
1335 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1336 argv[argc] = commandShell->echo;
1345 * Restart a job that stopped for some reason. The job must be neither
1346 * on the jobs nor on the stoppedJobs list.
1349 * jobFull will be set if the job couldn't be run.
1352 JobRestart(Job *job)
1355 if (job->flags & JOB_RESTART) {
1357 * Set up the control arguments to the shell. This is based on
1358 * the flags set earlier for this job. If the JOB_IGNERR flag
1359 * is clear, the 'exit' flag of the commandShell is used to
1360 * cause it to exit upon receiving an error. If the JOB_SILENT
1361 * flag is clear, the 'echo' flag of the commandShell is used
1362 * to get it to start echoing as soon as it starts
1363 * processing commands.
1367 JobMakeArgv(job, argv);
1369 DEBUGF(JOB, ("Restarting %s...", job->node->name));
1370 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL)) {
1372 * Not allowed to run -- put it back on the hold
1373 * queue and mark the table full
1375 DEBUGF(JOB, ("holding\n"));
1376 TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1378 DEBUGF(JOB, ("Job queue is full.\n"));
1382 * Job may be run locally.
1384 DEBUGF(JOB, ("running locally\n"));
1390 * The job has stopped and needs to be restarted.
1391 * Why it stopped, we don't know...
1393 DEBUGF(JOB, ("Resuming %s...", job->node->name));
1394 if ((nJobs < maxJobs || ((job->flags & JOB_SPECIAL) &&
1395 maxJobs == 0)) && nJobs != maxJobs) {
1397 * If we haven't reached the concurrency limit already
1398 * (or the job must be run and maxJobs is 0), it's ok
1404 error = (KILL(job->pid, SIGCONT) != 0);
1408 * Make sure the user knows we've continued
1409 * the beast and actually put the thing in the
1412 job->flags |= JOB_CONTINUING;
1414 W_SETTERMSIG(&status, SIGCONT);
1415 JobFinish(job, &status);
1417 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1418 DEBUGF(JOB, ("done\n"));
1420 Error("couldn't resume %s: %s",
1421 job->node->name, strerror(errno));
1423 W_SETEXITSTATUS(&status, 1);
1424 JobFinish(job, &status);
1428 * Job cannot be restarted. Mark the table as full and
1429 * place the job back on the list of stopped jobs.
1431 DEBUGF(JOB, ("table full\n"));
1432 TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
1434 DEBUGF(JOB, ("Job queue is full.\n"));
1441 * Start a target-creation process going for the target described
1442 * by the graph node gn.
1445 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1446 * if there isn't actually anything left to do for the job and
1447 * JOB_RUNNING if the job has been started.
1450 * A new Job node is created and added to the list of running
1451 * jobs. PMake is forked and a child shell created.
1454 JobStart(GNode *gn, int flags, Job *previous)
1456 Job *job; /* new job descriptor */
1457 char *argv[4]; /* Argument vector to shell */
1458 Boolean cmdsOK; /* true if the nodes commands were all right */
1459 Boolean noExec; /* Set true if we decide not to run the job */
1460 int tfd; /* File descriptor for temp file */
1462 char tfile[sizeof(TMPPAT)];
1465 JobPassSig(interrupted);
1468 if (previous != NULL) {
1469 previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1472 job = emalloc(sizeof(Job));
1477 job->tailCmds = NULL;
1480 * Set the initial value of the flags for this job based on the global
1481 * ones and the node's attributes... Any flags supplied by the caller
1482 * are also added to the field.
1485 if (Targ_Ignore(gn)) {
1486 job->flags |= JOB_IGNERR;
1488 if (Targ_Silent(gn)) {
1489 job->flags |= JOB_SILENT;
1491 job->flags |= flags;
1494 * Check the commands now so any attributes from .DEFAULT have a chance
1495 * to migrate to the node.
1497 if (!compatMake && (job->flags & JOB_FIRST)) {
1498 cmdsOK = Job_CheckCommands(gn, Error);
1504 * If the -n flag wasn't given, we open up OUR (not the child's)
1505 * temporary file to stuff commands in it. The thing is rd/wr so we
1506 * don't need to reopen it to feed it to the shell. If the -n flag
1507 * *was* given, we just set the file to be stdout. Cute, huh?
1509 if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1511 * We're serious here, but if the commands were bogus, we're
1518 strcpy(tfile, TMPPAT);
1519 if ((tfd = mkstemp(tfile)) == -1)
1520 Punt("Cannot create temp file: %s", strerror(errno));
1521 job->cmdFILE = fdopen(tfd, "w+");
1523 if (job->cmdFILE == NULL) {
1525 Punt("Could not open %s", tfile);
1527 fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1529 * Send the commands to the command file, flush all its
1530 * buffers then rewind and remove the thing.
1535 * Used to be backwards; replace when start doing multiple
1536 * commands per shell.
1540 * Be compatible: If this is the first time for this
1541 * node, verify its commands are ok and open the
1542 * commands list for sequential access by later
1543 * invocations of JobStart. Once that is done, we take
1544 * the next command off the list and print it to the
1545 * command file. If the command was an ellipsis, note
1546 * that there's nothing more to execute.
1548 if (job->flags & JOB_FIRST)
1549 gn->compat_command = Lst_First(&gn->commands);
1551 gn->compat_command =
1552 Lst_Succ(gn->compat_command);
1554 if (gn->compat_command == NULL ||
1555 JobPrintCommand(Lst_Datum(gn->compat_command), job))
1558 if (noExec && !(job->flags & JOB_FIRST)) {
1560 * If we're not going to execute anything, the
1561 * job is done and we need to close down the
1562 * various file descriptors we've opened for
1563 * output, then call JobDoOutput to catch the
1564 * final characters or send the file to the
1565 * screen... Note that the i/o streams are only
1566 * open if this isn't the first job. Note also
1567 * that this could not be done in
1568 * Job_CatchChildren b/c it wasn't clear if
1569 * there were more commands to execute or not...
1575 * We can do all the commands at once. hooray for sanity
1578 LST_FOREACH(ln, &gn->commands) {
1579 if (JobPrintCommand(Lst_Datum(ln), job))
1584 * If we didn't print out any commands to the shell
1585 * script, there's not much point in executing the
1588 if (numCommands == 0) {
1593 } else if (noExecute) {
1595 * Not executing anything -- just print all the commands to
1596 * stdout in one fell swoop. This will still set up
1597 * job->tailCmds correctly.
1599 if (lastNode != gn) {
1600 MESSAGE(stdout, gn);
1603 job->cmdFILE = stdout;
1606 * Only print the commands if they're ok, but don't die if
1607 * they're not -- just let the user know they're bad and keep
1608 * going. It doesn't do any harm in this case and may do
1612 LST_FOREACH(ln, &gn->commands) {
1613 if (JobPrintCommand(Lst_Datum(ln), job))
1618 * Don't execute the shell, thank you.
1624 * Just touch the target and note that no shell should be
1625 * executed. Set cmdFILE to stdout to make life easier. Check
1626 * the commands, too, but don't die if they're no good -- it
1627 * does no harm to keep working up the graph.
1629 job->cmdFILE = stdout;
1630 Job_Touch(gn, job->flags & JOB_SILENT);
1635 * If we're not supposed to execute a shell, don't.
1639 * Unlink and close the command file if we opened one
1641 if (job->cmdFILE != stdout) {
1642 if (job->cmdFILE != NULL)
1643 fclose(job->cmdFILE);
1649 * We only want to work our way up the graph if we aren't here
1650 * because the commands for the job were no good.
1653 if (aborting == 0) {
1654 for (ln = job->tailCmds; ln != NULL;
1655 ln = LST_NEXT(ln)) {
1656 Lst_AtEnd(&postCommands->commands,
1657 Buf_Peel(Var_Subst(Lst_Datum(ln),
1658 job->node, FALSE)));
1660 job->node->made = MADE;
1661 Make_Update(job->node);
1664 return(JOB_FINISHED);
1670 fflush(job->cmdFILE);
1674 * Set up the control arguments to the shell. This is based on the flags
1675 * set earlier for this job.
1677 JobMakeArgv(job, argv);
1680 * If we're using pipes to catch output, create the pipe by which we'll
1681 * get the shell's output. If we're using files, print out that we're
1682 * starting a job and then set up its temporary-file name.
1684 if (!compatMake || (job->flags & JOB_FIRST)) {
1689 Punt("Cannot create pipe: %s", strerror(errno));
1690 job->inPipe = fd[0];
1691 job->outPipe = fd[1];
1692 fcntl(job->inPipe, F_SETFD, 1);
1693 fcntl(job->outPipe, F_SETFD, 1);
1695 fprintf(stdout, "Remaking `%s'\n", gn->name);
1697 strcpy(job->outFile, TMPPAT);
1698 if ((job->outFd = mkstemp(job->outFile)) == -1)
1699 Punt("cannot create temp file: %s",
1701 fcntl(job->outFd, F_SETFD, 1);
1705 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL) && maxJobs != 0) {
1707 * We've hit the limit of concurrency, so put the job on hold
1708 * until some other job finishes. Note that the special jobs
1709 * (.BEGIN, .INTERRUPT and .END) may be run even when the
1710 * limit has been reached (e.g. when maxJobs == 0).
1714 DEBUGF(JOB, ("Can only run job locally.\n"));
1715 job->flags |= JOB_RESTART;
1716 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
1718 if (nJobs >= maxJobs) {
1720 * If we're running this job as a special case
1721 * (see above), at least say the table is full.
1724 DEBUGF(JOB, ("Local job queue is full.\n"));
1728 return (JOB_RUNNING);
1732 JobOutput(Job *job, char *cp, char *endp, int msg)
1736 if (commandShell->noPrint) {
1737 ecp = strstr(cp, commandShell->noPrint);
1738 while (ecp != NULL) {
1741 if (msg && job->node != lastNode) {
1742 MESSAGE(stdout, job->node);
1743 lastNode = job->node;
1746 * The only way there wouldn't be a newline
1747 * after this line is if it were the last in
1748 * the buffer. However, since the non-printable
1749 * comes after it, there must be a newline, so
1750 * we don't print one.
1752 fprintf(stdout, "%s", cp);
1755 cp = ecp + strlen(commandShell->noPrint);
1758 * Still more to print, look again after
1759 * skipping the whitespace following the
1760 * non-printable command....
1763 while (*cp == ' ' || *cp == '\t' ||
1767 ecp = strstr(cp, commandShell->noPrint);
1778 * This function is called at different times depending on
1779 * whether the user has specified that output is to be collected
1780 * via pipes or temporary files. In the former case, we are called
1781 * whenever there is something to read on the pipe. We collect more
1782 * output from the given job and store it in the job's outBuf. If
1783 * this makes up a line, we print it tagged by the job's identifier,
1785 * If output has been collected in a temporary file, we open the
1786 * file and read it line by line, transfering it to our own
1787 * output channel until the file is empty. At which point we
1788 * remove the temporary file.
1789 * In both cases, however, we keep our figurative eye out for the
1790 * 'noPrint' line for the shell from which the output came. If
1791 * we recognize a line, we don't print it. If the command is not
1792 * alone on the line (the character after it is not \0 or \n), we
1793 * do print whatever follows it.
1796 * curPos may be shifted as may the contents of outBuf.
1799 JobDoOutput(Job *job, Boolean finish)
1801 Boolean gotNL = FALSE; /* true if got a newline */
1802 Boolean fbuf; /* true if our buffer filled up */
1803 int nr; /* number of bytes read */
1804 int i; /* auxiliary index into outBuf */
1805 int max; /* limit for i (end of current data) */
1806 int nRead; /* (Temporary) number of bytes read */
1807 FILE *oFILE; /* Stream pointer to shell's output file */
1812 * Read as many bytes as will fit in the buffer.
1818 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1819 JOB_BUFSIZE - job->curPos);
1821 * Check for interrupt here too, because the above read may
1822 * block when the child process is stopped. In this case the
1823 * interrupt will unblock it (we don't use SA_RESTART).
1826 JobPassSig(interrupted);
1829 DEBUGF(JOB, ("JobDoOutput(piperead)"));
1836 * If we hit the end-of-file (the job is dead), we must flush
1837 * its remaining output, so pretend we read a newline if
1838 * there's any output remaining in the buffer.
1839 * Also clear the 'finish' flag so we stop looping.
1841 if (nr == 0 && job->curPos != 0) {
1842 job->outBuf[job->curPos] = '\n';
1845 } else if (nr == 0) {
1850 * Look for the last newline in the bytes we just got. If there
1851 * is one, break out of the loop with 'i' as its index and
1854 max = job->curPos + nr;
1855 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1856 if (job->outBuf[i] == '\n') {
1859 } else if (job->outBuf[i] == '\0') {
1863 job->outBuf[i] = ' ';
1869 if (job->curPos == JOB_BUFSIZE) {
1871 * If we've run out of buffer space, we have
1872 * no choice but to print the stuff. sigh.
1878 if (gotNL || fbuf) {
1880 * Need to send the output to the screen. Null terminate
1881 * it first, overwriting the newline character if there
1882 * was one. So long as the line isn't one we should
1883 * filter (according to the shell description), we print
1884 * the line, preceded by a target banner if this target
1885 * isn't the same as the one for which we last printed
1886 * something. The rest of the data in the buffer are
1887 * then shifted down to the start of the buffer and
1888 * curPos is set accordingly.
1890 job->outBuf[i] = '\0';
1891 if (i >= job->curPos) {
1894 cp = JobOutput(job, job->outBuf,
1895 &job->outBuf[i], FALSE);
1898 * There's still more in that buffer. This time,
1899 * though, we know there's no newline at the
1900 * end, so we add one of our own free will.
1903 if (job->node != lastNode) {
1904 MESSAGE(stdout, job->node);
1905 lastNode = job->node;
1907 fprintf(stdout, "%s%s", cp,
1913 /* shift the remaining characters down */
1914 memcpy(job->outBuf, &job->outBuf[i + 1],
1916 job->curPos = max - (i + 1);
1920 * We have written everything out, so we just
1921 * start over from the start of the buffer.
1922 * No copying. No nothing.
1929 * If the finish flag is true, we must loop until we hit
1930 * end-of-file on the pipe. This is guaranteed to happen
1931 * eventually since the other end of the pipe is now
1932 * closed (we closed it explicitly and the child has
1933 * exited). When we do get an EOF, finish will be set
1934 * FALSE and we'll fall through and out.
1941 * We've been called to retrieve the output of the job from the
1942 * temporary file where it's been squirreled away. This consists
1943 * of opening the file, reading the output line by line, being
1944 * sure not to print the noPrint line for the shell we used,
1945 * then close and remove the temporary file. Very simple.
1947 * Change to read in blocks and do FindSubString type things
1948 * as for pipes? That would allow for "@echo -n..."
1950 oFILE = fopen(job->outFile, "r");
1951 if (oFILE != NULL) {
1952 fprintf(stdout, "Results of making %s:\n",
1956 while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
1957 char *cp, *endp, *oendp;
1960 oendp = endp = inLine + strlen(inLine);
1961 if (endp[-1] == '\n') {
1964 cp = JobOutput(job, inLine, endp, FALSE);
1967 * There's still more in that buffer. This time,
1968 * though, we know there's no newline at the
1969 * end, so we add one of our own free will.
1971 fprintf(stdout, "%s", cp);
1973 if (endp != oendp) {
1974 fprintf(stdout, "\n");
1979 eunlink(job->outFile);
1986 * Handle the exit of a child. Called from Make_Make.
1989 * The job descriptor is removed from the list of children.
1992 * We do waits, blocking or not, according to the wisdom of our
1993 * caller, until there are no more children to report. For each
1994 * job, call JobFinish to finish things off. This will take care of
1995 * putting jobs on the stoppedJobs queue.
1998 Job_CatchChildren(Boolean block)
2000 pid_t pid; /* pid of dead child */
2001 Job *job; /* job descriptor for dead child */
2002 int status; /* Exit/termination status */
2005 * Don't even bother if we know there's no one around.
2012 pid = waitpid((pid_t)-1, &status,
2013 (block ? 0 : WNOHANG) | WUNTRACED);
2017 DEBUGF(JOB, ("Process %jd exited or stopped.\n",
2020 TAILQ_FOREACH(job, &jobs, link) {
2021 if (job->pid == pid)
2026 if (WIFSIGNALED(status) &&
2027 (WTERMSIG(status) == SIGCONT)) {
2028 TAILQ_FOREACH(job, &jobs, link) {
2029 if (job->pid == pid)
2033 Error("Resumed child (%jd) "
2034 "not in table", (intmax_t)pid);
2037 TAILQ_REMOVE(&stoppedJobs, job, link);
2039 Error("Child (%jd) not in table?",
2044 TAILQ_REMOVE(&jobs, job, link);
2046 if (fifoFd >= 0 && maxJobs > 1) {
2047 write(fifoFd, "+", 1);
2049 if (nJobs >= maxJobs)
2054 DEBUGF(JOB, ("Job queue is no longer full.\n"));
2059 JobFinish(job, &status);
2062 JobPassSig(interrupted);
2067 * Catch the output from our children, if we're using
2068 * pipes do so. Otherwise just block time until we get a
2069 * signal(most likely a SIGCHLD) since there's no point in
2070 * just spinning when there's nothing to do and the reaping
2071 * of a child can wait for a while.
2074 * Output is read from pipes if we're piping.
2075 * -----------------------------------------------------------------------
2079 Job_CatchOutput(int flag __unused)
2081 Job_CatchOutput(int flag)
2087 struct kevent kev[KEV_SIZE];
2090 struct timeval timeout;
2099 if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
2101 Punt("kevent: %s", strerror(errno));
2103 JobPassSig(interrupted);
2105 for (i = 0; i < nfds; i++) {
2106 if (kev[i].flags & EV_ERROR) {
2107 warnc(kev[i].data, "kevent");
2110 switch (kev[i].filter) {
2112 JobDoOutput(kev[i].udata, FALSE);
2116 * Just wake up and let
2117 * Job_CatchChildren() collect the
2126 timeout.tv_sec = SEL_SEC;
2127 timeout.tv_usec = SEL_USEC;
2128 if (flag && jobFull && fifoFd >= 0)
2129 FD_SET(fifoFd, &readfds);
2131 nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
2132 (fd_set *)NULL, &timeout);
2135 JobPassSig(interrupted);
2138 if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2142 job = TAILQ_FIRST(&jobs);
2143 while (nfds != 0 && job != NULL) {
2144 if (FD_ISSET(job->inPipe, &readfds)) {
2145 JobDoOutput(job, FALSE);
2148 job = TAILQ_NEXT(job, link);
2150 #endif /* !USE_KQUEUE */
2156 * Start the creation of a target. Basically a front-end for
2157 * JobStart used by the Make module.
2160 * Another job is started.
2166 JobStart(gn, 0, NULL);
2171 * Make a new copy of the shell structure including a copy of the strings
2172 * in it. This also defaults some fields in case they are NULL.
2175 * The function returns a pointer to the new shell structure.
2177 static struct Shell *
2178 JobCopyShell(const struct Shell *osh)
2182 nsh = emalloc(sizeof(*nsh));
2183 nsh->name = estrdup(osh->name);
2185 if (osh->echoOff != NULL)
2186 nsh->echoOff = estrdup(osh->echoOff);
2188 nsh->echoOff = NULL;
2189 if (osh->echoOn != NULL)
2190 nsh->echoOn = estrdup(osh->echoOn);
2193 nsh->hasEchoCtl = osh->hasEchoCtl;
2195 if (osh->noPrint != NULL)
2196 nsh->noPrint = estrdup(osh->noPrint);
2198 nsh->noPrint = NULL;
2200 nsh->hasErrCtl = osh->hasErrCtl;
2201 if (osh->errCheck == NULL)
2202 nsh->errCheck = estrdup("");
2204 nsh->errCheck = estrdup(osh->errCheck);
2205 if (osh->ignErr == NULL)
2206 nsh->ignErr = estrdup("%s");
2208 nsh->ignErr = estrdup(osh->ignErr);
2210 if (osh->echo == NULL)
2211 nsh->echo = estrdup("");
2213 nsh->echo = estrdup(osh->echo);
2215 if (osh->exit == NULL)
2216 nsh->exit = estrdup("");
2218 nsh->exit = estrdup(osh->exit);
2225 * Free a shell structure and all associated strings.
2228 JobFreeShell(struct Shell *sh)
2248 if (commandShell == NULL)
2249 commandShell = JobMatchShell(shells[DEFSHELL].name);
2251 if (shellPath == NULL) {
2253 * The user didn't specify a shell to use, so we are using the
2254 * default one... Both the absolute path and the last component
2255 * must be set. The last component is taken from the 'name'
2256 * field of the default shell description pointed-to by
2257 * commandShell. All default shells are located in
2260 shellName = commandShell->name;
2261 shellPath = str_concat(PATH_DEFSHELLDIR, shellName,
2268 * Initialize the process module, given a maximum number of jobs.
2271 * lists and counters are initialized
2274 Job_Init(int maxproc)
2276 GNode *begin; /* node for commands to do at the very start */
2278 struct sigaction sa;
2281 env = getenv("MAKE_JOBS_FIFO");
2283 if (env == NULL && maxproc > 1) {
2285 * We did not find the environment variable so we are the
2286 * leader. Create the fifo, open it, write one char per
2287 * allowed job into the pipe.
2290 if (!mkfifo(fifoName, 0600)) {
2291 fifoFd = open(fifoName, O_RDWR | O_NONBLOCK, 0);
2294 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2296 setenv("MAKE_JOBS_FIFO", env, 1);
2297 while (maxproc-- > 0) {
2298 write(fifoFd, "+", 1);
2300 /* The master make does not get a magic token */
2309 } else if (env != NULL) {
2311 * We had the environment variable so we are a slave.
2312 * Open fifo and give ourselves a magic token which represents
2313 * the token our parent make has grabbed to start his make
2314 * process. Otherwise the sub-makes would gobble up tokens and
2315 * the proper number of tokens to specify to -j would depend
2316 * on the depth of the tree and the order of execution.
2318 fifoFd = open(env, O_RDWR, 0);
2320 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2337 if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2339 * If only one job can run at a time, there's no need for a
2340 * banner, no is there?
2350 * Catch the four signals that POSIX specifies if they aren't ignored.
2351 * JobCatchSignal will just set global variables and hope someone
2352 * else is going to handle the interrupt.
2354 sa.sa_handler = JobCatchSig;
2355 sigemptyset(&sa.sa_mask);
2358 if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2359 sigaction(SIGINT, &sa, NULL);
2361 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2362 sigaction(SIGHUP, &sa, NULL);
2364 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2365 sigaction(SIGQUIT, &sa, NULL);
2367 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2368 sigaction(SIGTERM, &sa, NULL);
2371 * There are additional signals that need to be caught and passed if
2372 * either the export system wants to be told directly of signals or if
2373 * we're giving each job its own process group (since then it won't get
2374 * signals from the terminal driver as we own the terminal)
2376 #if defined(USE_PGRP)
2377 if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2378 sigaction(SIGTSTP, &sa, NULL);
2380 if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2381 sigaction(SIGTTOU, &sa, NULL);
2383 if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2384 sigaction(SIGTTIN, &sa, NULL);
2386 if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2387 sigaction(SIGWINCH, &sa, NULL);
2392 if ((kqfd = kqueue()) == -1) {
2393 Punt("kqueue: %s", strerror(errno));
2397 begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2399 if (begin != NULL) {
2400 JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2403 Job_CatchChildren(!usePipes);
2406 postCommands = Targ_FindNode(".END", TARG_CREATE);
2411 * See if the job table is full. It is considered full if it is OR
2412 * if we are in the process of aborting OR if we have
2413 * reached/exceeded our local quota. This prevents any more jobs
2417 * TRUE if the job table is full, FALSE otherwise
2427 if (fifoFd >= 0 && jobFull) {
2428 i = read(fifoFd, &c, 1);
2439 * See if the job table is empty. Because the local concurrency may
2440 * be set to 0, it is possible for the job table to become empty,
2441 * while the list of stoppedJobs remains non-empty. In such a case,
2442 * we want to restart as many jobs as we can.
2445 * TRUE if it is. FALSE if it ain't.
2451 if (!TAILQ_EMPTY(&stoppedJobs) && !aborting) {
2453 * The job table is obviously not full if it has no
2454 * jobs in it...Try and restart the stopped jobs.
2469 * Find a matching shell in 'shells' given its final component.
2472 * A pointer to a freshly allocated Shell structure with a copy
2473 * of the static structure or NULL if no shell with the given name
2476 static struct Shell *
2477 JobMatchShell(const char *name)
2479 const struct CShell *sh; /* Pointer into shells table */
2482 for (sh = shells; sh < shells + __arysize(shells); sh++)
2483 if (strcmp(sh->name, name) == 0)
2486 if (sh == shells + __arysize(shells))
2490 nsh = emalloc(sizeof(*nsh));
2492 nsh->name = estrdup(sh->name);
2493 nsh->echoOff = estrdup(sh->echoOff);
2494 nsh->echoOn = estrdup(sh->echoOn);
2495 nsh->hasEchoCtl = sh->hasEchoCtl;
2496 nsh->noPrint = estrdup(sh->noPrint);
2497 nsh->hasErrCtl = sh->hasErrCtl;
2498 nsh->errCheck = estrdup(sh->errCheck);
2499 nsh->ignErr = estrdup(sh->ignErr);
2500 nsh->echo = estrdup(sh->echo);
2501 nsh->exit = estrdup(sh->exit);
2508 * Parse a shell specification and set up commandShell, shellPath
2509 * and shellName appropriately.
2512 * FAILURE if the specification was incorrect.
2515 * commandShell points to a Shell structure (either predefined or
2516 * created from the shell spec), shellPath is the full path of the
2517 * shell described by commandShell, while shellName is just the
2518 * final component of shellPath.
2521 * A shell specification consists of a .SHELL target, with dependency
2522 * operator, followed by a series of blank-separated words. Double
2523 * quotes can be used to use blanks in words. A backslash escapes
2524 * anything (most notably a double-quote and a space) and
2525 * provides the functionality it does in C. Each word consists of
2526 * keyword and value separated by an equal sign. There should be no
2527 * unnecessary spaces in the word. The keywords are as follows:
2528 * name Name of shell.
2529 * path Location of shell. Overrides "name" if given
2530 * quiet Command to turn off echoing.
2531 * echo Command to turn echoing on
2532 * filter Result of turning off echoing that shouldn't be
2534 * echoFlag Flag to turn echoing on at the start
2535 * errFlag Flag to turn error checking on at the start
2536 * hasErrCtl True if shell has error checking control
2537 * check Command to turn on error checking if hasErrCtl
2538 * is TRUE or template of command to echo a command
2539 * for which error checking is off if hasErrCtl is
2541 * ignore Command to turn off error checking if hasErrCtl
2542 * is TRUE or template of command to execute a
2543 * command so as to ignore any errors it returns if
2544 * hasErrCtl is FALSE.
2547 Job_ParseShell(char *line)
2555 Boolean fullSpec = FALSE;
2556 struct Shell newShell;
2559 while (isspace((unsigned char)*line)) {
2562 words = brk_string(line, &wordCount, TRUE);
2564 memset(&newShell, 0, sizeof(newShell));
2568 * Parse the specification by keyword but skip the first word - it
2569 * is not set by brk_string.
2574 for (argc = wordCount, argv = words; argc != 0; argc--, argv++) {
2576 * Split keyword and value
2578 if ((eq = strchr(*argv, '=')) == NULL) {
2579 Parse_Error(PARSE_FATAL, "missing '=' in shell "
2580 "specification keyword '%s'", *argv);
2585 if (strcmp(*argv, "path") == 0) {
2587 } else if (strcmp(*argv, "name") == 0) {
2589 } else if (strcmp(*argv, "quiet") == 0) {
2590 newShell.echoOff = eq;
2592 } else if (strcmp(*argv, "echo") == 0) {
2593 newShell.echoOn = eq;
2595 } else if (strcmp(*argv, "filter") == 0) {
2596 newShell.noPrint = eq;
2598 } else if (strcmp(*argv, "echoFlag") == 0) {
2601 } else if (strcmp(*argv, "errFlag") == 0) {
2604 } else if (strcmp(*argv, "hasErrCtl") == 0) {
2605 newShell.hasErrCtl = (*eq == 'Y' || *eq == 'y' ||
2606 *eq == 'T' || *eq == 't');
2608 } else if (strcmp(*argv, "check") == 0) {
2609 newShell.errCheck = eq;
2611 } else if (strcmp(*argv, "ignore") == 0) {
2612 newShell.ignErr = eq;
2615 Parse_Error(PARSE_FATAL, "unknown keyword in shell "
2616 "specification '%s'", *argv);
2622 * Some checks (could be more)
2625 if ((newShell.echoOn != NULL) ^ (newShell.echoOff != NULL))
2626 Parse_Error(PARSE_FATAL, "Shell must have either both "
2627 "echoOff and echoOn or none of them");
2629 if (newShell.echoOn != NULL && newShell.echoOff)
2630 newShell.hasEchoCtl = TRUE;
2635 * If no path was given, the user wants one of the pre-defined
2636 * shells, yes? So we find the one s/he wants with the help of
2637 * JobMatchShell and set things up the right way. shellPath
2638 * will be set up by Job_Init.
2640 if (newShell.name == NULL) {
2641 Parse_Error(PARSE_FATAL,
2642 "Neither path nor name specified");
2645 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2646 Parse_Error(PARSE_FATAL, "%s: no matching shell",
2653 * The user provided a path. If s/he gave nothing else
2654 * (fullSpec is FALSE), try and find a matching shell in the
2655 * ones we know of. Else we just take the specification at its
2656 * word and copy it to a new location. In either case, we need
2657 * to record the path the user gave for the shell.
2660 shellPath = estrdup(path);
2661 if (newShell.name == NULL) {
2662 /* get the base name as the name */
2663 path = strrchr(path, '/');
2669 newShell.name = path;
2673 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2674 Parse_Error(PARSE_FATAL,
2675 "%s: no matching shell", newShell.name);
2679 sh = JobCopyShell(&newShell);
2683 /* set the new shell */
2684 JobFreeShell(commandShell);
2687 shellName = commandShell->name;
2694 * Handle the receipt of an interrupt.
2697 * All children are killed. Another job will be started if the
2698 * .INTERRUPT target was given.
2701 JobInterrupt(int runINTERRUPT, int signo)
2703 Job *job; /* job descriptor in that element */
2704 GNode *interrupt; /* the node describing the .INTERRUPT target */
2706 aborting = ABORT_INTERRUPT;
2708 TAILQ_FOREACH(job, &jobs, link) {
2709 if (!Targ_Precious(job->node)) {
2710 char *file = (job->node->path == NULL ?
2711 job->node->name : job->node->path);
2713 if (!noExecute && eunlink(file) != -1) {
2714 Error("*** %s removed", file);
2718 DEBUGF(JOB, ("JobInterrupt passing signal to child "
2719 "%jd.\n", (intmax_t)job->pid));
2720 KILL(job->pid, signo);
2724 if (runINTERRUPT && !touchFlag) {
2726 * clear the interrupted flag because we would get an
2727 * infinite loop otherwise.
2731 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2732 if (interrupt != NULL) {
2733 ignoreErrors = FALSE;
2735 JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
2738 Job_CatchChildren(!usePipes);
2746 * Do final processing such as the running of the commands
2747 * attached to the .END target.
2750 * Number of errors reported.
2756 if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
2758 Error("Errors reported so .END ignored");
2760 JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
2764 Job_CatchChildren(!usePipes);
2779 * Waits for all running jobs to finish and returns. Sets 'aborting'
2780 * to ABORT_WAIT to prevent other jobs from starting.
2783 * Currently running jobs finish.
2789 aborting = ABORT_WAIT;
2790 while (nJobs != 0) {
2792 Job_CatchChildren(!usePipes);
2799 * Abort all currently running jobs without handling output or anything.
2800 * This function is to be called only in the event of a major
2801 * error. Most definitely NOT to be called from JobInterrupt.
2804 * All children are killed, not just the firstborn
2809 Job *job; /* the job descriptor in that element */
2812 aborting = ABORT_ERROR;
2815 TAILQ_FOREACH(job, &jobs, link) {
2817 * kill the child process with increasingly drastic
2818 * signals to make darn sure it's dead.
2820 KILL(job->pid, SIGINT);
2821 KILL(job->pid, SIGKILL);
2826 * Catch as many children as want to report in at first, then give up
2828 while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2834 * Tries to restart stopped jobs if there are slots available.
2835 * Note that this tries to restart them regardless of pending errors.
2836 * It's not good to leave stopped jobs lying around!
2839 * Resumes(and possibly migrates) jobs.
2842 JobRestartJobs(void)
2846 while (!jobFull && (job = TAILQ_FIRST(&stoppedJobs)) != NULL) {
2847 DEBUGF(JOB, ("Job queue is not full. "
2848 "Restarting a stopped job.\n"));
2849 TAILQ_REMOVE(&stoppedJobs, job, link);