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.50 2005/04/07 00:44:18 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/types.h>
101 #include <sys/select.h>
102 #include <sys/stat.h>
104 #include <sys/event.h>
106 #include <sys/wait.h>
125 #include "pathnames.h"
131 #define STATIC static
134 * error handling variables
136 static int errors = 0; /* number of errors reported */
137 static int aborting = 0; /* why is the make aborting? */
138 #define ABORT_ERROR 1 /* Because of an error */
139 #define ABORT_INTERRUPT 2 /* Because it was interrupted */
140 #define ABORT_WAIT 3 /* Waiting for jobs to finish */
143 * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
144 * is a char! So when we go above 127 we turn negative!
146 #define FILENO(a) ((unsigned)fileno(a))
149 * post-make command processing. The node postCommands is really just the
150 * .END target but we keep it around to avoid having to search for it
153 static GNode *postCommands;
156 * The number of commands actually printed for a target. Should this
157 * number be 0, no shell will be executed.
159 static int numCommands;
162 * Return values from JobStart.
164 #define JOB_RUNNING 0 /* Job is running */
165 #define JOB_ERROR 1 /* Error in starting the job */
166 #define JOB_FINISHED 2 /* The job is already finished */
167 #define JOB_STOPPED 3 /* The job is stopped */
170 * tfile is used to build temp file names to store shell commands to
173 static char tfile[sizeof(TMPPAT)];
176 * Descriptions for various shells.
178 static const DEF_SHELL_STRUCT(CShell, const) shells[] = {
180 * CSH description. The csh can do echo control by playing
181 * with the setting of the 'echo' shell variable. Sadly,
182 * however, it is unable to do error control nicely.
186 TRUE, "unset verbose", "set verbose", "unset verbose", 13,
187 FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"",
191 * SH description. Echo control is also possible and, under
192 * sun UNIX anyway, one can even control error checking.
196 TRUE, "set -", "set -v", "set -", 5,
197 TRUE, "set -e", "set +e",
198 #ifdef OLDBOURNESHELL
199 FALSE, "echo \"%s\"\n", "sh -c '%s || exit 0'\n",
204 * KSH description. The Korn shell has a superset of
205 * the Bourne shell's functionality.
209 TRUE, "set -", "set -v", "set -", 5,
210 TRUE, "set -e", "set +e",
216 * This is the shell to which we pass all commands in the Makefile.
217 * It is set by the Job_ParseShell function.
219 static Shell *commandShell = NULL;
220 char *shellPath = NULL; /* full pathname of executable image */
221 char *shellName = NULL; /* last component of shell */
223 int maxJobs; /* The most children we can run at once */
224 STATIC int nJobs; /* The number of children currently running */
226 /* The structures that describe them */
227 STATIC Lst jobs = Lst_Initializer(jobs);
229 STATIC Boolean jobFull; /* Flag to tell when the job table is full. It
230 * is set TRUE when (1) the total number of
231 * running jobs equals the maximum allowed */
233 static int kqfd; /* File descriptor obtained by kqueue() */
235 static fd_set outputs; /* Set of descriptors of pipes connected to
236 * the output channels of children */
239 STATIC GNode *lastNode; /* The node for which output was most recently
241 STATIC const char *targFmt; /* Format string to use to head output from a
242 * job when it's not the most-recent job heard
245 #define TARG_FMT "--- %s ---\n" /* Default format */
246 #define MESSAGE(fp, gn) \
247 fprintf(fp, targFmt, gn->name);
250 * When JobStart attempts to run a job but isn't allowed to
251 * or when Job_CatchChildren detects a job that has
252 * been stopped somehow, the job is placed on the stoppedJobs queue to be run
253 * when the next job finishes.
255 * Lst of Job structures describing jobs that were stopped due to
256 * concurrency limits or externally
258 STATIC Lst stoppedJobs = Lst_Initializer(stoppedJobs);
260 STATIC int fifoFd; /* Fd of our job fifo */
261 STATIC char fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
262 STATIC int fifoMaster;
264 static sig_atomic_t interrupted;
267 #if defined(USE_PGRP) && defined(SYSV)
268 # define KILL(pid, sig) killpg(-(pid), (sig))
270 # if defined(USE_PGRP)
271 # define KILL(pid, sig) killpg((pid), (sig))
273 # define KILL(pid, sig) kill((pid), (sig))
278 * Grmpf... There is no way to set bits of the wait structure
279 * anymore with the stupid W*() macros. I liked the union wait
280 * stuff much more. So, we devise our own macros... This is
281 * really ugly, use dramamine sparingly. You have been warned.
283 #define W_SETMASKED(st, val, fun) \
286 int mask = fun(sh); \
288 for (sh = 0; ((mask >> sh) & 1) == 0; sh++) \
290 *(st) = (*(st) & ~mask) | ((val) << sh); \
293 #define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
294 #define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
296 static void JobPassSig(int);
297 static int JobPrintCommand(void *, void *);
298 static void JobClose(Job *);
299 static void JobFinish(Job *, int *);
300 static void JobExec(Job *, char **);
301 static void JobMakeArgv(Job *, char **);
302 static void JobRestart(Job *);
303 static int JobStart(GNode *, int, Job *);
304 static char *JobOutput(Job *, char *, char *, int);
305 static void JobDoOutput(Job *, Boolean);
306 static Shell *JobMatchShell(const char *);
307 static void JobInterrupt(int, int);
308 static void JobRestartJobs(void);
312 * Got a signal. Set global variables and hope that someone will
316 JobCatchSig(int signo)
324 * Pass a signal to all jobs
327 * None, except the job may bite it.
330 JobCondPassSig(int signo)
335 LST_FOREACH(ln, &jobs) {
338 DEBUGF(JOB, ("JobCondPassSig passing signal %d to child %d.\n",
340 KILL(job->pid, signo);
346 * Pass a signal on to all local jobs if
347 * USE_PGRP is defined, then die ourselves.
350 * We die by the same signal.
353 JobPassSig(int signo)
355 sigset_t nmask, omask;
356 struct sigaction act;
359 sigaddset(&nmask, signo);
360 sigprocmask(SIG_SETMASK, &nmask, &omask);
362 DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
363 JobCondPassSig(signo);
366 * Deal with proper cleanup based on the signal received. We only run
367 * the .INTERRUPT target if the signal was in fact an interrupt.
368 * The other three termination signals are more of a "get out *now*"
371 if (signo == SIGINT) {
372 JobInterrupt(TRUE, signo);
373 } else if ((signo == SIGHUP) || (signo == SIGTERM) || (signo == SIGQUIT)) {
374 JobInterrupt(FALSE, signo);
378 * Leave gracefully if SIGQUIT, rather than core dumping.
380 if (signo == SIGQUIT) {
385 * Send ourselves the signal now we've given the message to everyone
386 * else. Note we block everything else possible while we're getting
387 * the signal. This ensures that all our jobs get continued when we
388 * wake up before we take any other signal.
389 * XXX this comment seems wrong.
391 act.sa_handler = SIG_DFL;
392 sigemptyset(&act.sa_mask);
394 sigaction(signo, &act, NULL);
396 DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
397 ~0 & ~(1 << (signo - 1))));
398 signal(signo, SIG_DFL);
400 KILL(getpid(), signo);
403 JobCondPassSig(signo);
405 sigprocmask(SIG_SETMASK, &omask, NULL);
406 sigprocmask(SIG_SETMASK, &omask, NULL);
407 act.sa_handler = JobPassSig;
408 sigaction(signo, &act, NULL);
413 * Put out another command for the given job. If the command starts
414 * with an @ or a - we process it specially. In the former case,
415 * so long as the -s and -n flags weren't given to make, we stick
416 * a shell-specific echoOff command in the script. In the latter,
417 * we ignore errors for the entire job, unless the shell has error
419 * If the command is just "..." we take all future commands for this
420 * job to be commands to be executed once the entire graph has been
421 * made and return non-zero to signal that the end of the commands
422 * was reached. These commands are later attached to the postCommands
423 * node and executed by Job_Finish when all things are done.
424 * This function is called from JobStart via LST_FOREACH.
427 * Always 0, unless the command was "..."
430 * If the command begins with a '-' and the shell has no error control,
431 * the JOB_IGNERR flag is set in the job descriptor.
432 * If the command is "..." and we're not ignoring such things,
433 * tailCmds is set to the successor node of the cmd.
434 * numCommands is incremented if the command is actually printed.
437 JobPrintCommand(void *cmdp, void *jobp)
439 Boolean noSpecials; /* true if we shouldn't worry about
440 * inserting special commands into
441 * the input stream. */
442 Boolean shutUp = FALSE; /* true if we put a no echo command
443 * into the command file */
444 Boolean errOff = FALSE; /* true if we turned error checking
445 * off before printing the command
446 * and need to turn it back on */
447 const char *cmdTemplate;/* Template to use when printing the command */
448 char *cmdStart; /* Start of expanded command */
449 LstNode *cmdNode; /* Node for replacing the command */
453 noSpecials = (noExecute && !(job->node->type & OP_MAKE));
455 if (strcmp(cmd, "...") == 0) {
456 job->node->type |= OP_SAVE_CMDS;
457 if ((job->flags & JOB_IGNDOTS) == 0) {
459 Lst_Succ(Lst_Member(&job->node->commands, cmd));
465 #define DBPRINTF(fmt, arg) \
466 DEBUGF(JOB, (fmt, arg)); \
467 fprintf(job->cmdFILE, fmt, arg); \
468 fflush(job->cmdFILE);
473 * For debugging, we replace each command with the result of expanding
474 * the variables in the command.
476 cmdNode = Lst_Member(&job->node->commands, cmd);
478 cmd = Buf_Peel(Var_Subst(NULL, cmd, job->node, FALSE));
481 Lst_Replace(cmdNode, cmdStart);
483 cmdTemplate = "%s\n";
486 * Check for leading @', -' or +'s to control echoing, error checking,
487 * and execution on -n.
489 while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
493 shutUp = DEBUG(LOUD) ? FALSE : TRUE;
503 * We're not actually exececuting anything...
504 * but this one needs to be - use compat mode
507 Compat_RunCommand(cmdp, job->node);
515 while (isspace((unsigned char)*cmd))
519 if (!(job->flags & JOB_SILENT) && !noSpecials &&
520 commandShell->hasEchoCtl) {
521 DBPRINTF("%s\n", commandShell->echoOff);
528 if (!(job->flags & JOB_IGNERR) && !noSpecials) {
529 if (commandShell->hasErrCtl) {
531 * We don't want the error-control commands
532 * showing up either, so we turn off echoing
533 * while executing them. We could put another
534 * field in the shell structure to tell
535 * JobDoOutput to look for this string too,
536 * but why make it any more complex than
539 if (!(job->flags & JOB_SILENT) && !shutUp &&
540 commandShell->hasEchoCtl) {
541 DBPRINTF("%s\n", commandShell->echoOff);
542 DBPRINTF("%s\n", commandShell->ignErr);
543 DBPRINTF("%s\n", commandShell->echoOn);
545 DBPRINTF("%s\n", commandShell->ignErr);
547 } else if (commandShell->ignErr &&
548 (*commandShell->ignErr != '\0')) {
550 * The shell has no error control, so we need to
551 * be weird to get it to ignore any errors from
552 * the command. If echoing is turned on, we turn
553 * it off and use the errCheck template to echo
554 * the command. Leave echoing off so the user
555 * doesn't see the weirdness we go through to
556 * ignore errors. Set cmdTemplate to use the
557 * weirdness instead of the simple "%s\n"
560 if (!(job->flags & JOB_SILENT) && !shutUp &&
561 commandShell->hasEchoCtl) {
562 DBPRINTF("%s\n", commandShell->echoOff);
563 DBPRINTF(commandShell->errCheck, cmd);
566 cmdTemplate = commandShell->ignErr;
568 * The error ignoration (hee hee) is already
569 * taken care of by the ignErr template, so
570 * pretend error checking is still on.
581 DBPRINTF(cmdTemplate, cmd);
585 * If echoing is already off, there's no point in issuing the
586 * echoOff command. Otherwise we issue it and pretend it was on
587 * for the whole command...
589 if (!shutUp && !(job->flags & JOB_SILENT) &&
590 commandShell->hasEchoCtl) {
591 DBPRINTF("%s\n", commandShell->echoOff);
594 DBPRINTF("%s\n", commandShell->errCheck);
597 DBPRINTF("%s\n", commandShell->echoOn);
604 * Called to close both input and output pipes when a job is finished.
607 * The file descriptors associated with the job are closed.
614 #if !defined(USE_KQUEUE)
615 FD_CLR(job->inPipe, &outputs);
617 if (job->outPipe != job->inPipe) {
620 JobDoOutput(job, TRUE);
624 JobDoOutput(job, TRUE);
630 * Do final processing for the given job including updating
631 * parents and starting new jobs as available/necessary. Note
632 * that we pay no attention to the JOB_IGNERR flag here.
633 * This is because when we're called because of a noexecute flag
634 * or something, jstat.w_status is 0 and when called from
635 * Job_CatchChildren, the status is zeroed if it s/b ignored.
638 * Some nodes may be put on the toBeMade queue.
639 * Final commands for the job are placed on postCommands.
641 * If we got an error and are aborting (aborting == ABORT_ERROR) and
642 * the job list is now empty, we are done for the day.
643 * If we recognized an error (errors !=0), we set the aborting flag
644 * to ABORT_ERROR so no more jobs will be started.
647 JobFinish(Job *job, int *status)
652 if ((WIFEXITED(*status) &&
653 (((WEXITSTATUS(*status) != 0) && !(job->flags & JOB_IGNERR)))) ||
654 (WIFSIGNALED(*status) && (WTERMSIG(*status) != SIGCONT))) {
656 * If it exited non-zero and either we're doing things our
657 * way or we're not ignoring errors, the job is finished.
658 * Similarly, if the shell died because of a signal
659 * the job is also finished. In these cases, finish out the
660 * job's output before printing the exit status...
663 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
664 fclose(job->cmdFILE);
668 } else if (WIFEXITED(*status)) {
670 * Deal with ignored errors in -B mode. We need to print a
671 * message telling of the ignored error as well as setting
672 * status.w_status to 0 so the next command gets run. To do
673 * this, we set done to be TRUE if in -B mode and the job
676 done = WEXITSTATUS(*status) != 0;
679 * Old comment said: "Note we don't want to close down any of
680 * the streams until we know we're at the end." But we do.
681 * Otherwise when are we going to print the rest of the stuff?
686 * No need to close things down or anything.
691 if (done || WIFSTOPPED(*status) ||
692 (WIFSIGNALED(*status) && (WTERMSIG(*status) == SIGCONT)) ||
696 if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
698 * If output is going to a file and this job is ignoring
699 * errors, arrange to have the exit status sent to the
700 * output file as well.
702 out = fdopen(job->outFd, "w");
704 Punt("Cannot fdopen");
709 if (WIFEXITED(*status)) {
710 DEBUGF(JOB, ("Process %d exited.\n", job->pid));
711 if (WEXITSTATUS(*status) != 0) {
712 if (usePipes && job->node != lastNode) {
713 MESSAGE(out, job->node);
714 lastNode = job->node;
716 fprintf(out, "*** Error code %d%s\n",
717 WEXITSTATUS(*status),
718 (job->flags & JOB_IGNERR) ?
721 if (job->flags & JOB_IGNERR) {
724 } else if (DEBUG(JOB)) {
725 if (usePipes && job->node != lastNode) {
726 MESSAGE(out, job->node);
727 lastNode = job->node;
729 fprintf(out, "*** Completed successfully\n");
732 } else if (WIFSTOPPED(*status)) {
733 DEBUGF(JOB, ("Process %d stopped.\n", job->pid));
734 if (usePipes && job->node != lastNode) {
735 MESSAGE(out, job->node);
736 lastNode = job->node;
738 fprintf(out, "*** Stopped -- signal %d\n",
740 job->flags |= JOB_RESUME;
741 Lst_AtEnd(&stoppedJobs, job);
745 } else if (WTERMSIG(*status) == SIGCONT) {
747 * If the beastie has continued, shift the Job from
748 * the stopped list to the running one (or re-stop it
749 * if concurrency is exceeded) and go and get another
752 if (job->flags & (JOB_RESUME|JOB_RESTART)) {
753 if (usePipes && job->node != lastNode) {
754 MESSAGE(out, job->node);
755 lastNode = job->node;
757 fprintf(out, "*** Continued\n");
759 if (!(job->flags & JOB_CONTINUING)) {
760 DEBUGF(JOB, ("Warning: process %d was not "
761 "continuing.\n", job->pid));
764 * We don't really want to restart a job from
765 * scratch just because it continued, especially
766 * not without killing the continuing process!
767 * That's why this is ifdef'ed out.
773 job->flags &= ~JOB_CONTINUING;
774 Lst_AtEnd(&jobs, job);
776 DEBUGF(JOB, ("Process %d is continuing locally.\n",
778 if (nJobs == maxJobs) {
780 DEBUGF(JOB, ("Job queue is full.\n"));
786 if (usePipes && job->node != lastNode) {
787 MESSAGE(out, job->node);
788 lastNode = job->node;
790 fprintf(out, "*** Signal %d\n", WTERMSIG(*status));
797 * Now handle the -B-mode stuff. If the beast still isn't finished,
798 * try and restart the job on the next command. If JobStart says it's
799 * ok, it's ok. If there's an error, this puppy is done.
801 if (compatMake && WIFEXITED(*status) &&
802 Lst_Succ(job->node->compat_command) != NULL) {
803 switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
809 W_SETEXITSTATUS(status, 1);
813 * If we got back a JOB_FINISHED code, JobStart has
814 * already called Make_Update and freed the job
815 * descriptor. We set done to false here to avoid fake
816 * cycles and double frees. JobStart needs to do the
817 * update so we can proceed up the graph when given
829 if (done && (aborting != ABORT_ERROR) &&
830 (aborting != ABORT_INTERRUPT) && (*status == 0)) {
832 * As long as we aren't aborting and the job didn't return a
833 * non-zero status that we shouldn't ignore, we call
834 * Make_Update to update the parents. In addition, any saved
835 * commands for the node are placed on the .END target.
837 for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
838 Lst_AtEnd(&postCommands->commands,
839 Buf_Peel(Var_Subst(NULL, Lst_Datum(ln),
843 job->node->made = MADE;
844 Make_Update(job->node);
847 } else if (*status != 0) {
855 * Set aborting if any error.
857 if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
859 * If we found any errors in this batch of children and the -k
860 * flag wasn't given, we set the aborting flag so no more jobs
863 aborting = ABORT_ERROR;
866 if ((aborting == ABORT_ERROR) && Job_Empty()) {
868 * If we are aborting and the job table is now empty, we finish.
876 * Touch the given target. Called by JobStart when the -t flag was
877 * given. Prints messages unless told to be silent.
880 * The data modification of the file is changed. In addition, if the
881 * file did not exist, it is created.
884 Job_Touch(GNode *gn, Boolean silent)
886 int streamID; /* ID of stream opened to do the touch */
887 struct utimbuf times; /* Times for utime() call */
889 if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
891 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
892 * targets and, as such, shouldn't really be created.
898 fprintf(stdout, "touch %s\n", gn->name);
906 if (gn->type & OP_ARCHV) {
908 } else if (gn->type & OP_LIB) {
911 char *file = gn->path ? gn->path : gn->name;
913 times.actime = times.modtime = now;
914 if (utime(file, ×) < 0) {
915 streamID = open(file, O_RDWR | O_CREAT, 0666);
921 * Read and write a byte to the file to change
922 * the modification time, then close the file.
924 if (read(streamID, &c, 1) == 1) {
925 lseek(streamID, (off_t)0, SEEK_SET);
926 write(streamID, &c, 1);
931 fprintf(stdout, "*** couldn't touch %s: %s",
932 file, strerror(errno));
941 * Make sure the given node has all the commands it needs.
944 * TRUE if the commands list is/was ok.
947 * The node will have commands from the .DEFAULT rule added to it
951 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
954 if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
955 (gn->type & OP_LIB) == 0) {
957 * No commands. Look for .DEFAULT rule from which we might infer
960 if ((DEFAULT != NULL) && !Lst_IsEmpty(&DEFAULT->commands)) {
963 * Make only looks for a .DEFAULT if the node was
964 * never the target of an operator, so that's what we
965 * do too. If a .DEFAULT was given, we substitute its
966 * commands for gn's commands and set the IMPSRC
967 * variable to be the target's name The DEFAULT node
968 * acts like a transformation rule, in that gn also
969 * inherits any attributes or sources attached to
972 Make_HandleUse(DEFAULT, gn);
973 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn);
976 } else if (Dir_MTime(gn) == 0) {
978 * The node wasn't the target of an operator we have
979 * no .DEFAULT rule to go on and the target doesn't
980 * already exist. There's nothing more we can do for
981 * this branch. If the -k flag wasn't given, we stop
982 * in our tracks, otherwise we just don't update
983 * this node's parents so they never get examined.
985 static const char msg[] =
986 "make: don't know how to make";
988 if (gn->type & OP_OPTIONAL) {
989 fprintf(stdout, "%s %s(ignored)\n",
992 } else if (keepgoing) {
993 fprintf(stdout, "%s %s(continuing)\n",
999 if (strcmp(gn->name,"love") == 0)
1000 (*abortProc)("Not war.");
1003 (*abortProc)("%s %s. Stop",
1014 * Execute the shell for the given job. Called from JobStart and
1018 * A shell is executed, outputs is altered and the Job structure added
1022 JobExec(Job *job, char **argv)
1024 int cpid; /* ID of new child */
1029 DEBUGF(JOB, ("Running %s\n", job->node->name));
1030 DEBUGF(JOB, ("\tCommand: "));
1031 for (i = 0; argv[i] != NULL; i++) {
1032 DEBUGF(JOB, ("%s ", argv[i]));
1034 DEBUGF(JOB, ("\n"));
1038 * Some jobs produce no output and it's disconcerting to have
1039 * no feedback of their running (since they produce no output, the
1040 * banner with their name in it never appears). This is an attempt to
1041 * provide that feedback, even if nothing follows it.
1043 if ((lastNode != job->node) && (job->flags & JOB_FIRST) &&
1044 !(job->flags & JOB_SILENT)) {
1045 MESSAGE(stdout, job->node);
1046 lastNode = job->node;
1049 if ((cpid = vfork()) == -1) {
1050 Punt("Cannot fork");
1052 } else if (cpid == 0) {
1057 * Must duplicate the input stream down to the child's input and
1058 * reset it to the beginning (again). Since the stream was
1059 * marked close-on-exec, we must clear that bit in the new
1062 if (dup2(FILENO(job->cmdFILE), 0) == -1)
1063 Punt("Cannot dup2: %s", strerror(errno));
1064 fcntl(0, F_SETFD, 0);
1065 lseek(0, (off_t)0, SEEK_SET);
1069 * Set up the child's output to be routed through the
1070 * pipe we've created for it.
1072 if (dup2(job->outPipe, 1) == -1)
1073 Punt("Cannot dup2: %s", strerror(errno));
1076 * We're capturing output in a file, so we duplicate the
1077 * descriptor to the temporary file into the standard
1080 if (dup2(job->outFd, 1) == -1)
1081 Punt("Cannot dup2: %s", strerror(errno));
1084 * The output channels are marked close on exec. This bit was
1085 * duplicated by the dup2 (on some systems), so we have to clear
1086 * it before routing the shell's error output to the same place
1087 * as its standard output.
1089 fcntl(1, F_SETFD, 0);
1090 if (dup2(1, 2) == -1)
1091 Punt("Cannot dup2: %s", strerror(errno));
1095 * We want to switch the child into a different process family
1096 * so we can kill it and all its descendants in one fell swoop,
1097 * by killing its process family, but not commit suicide.
1102 setpgid(0, getpid());
1104 #endif /* USE_PGRP */
1106 execv(shellPath, argv);
1108 write(STDERR_FILENO, "Could not execute shell\n",
1109 sizeof("Could not execute shell"));
1115 if (usePipes && (job->flags & JOB_FIRST)) {
1117 * The first time a job is run for a node, we set the
1118 * current position in the buffer to the beginning and
1119 * mark another stream to watch in the outputs mask.
1122 struct kevent kev[2];
1126 #if defined(USE_KQUEUE)
1127 EV_SET(&kev[0], job->inPipe, EVFILT_READ,
1129 EV_SET(&kev[1], job->pid, EVFILT_PROC,
1130 EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
1131 if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1133 * kevent() will fail if the job is already
1136 if (errno != EINTR && errno != EBADF &&
1138 Punt("kevent: %s", strerror(errno));
1141 FD_SET(job->inPipe, &outputs);
1142 #endif /* USE_KQUEUE */
1145 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1146 fclose(job->cmdFILE);
1147 job->cmdFILE = NULL;
1152 * Now the job is actually running, add it to the table.
1155 Lst_AtEnd(&jobs, job);
1156 if (nJobs == maxJobs) {
1163 * Create the argv needed to execute the shell for a given job.
1166 JobMakeArgv(Job *job, char **argv)
1169 static char args[10]; /* For merged arguments */
1171 argv[0] = shellName;
1174 if ((commandShell->exit && (*commandShell->exit != '-')) ||
1175 (commandShell->echo && (*commandShell->echo != '-'))) {
1177 * At least one of the flags doesn't have a minus before it, so
1178 * merge them together. Have to do this because the *(&(@*#*&#$#
1179 * Bourne shell thinks its second argument is a file to source.
1180 * Grrrr. Note the ten-character limitation on the combined
1183 sprintf(args, "-%s%s", ((job->flags & JOB_IGNERR) ? "" :
1184 (commandShell->exit ? commandShell->exit : "")),
1185 ((job->flags & JOB_SILENT) ? "" :
1186 (commandShell->echo ? commandShell->echo : "")));
1193 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1194 argv[argc] = commandShell->exit;
1197 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1198 argv[argc] = commandShell->echo;
1207 * Restart a job that stopped for some reason.
1210 * jobFull will be set if the job couldn't be run.
1213 JobRestart(Job *job)
1216 if (job->flags & JOB_RESTART) {
1218 * Set up the control arguments to the shell. This is based on
1219 * the flags set earlier for this job. If the JOB_IGNERR flag
1220 * is clear, the 'exit' flag of the commandShell is used to
1221 * cause it to exit upon receiving an error. If the JOB_SILENT
1222 * flag is clear, the 'echo' flag of the commandShell is used
1223 * to get it to start echoing as soon as it starts
1224 * processing commands.
1228 JobMakeArgv(job, argv);
1230 DEBUGF(JOB, ("Restarting %s...", job->node->name));
1231 if (((nJobs >= maxJobs) && !(job->flags & JOB_SPECIAL))) {
1233 * Can't be exported and not allowed to run locally --
1234 * put it back on the hold queue and mark the table full
1236 DEBUGF(JOB, ("holding\n"));
1237 Lst_AtFront(&stoppedJobs, (void *)job);
1239 DEBUGF(JOB, ("Job queue is full.\n"));
1243 * Job may be run locally.
1245 DEBUGF(JOB, ("running locally\n"));
1251 * The job has stopped and needs to be restarted.
1252 * Why it stopped, we don't know...
1254 DEBUGF(JOB, ("Resuming %s...", job->node->name));
1255 if (((nJobs < maxJobs) || ((job->flags & JOB_SPECIAL) &&
1256 (maxJobs == 0))) && (nJobs != maxJobs)) {
1258 * If we haven't reached the concurrency limit already
1259 * (or the job must be run and maxJobs is 0), it's ok
1265 error = (KILL(job->pid, SIGCONT) != 0);
1269 * Make sure the user knows we've continued
1270 * the beast and actually put the thing in the
1273 job->flags |= JOB_CONTINUING;
1275 W_SETTERMSIG(&status, SIGCONT);
1276 JobFinish(job, &status);
1278 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1279 DEBUGF(JOB, ("done\n"));
1281 Error("couldn't resume %s: %s",
1282 job->node->name, strerror(errno));
1284 W_SETEXITSTATUS(&status, 1);
1285 JobFinish(job, &status);
1289 * Job cannot be restarted. Mark the table as full and
1290 * place the job back on the list of stopped jobs.
1292 DEBUGF(JOB, ("table full\n"));
1293 Lst_AtFront(&stoppedJobs, (void *)job);
1295 DEBUGF(JOB, ("Job queue is full.\n"));
1302 * Start a target-creation process going for the target described
1303 * by the graph node gn.
1306 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1307 * if there isn't actually anything left to do for the job and
1308 * JOB_RUNNING if the job has been started.
1311 * A new Job node is created and added to the list of running
1312 * jobs. PMake is forked and a child shell created.
1315 JobStart(GNode *gn, int flags, Job *previous)
1317 Job *job; /* new job descriptor */
1318 char *argv[4]; /* Argument vector to shell */
1319 Boolean cmdsOK; /* true if the nodes commands were all right */
1320 Boolean noExec; /* Set true if we decide not to run the job */
1321 int tfd; /* File descriptor for temp file */
1325 JobPassSig(interrupted);
1328 if (previous != NULL) {
1329 previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1332 job = emalloc(sizeof(Job));
1337 job->tailCmds = NULL;
1340 * Set the initial value of the flags for this job based on the global
1341 * ones and the node's attributes... Any flags supplied by the caller
1342 * are also added to the field.
1345 if (Targ_Ignore(gn)) {
1346 job->flags |= JOB_IGNERR;
1348 if (Targ_Silent(gn)) {
1349 job->flags |= JOB_SILENT;
1351 job->flags |= flags;
1354 * Check the commands now so any attributes from .DEFAULT have a chance
1355 * to migrate to the node.
1357 if (!compatMake && job->flags & JOB_FIRST) {
1358 cmdsOK = Job_CheckCommands(gn, Error);
1364 * If the -n flag wasn't given, we open up OUR (not the child's)
1365 * temporary file to stuff commands in it. The thing is rd/wr so we
1366 * don't need to reopen it to feed it to the shell. If the -n flag
1367 * *was* given, we just set the file to be stdout. Cute, huh?
1369 if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1371 * We're serious here, but if the commands were bogus, we're
1378 strcpy(tfile, TMPPAT);
1379 if ((tfd = mkstemp(tfile)) == -1)
1380 Punt("Cannot create temp file: %s", strerror(errno));
1381 job->cmdFILE = fdopen(tfd, "w+");
1383 if (job->cmdFILE == NULL) {
1385 Punt("Could not open %s", tfile);
1387 fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1389 * Send the commands to the command file, flush all its
1390 * buffers then rewind and remove the thing.
1395 * Used to be backwards; replace when start doing multiple
1396 * commands per shell.
1400 * Be compatible: If this is the first time for this
1401 * node, verify its commands are ok and open the
1402 * commands list for sequential access by later
1403 * invocations of JobStart. Once that is done, we take
1404 * the next command off the list and print it to the
1405 * command file. If the command was an ellipsis, note
1406 * that there's nothing more to execute.
1408 if (job->flags & JOB_FIRST)
1409 gn->compat_command = Lst_First(&gn->commands);
1411 gn->compat_command =
1412 Lst_Succ(gn->compat_command);
1414 if (gn->compat_command == NULL ||
1415 JobPrintCommand(Lst_Datum(gn->compat_command), job))
1418 if (noExec && !(job->flags & JOB_FIRST)) {
1420 * If we're not going to execute anything, the
1421 * job is done and we need to close down the
1422 * various file descriptors we've opened for
1423 * output, then call JobDoOutput to catch the
1424 * final characters or send the file to the
1425 * screen... Note that the i/o streams are only
1426 * open if this isn't the first job. Note also
1427 * that this could not be done in
1428 * Job_CatchChildren b/c it wasn't clear if
1429 * there were more commands to execute or not...
1435 * We can do all the commands at once. hooray for sanity
1438 LST_FOREACH(ln, &gn->commands) {
1439 if (JobPrintCommand(Lst_Datum(ln), job))
1444 * If we didn't print out any commands to the shell
1445 * script, there's not much point in executing the
1448 if (numCommands == 0) {
1453 } else if (noExecute) {
1455 * Not executing anything -- just print all the commands to
1456 * stdout in one fell swoop. This will still set up
1457 * job->tailCmds correctly.
1459 if (lastNode != gn) {
1460 MESSAGE(stdout, gn);
1463 job->cmdFILE = stdout;
1466 * Only print the commands if they're ok, but don't die if
1467 * they're not -- just let the user know they're bad and keep
1468 * going. It doesn't do any harm in this case and may do
1472 LST_FOREACH(ln, &gn->commands) {
1473 if (JobPrintCommand(Lst_Datum(ln), job))
1478 * Don't execute the shell, thank you.
1484 * Just touch the target and note that no shell should be
1485 * executed. Set cmdFILE to stdout to make life easier. Check
1486 * the commands, too, but don't die if they're no good -- it
1487 * does no harm to keep working up the graph.
1489 job->cmdFILE = stdout;
1490 Job_Touch(gn, job->flags & JOB_SILENT);
1495 * If we're not supposed to execute a shell, don't.
1499 * Unlink and close the command file if we opened one
1501 if (job->cmdFILE != stdout) {
1502 if (job->cmdFILE != NULL)
1503 fclose(job->cmdFILE);
1509 * We only want to work our way up the graph if we aren't here
1510 * because the commands for the job were no good.
1513 if (aborting == 0) {
1514 for (ln = job->tailCmds; ln != NULL;
1515 ln = LST_NEXT(ln)) {
1516 Lst_AtEnd(&postCommands->commands,
1517 Buf_Peel(Var_Subst(NULL,
1518 Lst_Datum(ln), job->node, FALSE)));
1520 job->node->made = MADE;
1521 Make_Update(job->node);
1524 return(JOB_FINISHED);
1530 fflush(job->cmdFILE);
1534 * Set up the control arguments to the shell. This is based on the flags
1535 * set earlier for this job.
1537 JobMakeArgv(job, argv);
1540 * If we're using pipes to catch output, create the pipe by which we'll
1541 * get the shell's output. If we're using files, print out that we're
1542 * starting a job and then set up its temporary-file name.
1544 if (!compatMake || (job->flags & JOB_FIRST)) {
1549 Punt("Cannot create pipe: %s", strerror(errno));
1550 job->inPipe = fd[0];
1551 job->outPipe = fd[1];
1552 fcntl(job->inPipe, F_SETFD, 1);
1553 fcntl(job->outPipe, F_SETFD, 1);
1555 fprintf(stdout, "Remaking `%s'\n", gn->name);
1557 strcpy(job->outFile, TMPPAT);
1558 if ((job->outFd = mkstemp(job->outFile)) == -1)
1559 Punt("cannot create temp file: %s",
1561 fcntl(job->outFd, F_SETFD, 1);
1565 if ((nJobs >= maxJobs) && !(job->flags & JOB_SPECIAL) && (maxJobs != 0)) {
1567 * We've hit the limit of concurrency, so put the job on hold
1568 * until some other job finishes. Note that the special jobs
1569 * (.BEGIN, .INTERRUPT and .END) may be run even when the
1570 * limit has been reached (e.g. when maxJobs == 0).
1574 DEBUGF(JOB, ("Can only run job locally.\n"));
1575 job->flags |= JOB_RESTART;
1576 Lst_AtEnd(&stoppedJobs, job);
1578 if (nJobs >= maxJobs) {
1580 * If we're running this job locally as a special case
1581 * (see above), at least say the table is full.
1584 DEBUGF(JOB, ("Local job queue is full.\n"));
1588 return (JOB_RUNNING);
1592 JobOutput(Job *job, char *cp, char *endp, int msg)
1596 if (commandShell->noPrint) {
1597 ecp = strstr(cp, commandShell->noPrint);
1598 while (ecp != NULL) {
1601 if (msg && job->node != lastNode) {
1602 MESSAGE(stdout, job->node);
1603 lastNode = job->node;
1606 * The only way there wouldn't be a newline
1607 * after this line is if it were the last in
1608 * the buffer. However, since the non-printable
1609 * comes after it, there must be a newline, so
1610 * we don't print one.
1612 fprintf(stdout, "%s", cp);
1615 cp = ecp + commandShell->noPLen;
1618 * Still more to print, look again after
1619 * skipping the whitespace following the
1620 * non-printable command....
1623 while (*cp == ' ' || *cp == '\t' ||
1627 ecp = strstr(cp, commandShell->noPrint);
1638 * This function is called at different times depending on
1639 * whether the user has specified that output is to be collected
1640 * via pipes or temporary files. In the former case, we are called
1641 * whenever there is something to read on the pipe. We collect more
1642 * output from the given job and store it in the job's outBuf. If
1643 * this makes up a line, we print it tagged by the job's identifier,
1645 * If output has been collected in a temporary file, we open the
1646 * file and read it line by line, transfering it to our own
1647 * output channel until the file is empty. At which point we
1648 * remove the temporary file.
1649 * In both cases, however, we keep our figurative eye out for the
1650 * 'noPrint' line for the shell from which the output came. If
1651 * we recognize a line, we don't print it. If the command is not
1652 * alone on the line (the character after it is not \0 or \n), we
1653 * do print whatever follows it.
1656 * curPos may be shifted as may the contents of outBuf.
1659 JobDoOutput(Job *job, Boolean finish)
1661 Boolean gotNL = FALSE; /* true if got a newline */
1662 Boolean fbuf; /* true if our buffer filled up */
1663 int nr; /* number of bytes read */
1664 int i; /* auxiliary index into outBuf */
1665 int max; /* limit for i (end of current data) */
1666 int nRead; /* (Temporary) number of bytes read */
1667 FILE *oFILE; /* Stream pointer to shell's output file */
1672 * Read as many bytes as will fit in the buffer.
1678 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1679 JOB_BUFSIZE - job->curPos);
1681 * Check for interrupt here too, because the above read may
1682 * block when the child process is stopped. In this case the
1683 * interrupt will unblock it (we don't use SA_RESTART).
1686 JobPassSig(interrupted);
1689 DEBUGF(JOB, ("JobDoOutput(piperead)"));
1696 * If we hit the end-of-file (the job is dead), we must flush
1697 * its remaining output, so pretend we read a newline if
1698 * there's any output remaining in the buffer.
1699 * Also clear the 'finish' flag so we stop looping.
1701 if ((nr == 0) && (job->curPos != 0)) {
1702 job->outBuf[job->curPos] = '\n';
1705 } else if (nr == 0) {
1710 * Look for the last newline in the bytes we just got. If there
1711 * is one, break out of the loop with 'i' as its index and
1714 max = job->curPos + nr;
1715 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1716 if (job->outBuf[i] == '\n') {
1719 } else if (job->outBuf[i] == '\0') {
1723 job->outBuf[i] = ' ';
1729 if (job->curPos == JOB_BUFSIZE) {
1731 * If we've run out of buffer space, we have
1732 * no choice but to print the stuff. sigh.
1738 if (gotNL || fbuf) {
1740 * Need to send the output to the screen. Null terminate
1741 * it first, overwriting the newline character if there
1742 * was one. So long as the line isn't one we should
1743 * filter (according to the shell description), we print
1744 * the line, preceded by a target banner if this target
1745 * isn't the same as the one for which we last printed
1746 * something. The rest of the data in the buffer are
1747 * then shifted down to the start of the buffer and
1748 * curPos is set accordingly.
1750 job->outBuf[i] = '\0';
1751 if (i >= job->curPos) {
1754 cp = JobOutput(job, job->outBuf,
1755 &job->outBuf[i], FALSE);
1758 * There's still more in that buffer. This time,
1759 * though, we know there's no newline at the
1760 * end, so we add one of our own free will.
1763 if (job->node != lastNode) {
1764 MESSAGE(stdout, job->node);
1765 lastNode = job->node;
1767 fprintf(stdout, "%s%s", cp,
1773 /* shift the remaining characters down */
1774 memcpy(job->outBuf, &job->outBuf[i + 1],
1776 job->curPos = max - (i + 1);
1780 * We have written everything out, so we just
1781 * start over from the start of the buffer.
1782 * No copying. No nothing.
1789 * If the finish flag is true, we must loop until we hit
1790 * end-of-file on the pipe. This is guaranteed to happen
1791 * eventually since the other end of the pipe is now
1792 * closed (we closed it explicitly and the child has
1793 * exited). When we do get an EOF, finish will be set
1794 * FALSE and we'll fall through and out.
1801 * We've been called to retrieve the output of the job from the
1802 * temporary file where it's been squirreled away. This consists
1803 * of opening the file, reading the output line by line, being
1804 * sure not to print the noPrint line for the shell we used,
1805 * then close and remove the temporary file. Very simple.
1807 * Change to read in blocks and do FindSubString type things
1808 * as for pipes? That would allow for "@echo -n..."
1810 oFILE = fopen(job->outFile, "r");
1811 if (oFILE != NULL) {
1812 fprintf(stdout, "Results of making %s:\n",
1816 while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
1817 char *cp, *endp, *oendp;
1820 oendp = endp = inLine + strlen(inLine);
1821 if (endp[-1] == '\n') {
1824 cp = JobOutput(job, inLine, endp, FALSE);
1827 * There's still more in that buffer. This time,
1828 * though, we know there's no newline at the
1829 * end, so we add one of our own free will.
1831 fprintf(stdout, "%s", cp);
1833 if (endp != oendp) {
1834 fprintf(stdout, "\n");
1839 eunlink(job->outFile);
1846 * Handle the exit of a child. Called from Make_Make.
1849 * The job descriptor is removed from the list of children.
1852 * We do waits, blocking or not, according to the wisdom of our
1853 * caller, until there are no more children to report. For each
1854 * job, call JobFinish to finish things off. This will take care of
1855 * putting jobs on the stoppedJobs queue.
1858 Job_CatchChildren(Boolean block)
1860 int pid; /* pid of dead child */
1861 Job *job; /* job descriptor for dead child */
1862 LstNode *jnode; /* list element for finding job */
1863 int status; /* Exit/termination status */
1866 * Don't even bother if we know there's no one around.
1873 pid = waitpid((pid_t)-1, &status,
1874 (block ? 0 : WNOHANG) | WUNTRACED);
1878 DEBUGF(JOB, ("Process %d exited or stopped.\n", pid));
1880 LST_FOREACH(jnode, &jobs) {
1881 if (((const Job *)Lst_Datum(jnode))->pid == pid)
1885 if (jnode == NULL) {
1886 if (WIFSIGNALED(status) &&
1887 (WTERMSIG(status) == SIGCONT)) {
1888 LST_FOREACH(jnode, &stoppedJobs) {
1889 if (((const Job *)Lst_Datum(jnode))->pid == pid)
1892 if (jnode == NULL) {
1893 Error("Resumed child (%d) not in table",
1897 job = Lst_Datum(jnode);
1898 Lst_Remove(&stoppedJobs, jnode);
1900 Error("Child (%d) not in table?", pid);
1904 job = Lst_Datum(jnode);
1905 Lst_Remove(&jobs, jnode);
1907 if (fifoFd >= 0 && maxJobs > 1) {
1908 write(fifoFd, "+", 1);
1910 if (nJobs >= maxJobs)
1915 DEBUGF(JOB, ("Job queue is no longer full.\n"));
1920 JobFinish(job, &status);
1923 JobPassSig(interrupted);
1928 * Catch the output from our children, if we're using
1929 * pipes do so. Otherwise just block time until we get a
1930 * signal(most likely a SIGCHLD) since there's no point in
1931 * just spinning when there's nothing to do and the reaping
1932 * of a child can wait for a while.
1935 * Output is read from pipes if we're piping.
1936 * -----------------------------------------------------------------------
1940 Job_CatchOutput(int flag __unused)
1942 Job_CatchOutput(int flag)
1948 struct kevent kev[KEV_SIZE];
1951 struct timeval timeout;
1961 if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
1963 Punt("kevent: %s", strerror(errno));
1965 JobPassSig(interrupted);
1967 for (i = 0; i < nfds; i++) {
1968 if (kev[i].flags & EV_ERROR) {
1969 warnc(kev[i].data, "kevent");
1972 switch (kev[i].filter) {
1974 JobDoOutput(kev[i].udata, FALSE);
1978 * Just wake up and let
1979 * Job_CatchChildren() collect the
1988 timeout.tv_sec = SEL_SEC;
1989 timeout.tv_usec = SEL_USEC;
1990 if (flag && jobFull && fifoFd >= 0)
1991 FD_SET(fifoFd, &readfds);
1993 nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
1994 (fd_set *)NULL, &timeout);
1997 JobPassSig(interrupted);
2000 if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2004 for (ln = Lst_First(&jobs); nfds != 0 && ln != NULL;
2006 job = Lst_Datum(ln);
2007 if (FD_ISSET(job->inPipe, &readfds)) {
2008 JobDoOutput(job, FALSE);
2012 #endif /* !USE_KQUEUE */
2018 * Start the creation of a target. Basically a front-end for
2019 * JobStart used by the Make module.
2022 * Another job is started.
2028 JobStart(gn, 0, NULL);
2033 * Make a new copy of the shell structure including a copy of the strings
2034 * in it. This also defaults some fields in case they are NULL.
2037 * The function returns a pointer to the new shell structure.
2040 JobCopyShell(const Shell *osh)
2044 nsh = emalloc(sizeof(*nsh));
2045 nsh->name = estrdup(osh->name);
2047 if (osh->echoOff != NULL)
2048 nsh->echoOff = estrdup(osh->echoOff);
2050 nsh->echoOff = NULL;
2051 if (osh->echoOn != NULL)
2052 nsh->echoOn = estrdup(osh->echoOn);
2055 nsh->hasEchoCtl = osh->hasEchoCtl;
2057 if (osh->noPrint != NULL)
2058 nsh->noPrint = estrdup(osh->noPrint);
2060 nsh->noPrint = NULL;
2061 nsh->noPLen = osh->noPLen;
2063 nsh->hasErrCtl = osh->hasErrCtl;
2064 if (osh->errCheck == NULL)
2065 nsh->errCheck = estrdup("");
2067 nsh->errCheck = estrdup(osh->errCheck);
2068 if (osh->ignErr == NULL)
2069 nsh->ignErr = estrdup("%s");
2071 nsh->ignErr = estrdup(osh->ignErr);
2073 if (osh->echo == NULL)
2074 nsh->echo = estrdup("");
2076 nsh->echo = estrdup(osh->echo);
2078 if (osh->exit == NULL)
2079 nsh->exit = estrdup("");
2081 nsh->exit = estrdup(osh->exit);
2088 * Free a shell structure and all associated strings.
2091 JobFreeShell(Shell *sh)
2111 if (commandShell == NULL)
2112 commandShell = JobMatchShell(shells[DEFSHELL].name);
2114 if (shellPath == NULL) {
2116 * The user didn't specify a shell to use, so we are using the
2117 * default one... Both the absolute path and the last component
2118 * must be set. The last component is taken from the 'name'
2119 * field of the default shell description pointed-to by
2120 * commandShell. All default shells are located in
2123 shellName = commandShell->name;
2124 shellPath = str_concat(PATH_DEFSHELLDIR, shellName,
2131 * Initialize the process module, given a maximum number of jobs.
2134 * lists and counters are initialized
2137 Job_Init(int maxproc)
2139 GNode *begin; /* node for commands to do at the very start */
2141 struct sigaction sa;
2144 env = getenv("MAKE_JOBS_FIFO");
2146 if (env == NULL && maxproc > 1) {
2148 * We did not find the environment variable so we are the
2149 * leader. Create the fifo, open it, write one char per
2150 * allowed job into the pipe.
2153 if (!mkfifo(fifoName, 0600)) {
2154 fifoFd = open(fifoName, O_RDWR | O_NONBLOCK, 0);
2157 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2159 setenv("MAKE_JOBS_FIFO", env, 1);
2160 while (maxproc-- > 0) {
2161 write(fifoFd, "+", 1);
2163 /* The master make does not get a magic token */
2172 } else if (env != NULL) {
2174 * We had the environment variable so we are a slave.
2175 * Open fifo and give ourselves a magic token which represents
2176 * the token our parent make has grabbed to start his make
2177 * process. Otherwise the sub-makes would gobble up tokens and
2178 * the proper number of tokens to specify to -j would depend
2179 * on the depth of the tree and the order of execution.
2181 fifoFd = open(env, O_RDWR, 0);
2183 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2200 if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2202 * If only one job can run at a time, there's no need for a
2203 * banner, no is there?
2213 * Catch the four signals that POSIX specifies if they aren't ignored.
2214 * JobCatchSignal will just set global variables and hope someone
2215 * else is going to handle the interrupt.
2217 sa.sa_handler = JobCatchSig;
2218 sigemptyset(&sa.sa_mask);
2221 if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2222 sigaction(SIGINT, &sa, NULL);
2224 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2225 sigaction(SIGHUP, &sa, NULL);
2227 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2228 sigaction(SIGQUIT, &sa, NULL);
2230 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2231 sigaction(SIGTERM, &sa, NULL);
2234 * There are additional signals that need to be caught and passed if
2235 * either the export system wants to be told directly of signals or if
2236 * we're giving each job its own process group (since then it won't get
2237 * signals from the terminal driver as we own the terminal)
2239 #if defined(USE_PGRP)
2240 if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2241 sigaction(SIGTSTP, &sa, NULL);
2243 if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2244 sigaction(SIGTTOU, &sa, NULL);
2246 if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2247 sigaction(SIGTTIN, &sa, NULL);
2249 if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2250 sigaction(SIGWINCH, &sa, NULL);
2255 if ((kqfd = kqueue()) == -1) {
2256 Punt("kqueue: %s", strerror(errno));
2260 begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2262 if (begin != NULL) {
2263 JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2266 Job_CatchChildren(!usePipes);
2269 postCommands = Targ_FindNode(".END", TARG_CREATE);
2274 * See if the job table is full. It is considered full if it is OR
2275 * if we are in the process of aborting OR if we have
2276 * reached/exceeded our local quota. This prevents any more jobs
2280 * TRUE if the job table is full, FALSE otherwise
2290 if (fifoFd >= 0 && jobFull) {
2291 i = read(fifoFd, &c, 1);
2302 * See if the job table is empty. Because the local concurrency may
2303 * be set to 0, it is possible for the job table to become empty,
2304 * while the list of stoppedJobs remains non-empty. In such a case,
2305 * we want to restart as many jobs as we can.
2308 * TRUE if it is. FALSE if it ain't.
2314 if (!Lst_IsEmpty(&stoppedJobs) && !aborting) {
2316 * The job table is obviously not full if it has no
2317 * jobs in it...Try and restart the stopped jobs.
2332 * Find a matching shell in 'shells' given its final component.
2335 * A pointer to a freshly allocated Shell structure with a copy
2336 * of the static structure or NULL if no shell with the given name
2340 JobMatchShell(const char *name)
2342 const struct CShell *sh; /* Pointer into shells table */
2345 for (sh = shells; sh < shells + __arysize(shells); sh++)
2346 if (strcmp(sh->name, name) == 0)
2349 if (sh == shells + __arysize(shells))
2353 nsh = emalloc(sizeof(*nsh));
2355 nsh->name = estrdup(sh->name);
2356 nsh->echoOff = estrdup(sh->echoOff);
2357 nsh->echoOn = estrdup(sh->echoOn);
2358 nsh->hasEchoCtl = sh->hasEchoCtl;
2359 nsh->noPrint = estrdup(sh->noPrint);
2360 nsh->noPLen = sh->noPLen;
2361 nsh->hasErrCtl = sh->hasErrCtl;
2362 nsh->errCheck = estrdup(sh->errCheck);
2363 nsh->ignErr = estrdup(sh->ignErr);
2364 nsh->echo = estrdup(sh->echo);
2365 nsh->exit = estrdup(sh->exit);
2372 * Parse a shell specification and set up commandShell, shellPath
2373 * and shellName appropriately.
2376 * FAILURE if the specification was incorrect.
2379 * commandShell points to a Shell structure (either predefined or
2380 * created from the shell spec), shellPath is the full path of the
2381 * shell described by commandShell, while shellName is just the
2382 * final component of shellPath.
2385 * A shell specification consists of a .SHELL target, with dependency
2386 * operator, followed by a series of blank-separated words. Double
2387 * quotes can be used to use blanks in words. A backslash escapes
2388 * anything (most notably a double-quote and a space) and
2389 * provides the functionality it does in C. Each word consists of
2390 * keyword and value separated by an equal sign. There should be no
2391 * unnecessary spaces in the word. The keywords are as follows:
2392 * name Name of shell.
2393 * path Location of shell. Overrides "name" if given
2394 * quiet Command to turn off echoing.
2395 * echo Command to turn echoing on
2396 * filter Result of turning off echoing that shouldn't be
2398 * echoFlag Flag to turn echoing on at the start
2399 * errFlag Flag to turn error checking on at the start
2400 * hasErrCtl True if shell has error checking control
2401 * check Command to turn on error checking if hasErrCtl
2402 * is TRUE or template of command to echo a command
2403 * for which error checking is off if hasErrCtl is
2405 * ignore Command to turn off error checking if hasErrCtl
2406 * is TRUE or template of command to execute a
2407 * command so as to ignore any errors it returns if
2408 * hasErrCtl is FALSE.
2411 Job_ParseShell(char *line)
2420 Boolean fullSpec = FALSE;
2422 while (isspace((unsigned char)*line)) {
2425 words = brk_string(line, &wordCount, TRUE);
2427 memset(&newShell, 0, sizeof(newShell));
2430 * Parse the specification by keyword
2432 for (path = NULL, argc = wordCount - 1, argv = words + 1; argc != 0;
2434 if (strncmp(*argv, "path=", 5) == 0) {
2436 } else if (strncmp(*argv, "name=", 5) == 0) {
2437 newShell.name = &argv[0][5];
2439 if (strncmp(*argv, "quiet=", 6) == 0) {
2440 newShell.echoOff = &argv[0][6];
2441 } else if (strncmp(*argv, "echo=", 5) == 0) {
2442 newShell.echoOn = &argv[0][5];
2443 } else if (strncmp(*argv, "filter=", 7) == 0) {
2444 newShell.noPrint = &argv[0][7];
2445 newShell.noPLen = strlen(newShell.noPrint);
2446 } else if (strncmp(*argv, "echoFlag=", 9) == 0) {
2447 newShell.echo = &argv[0][9];
2448 } else if (strncmp(*argv, "errFlag=", 8) == 0) {
2449 newShell.exit = &argv[0][8];
2450 } else if (strncmp(*argv, "hasErrCtl=", 10) == 0) {
2451 char c = argv[0][10];
2452 newShell.hasErrCtl = !((c != 'Y') &&
2453 (c != 'y') && (c != 'T') && (c != 't'));
2454 } else if (strncmp(*argv, "check=", 6) == 0) {
2455 newShell.errCheck = &argv[0][6];
2456 } else if (strncmp(*argv, "ignore=", 7) == 0) {
2457 newShell.ignErr = &argv[0][7];
2459 Parse_Error(PARSE_FATAL,
2460 "Unknown keyword \"%s\"", *argv);
2468 * Some checks (could be more)
2471 if ((newShell.echoOn != NULL) ^ (newShell.echoOff != NULL))
2472 Parse_Error(PARSE_FATAL, "Shell must have either both "
2473 "echoOff and echoOn or none of them");
2475 if (newShell.echoOn != NULL && newShell.echoOff)
2476 newShell.hasEchoCtl = TRUE;
2481 * If no path was given, the user wants one of the pre-defined
2482 * shells, yes? So we find the one s/he wants with the help of
2483 * JobMatchShell and set things up the right way. shellPath
2484 * will be set up by Job_Init.
2486 if (newShell.name == NULL) {
2487 Parse_Error(PARSE_FATAL,
2488 "Neither path nor name specified");
2491 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2492 Parse_Error(PARSE_FATAL, "%s: no matching shell",
2499 * The user provided a path. If s/he gave nothing else
2500 * (fullSpec is FALSE), try and find a matching shell in the
2501 * ones we know of. Else we just take the specification at its
2502 * word and copy it to a new location. In either case, we need
2503 * to record the path the user gave for the shell.
2506 shellPath = estrdup(path);
2507 if (newShell.name == NULL) {
2508 /* get the base name as the name */
2509 path = strrchr(path, '/');
2515 newShell.name = path;
2519 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2520 Parse_Error(PARSE_FATAL,
2521 "%s: no matching shell", newShell.name);
2525 sh = JobCopyShell(&newShell);
2529 /* set the new shell */
2530 JobFreeShell(commandShell);
2533 shellName = commandShell->name;
2540 * Handle the receipt of an interrupt.
2543 * All children are killed. Another job will be started if the
2544 * .INTERRUPT target was given.
2547 JobInterrupt(int runINTERRUPT, int signo)
2549 LstNode *ln; /* element in job table */
2550 Job *job; /* job descriptor in that element */
2551 GNode *interrupt; /* the node describing the .INTERRUPT target */
2553 aborting = ABORT_INTERRUPT;
2555 for (ln = Lst_First(&jobs); ln != NULL; ln = Lst_Succ(ln)) {
2556 job = Lst_Datum(ln);
2558 if (!Targ_Precious(job->node)) {
2559 char *file = (job->node->path == NULL ?
2560 job->node->name : job->node->path);
2562 if (!noExecute && eunlink(file) != -1) {
2563 Error("*** %s removed", file);
2567 DEBUGF(JOB, ("JobInterrupt passing signal to child "
2568 "%d.\n", job->pid));
2569 KILL(job->pid, signo);
2573 if (runINTERRUPT && !touchFlag) {
2575 * clear the interrupted flag because we would get an
2576 * infinite loop otherwise.
2580 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2581 if (interrupt != NULL) {
2582 ignoreErrors = FALSE;
2584 JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
2587 Job_CatchChildren(!usePipes);
2595 * Do final processing such as the running of the commands
2596 * attached to the .END target.
2599 * Number of errors reported.
2605 if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
2607 Error("Errors reported so .END ignored");
2609 JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
2613 Job_CatchChildren(!usePipes);
2628 * Waits for all running jobs to finish and returns. Sets 'aborting'
2629 * to ABORT_WAIT to prevent other jobs from starting.
2632 * Currently running jobs finish.
2638 aborting = ABORT_WAIT;
2639 while (nJobs != 0) {
2641 Job_CatchChildren(!usePipes);
2648 * Abort all currently running jobs without handling output or anything.
2649 * This function is to be called only in the event of a major
2650 * error. Most definitely NOT to be called from JobInterrupt.
2653 * All children are killed, not just the firstborn
2658 LstNode *ln; /* element in job table */
2659 Job *job; /* the job descriptor in that element */
2662 aborting = ABORT_ERROR;
2665 for (ln = Lst_First(&jobs); ln != NULL; ln = Lst_Succ(ln)) {
2666 job = Lst_Datum(ln);
2669 * kill the child process with increasingly drastic
2670 * signals to make darn sure it's dead.
2672 KILL(job->pid, SIGINT);
2673 KILL(job->pid, SIGKILL);
2678 * Catch as many children as want to report in at first, then give up
2680 while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2686 * Tries to restart stopped jobs if there are slots available.
2687 * Note that this tries to restart them regardless of pending errors.
2688 * It's not good to leave stopped jobs lying around!
2691 * Resumes(and possibly migrates) jobs.
2694 JobRestartJobs(void)
2696 while (!jobFull && !Lst_IsEmpty(&stoppedJobs)) {
2697 DEBUGF(JOB, ("Job queue is not full. "
2698 "Restarting a stopped job.\n"));
2699 JobRestart(Lst_DeQueue(&stoppedJobs));