Merge illumos-gate
[unleashed.git] / bin / make / job.c
blobb3563022ae605d160239bbb73680c537113fa695
1 /* $NetBSD: job.c,v 1.190 2017/04/16 21:23:43 riastradh Exp $ */
3 /*
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5 * All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
36 * Copyright (c) 1988, 1989 by Adam de Boor
37 * Copyright (c) 1989 by Berkeley Softworks
38 * All rights reserved.
40 * This code is derived from software contributed to Berkeley by
41 * Adam de Boor.
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. All advertising materials mentioning features or use of this software
52 * must display the following acknowledgement:
53 * This product includes software developed by the University of
54 * California, Berkeley and its contributors.
55 * 4. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
72 #ifndef MAKE_NATIVE
73 static char rcsid[] = "$NetBSD: job.c,v 1.190 2017/04/16 21:23:43 riastradh Exp $";
74 #else
75 #include <sys/cdefs.h>
76 #ifndef lint
77 #if 0
78 static char sccsid[] = "@(#)job.c 8.2 (Berkeley) 3/19/94";
79 #else
80 __RCSID("$NetBSD: job.c,v 1.190 2017/04/16 21:23:43 riastradh Exp $");
81 #endif
82 #endif /* not lint */
83 #endif
85 /*-
86 * job.c --
87 * handle the creation etc. of our child processes.
89 * Interface:
90 * Job_Make Start the creation of the given target.
92 * Job_CatchChildren Check for and handle the termination of any
93 * children. This must be called reasonably
94 * frequently to keep the whole make going at
95 * a decent clip, since job table entries aren't
96 * removed until their process is caught this way.
98 * Job_CatchOutput Print any output our children have produced.
99 * Should also be called fairly frequently to
100 * keep the user informed of what's going on.
101 * If no output is waiting, it will block for
102 * a time given by the SEL_* constants, below,
103 * or until output is ready.
105 * Job_Init Called to intialize this module. in addition,
106 * any commands attached to the .BEGIN target
107 * are executed before this function returns.
108 * Hence, the makefile must have been parsed
109 * before this function is called.
111 * Job_End Cleanup any memory used.
113 * Job_ParseShell Given the line following a .SHELL target, parse
114 * the line as a shell specification. Returns
115 * FAILURE if the spec was incorrect.
117 * Job_Finish Perform any final processing which needs doing.
118 * This includes the execution of any commands
119 * which have been/were attached to the .END
120 * target. It should only be called when the
121 * job table is empty.
123 * Job_AbortAll Abort all currently running jobs. It doesn't
124 * handle output or do anything for the jobs,
125 * just kills them. It should only be called in
126 * an emergency, as it were.
128 * Job_CheckCommands Verify that the commands for a target are
129 * ok. Provide them if necessary and possible.
131 * Job_Touch Update a target without really updating it.
133 * Job_Wait Wait for all currently-running jobs to finish.
136 #ifdef HAVE_CONFIG_H
137 # include "config.h"
138 #endif
139 #include <sys/types.h>
140 #include <sys/stat.h>
141 #include <sys/file.h>
142 #include <sys/time.h>
143 #include "wait.h"
145 #include <assert.h>
146 #include <errno.h>
147 #if !defined(USE_SELECT) && defined(HAVE_POLL_H)
148 #include <poll.h>
149 #else
150 #ifndef USE_SELECT /* no poll.h */
151 # define USE_SELECT
152 #endif
153 #if defined(HAVE_SYS_SELECT_H)
154 # include <sys/select.h>
155 #endif
156 #endif
157 #include <signal.h>
158 #include <stdio.h>
159 #include <string.h>
160 #include <utime.h>
161 #if defined(HAVE_SYS_SOCKET_H)
162 # include <sys/socket.h>
163 #endif
165 #include "make.h"
166 #include "hash.h"
167 #include "dir.h"
168 #include "job.h"
169 #include "pathnames.h"
170 #include "trace.h"
171 # define STATIC static
174 * error handling variables
176 static int errors = 0; /* number of errors reported */
177 static int aborting = 0; /* why is the make aborting? */
178 #define ABORT_ERROR 1 /* Because of an error */
179 #define ABORT_INTERRUPT 2 /* Because it was interrupted */
180 #define ABORT_WAIT 3 /* Waiting for jobs to finish */
181 #define JOB_TOKENS "+EI+" /* Token to requeue for each abort state */
184 * this tracks the number of tokens currently "out" to build jobs.
186 int jobTokensRunning = 0;
187 int not_parallel = 0; /* set if .NOT_PARALLEL */
190 * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
191 * is a char! So when we go above 127 we turn negative!
193 #define FILENO(a) ((unsigned) fileno(a))
196 * post-make command processing. The node postCommands is really just the
197 * .END target but we keep it around to avoid having to search for it
198 * all the time.
200 static GNode *postCommands = NULL;
201 /* node containing commands to execute when
202 * everything else is done */
203 static int numCommands; /* The number of commands actually printed
204 * for a target. Should this number be
205 * 0, no shell will be executed. */
208 * Return values from JobStart.
210 #define JOB_RUNNING 0 /* Job is running */
211 #define JOB_ERROR 1 /* Error in starting the job */
212 #define JOB_FINISHED 2 /* The job is already finished */
215 * Descriptions for various shells.
217 * The build environment may set DEFSHELL_INDEX to one of
218 * DEFSHELL_INDEX_SH, DEFSHELL_INDEX_KSH, or DEFSHELL_INDEX_CSH, to
219 * select one of the prefedined shells as the default shell.
221 * Alternatively, the build environment may set DEFSHELL_CUSTOM to the
222 * name or the full path of a sh-compatible shell, which will be used as
223 * the default shell.
225 * ".SHELL" lines in Makefiles can choose the default shell from the
226 # set defined here, or add additional shells.
229 #ifdef DEFSHELL_CUSTOM
230 #define DEFSHELL_INDEX_CUSTOM 0
231 #define DEFSHELL_INDEX_SH 1
232 #define DEFSHELL_INDEX_KSH 2
233 #define DEFSHELL_INDEX_CSH 3
234 #else /* !DEFSHELL_CUSTOM */
235 #define DEFSHELL_INDEX_SH 0
236 #define DEFSHELL_INDEX_KSH 1
237 #define DEFSHELL_INDEX_CSH 2
238 #endif /* !DEFSHELL_CUSTOM */
240 #ifndef DEFSHELL_INDEX
241 #define DEFSHELL_INDEX 0 /* DEFSHELL_INDEX_CUSTOM or DEFSHELL_INDEX_SH */
242 #endif /* !DEFSHELL_INDEX */
244 static Shell shells[] = {
245 #ifdef DEFSHELL_CUSTOM
247 * An sh-compatible shell with a non-standard name.
249 * Keep this in sync with the "sh" description below, but avoid
250 * non-portable features that might not be supplied by all
251 * sh-compatible shells.
254 DEFSHELL_CUSTOM,
255 FALSE, "", "", "", 0,
256 FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
260 #endif /* DEFSHELL_CUSTOM */
262 * SH description. Echo control is also possible and, under
263 * sun UNIX anyway, one can even control error checking.
266 "sh",
267 FALSE, "", "", "", 0,
268 FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
269 #if defined(MAKE_NATIVE) && defined(__NetBSD__)
270 "q",
271 #else
273 #endif
277 * KSH description.
280 "ksh",
281 TRUE, "set +v", "set -v", "set +v", 6,
282 FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
283 "v",
287 * CSH description. The csh can do echo control by playing
288 * with the setting of the 'echo' shell variable. Sadly,
289 * however, it is unable to do error control nicely.
292 "csh",
293 TRUE, "unset verbose", "set verbose", "unset verbose", 10,
294 FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"\n", "", "'\\\n'", '#',
295 "v", "e",
298 * UNKNOWN.
301 NULL,
302 FALSE, NULL, NULL, NULL, 0,
303 FALSE, NULL, NULL, NULL, NULL, 0,
304 NULL, NULL,
307 static Shell *commandShell = &shells[DEFSHELL_INDEX]; /* this is the shell to
308 * which we pass all
309 * commands in the Makefile.
310 * It is set by the
311 * Job_ParseShell function */
312 const char *shellPath = NULL, /* full pathname of
313 * executable image */
314 *shellName = NULL; /* last component of shell */
315 char *shellErrFlag = NULL;
316 static const char *shellArgv = NULL; /* Custom shell args */
319 STATIC Job *job_table; /* The structures that describe them */
320 STATIC Job *job_table_end; /* job_table + maxJobs */
321 static int wantToken; /* we want a token */
322 static int lurking_children = 0;
323 static int make_suspended = 0; /* non-zero if we've seen a SIGTSTP (etc) */
326 * Set of descriptors of pipes connected to
327 * the output channels of children
329 static struct pollfd *fds = NULL;
330 static Job **jobfds = NULL;
331 static int nfds = 0;
332 static void watchfd(Job *);
333 static void clearfd(Job *);
334 static int readyfd(Job *);
336 STATIC GNode *lastNode; /* The node for which output was most recently
337 * produced. */
338 static char *targPrefix = NULL; /* What we print at the start of TARG_FMT */
339 static Job tokenWaitJob; /* token wait pseudo-job */
341 static Job childExitJob; /* child exit pseudo-job */
342 #define CHILD_EXIT "."
343 #define DO_JOB_RESUME "R"
345 #define TARG_FMT "%s %s ---\n" /* Default format */
346 #define MESSAGE(fp, gn) \
347 if (maxJobs != 1 && targPrefix && *targPrefix) \
348 (void)fprintf(fp, TARG_FMT, targPrefix, gn->name)
350 static sigset_t caught_signals; /* Set of signals we handle */
351 #if defined(SYSV)
352 #define KILLPG(pid, sig) kill(-(pid), (sig))
353 #else
354 #define KILLPG(pid, sig) killpg((pid), (sig))
355 #endif
357 static void JobChildSig(int);
358 static void JobContinueSig(int);
359 static Job *JobFindPid(int, int, Boolean);
360 static int JobPrintCommand(void *, void *);
361 static int JobSaveCommand(void *, void *);
362 static void JobClose(Job *);
363 static void JobExec(Job *, char **);
364 static void JobMakeArgv(Job *, char **);
365 static int JobStart(GNode *, int);
366 static char *JobOutput(Job *, char *, char *, int);
367 static void JobDoOutput(Job *, Boolean);
368 static Shell *JobMatchShell(const char *);
369 static void JobInterrupt(int, int) MAKE_ATTR_DEAD;
370 static void JobRestartJobs(void);
371 static void JobTokenAdd(void);
372 static void JobSigLock(sigset_t *);
373 static void JobSigUnlock(sigset_t *);
374 static void JobSigReset(void);
376 #if !defined(MALLOC_OPTIONS)
377 # define MALLOC_OPTIONS "A"
378 #endif
379 const char *malloc_options= MALLOC_OPTIONS;
381 static void
382 job_table_dump(const char *where)
384 Job *job;
386 fprintf(debug_file, "job table @ %s\n", where);
387 for (job = job_table; job < job_table_end; job++) {
388 fprintf(debug_file, "job %d, status %d, flags %d, pid %d\n",
389 (int)(job - job_table), job->job_state, job->flags, job->pid);
394 * Delete the target of a failed, interrupted, or otherwise
395 * unsuccessful job unless inhibited by .PRECIOUS.
397 static void
398 JobDeleteTarget(GNode *gn)
400 if ((gn->type & (OP_JOIN|OP_PHONY)) == 0 && !Targ_Precious(gn)) {
401 char *file = (gn->path == NULL ? gn->name : gn->path);
402 if (!noExecute && eunlink(file) != -1) {
403 Error("*** %s removed", file);
409 * JobSigLock/JobSigUnlock
411 * Signal lock routines to get exclusive access. Currently used to
412 * protect `jobs' and `stoppedJobs' list manipulations.
414 static void JobSigLock(sigset_t *omaskp)
416 if (sigprocmask(SIG_BLOCK, &caught_signals, omaskp) != 0) {
417 Punt("JobSigLock: sigprocmask: %s", strerror(errno));
418 sigemptyset(omaskp);
422 static void JobSigUnlock(sigset_t *omaskp)
424 (void)sigprocmask(SIG_SETMASK, omaskp, NULL);
427 static void
428 JobCreatePipe(Job *job, int minfd)
430 int i, fd, flags;
432 if (pipe(job->jobPipe) == -1)
433 Punt("Cannot create pipe: %s", strerror(errno));
435 for (i = 0; i < 2; i++) {
436 /* Avoid using low numbered fds */
437 fd = fcntl(job->jobPipe[i], F_DUPFD, minfd);
438 if (fd != -1) {
439 close(job->jobPipe[i]);
440 job->jobPipe[i] = fd;
444 /* Set close-on-exec flag for both */
445 if (fcntl(job->jobPipe[0], F_SETFD, FD_CLOEXEC) == -1)
446 Punt("Cannot set close-on-exec: %s", strerror(errno));
447 if (fcntl(job->jobPipe[1], F_SETFD, FD_CLOEXEC) == -1)
448 Punt("Cannot set close-on-exec: %s", strerror(errno));
451 * We mark the input side of the pipe non-blocking; we poll(2) the
452 * pipe when we're waiting for a job token, but we might lose the
453 * race for the token when a new one becomes available, so the read
454 * from the pipe should not block.
456 flags = fcntl(job->jobPipe[0], F_GETFL, 0);
457 if (flags == -1)
458 Punt("Cannot get flags: %s", strerror(errno));
459 flags |= O_NONBLOCK;
460 if (fcntl(job->jobPipe[0], F_SETFL, flags) == -1)
461 Punt("Cannot set flags: %s", strerror(errno));
465 *-----------------------------------------------------------------------
466 * JobCondPassSig --
467 * Pass a signal to a job
469 * Input:
470 * signop Signal to send it
472 * Side Effects:
473 * None, except the job may bite it.
475 *-----------------------------------------------------------------------
477 static void
478 JobCondPassSig(int signo)
480 Job *job;
482 if (DEBUG(JOB)) {
483 (void)fprintf(debug_file, "JobCondPassSig(%d) called.\n", signo);
486 for (job = job_table; job < job_table_end; job++) {
487 if (job->job_state != JOB_ST_RUNNING)
488 continue;
489 if (DEBUG(JOB)) {
490 (void)fprintf(debug_file,
491 "JobCondPassSig passing signal %d to child %d.\n",
492 signo, job->pid);
494 KILLPG(job->pid, signo);
499 *-----------------------------------------------------------------------
500 * JobChldSig --
501 * SIGCHLD handler.
503 * Input:
504 * signo The signal number we've received
506 * Results:
507 * None.
509 * Side Effects:
510 * Sends a token on the child exit pipe to wake us up from
511 * select()/poll().
513 *-----------------------------------------------------------------------
515 static void
516 JobChildSig(int signo MAKE_ATTR_UNUSED)
518 while (write(childExitJob.outPipe, CHILD_EXIT, 1) == -1 && errno == EAGAIN)
519 continue;
524 *-----------------------------------------------------------------------
525 * JobContinueSig --
526 * Resume all stopped jobs.
528 * Input:
529 * signo The signal number we've received
531 * Results:
532 * None.
534 * Side Effects:
535 * Jobs start running again.
537 *-----------------------------------------------------------------------
539 static void
540 JobContinueSig(int signo MAKE_ATTR_UNUSED)
543 * Defer sending to SIGCONT to our stopped children until we return
544 * from the signal handler.
546 while (write(childExitJob.outPipe, DO_JOB_RESUME, 1) == -1 &&
547 errno == EAGAIN)
548 continue;
552 *-----------------------------------------------------------------------
553 * JobPassSig --
554 * Pass a signal on to all jobs, then resend to ourselves.
556 * Input:
557 * signo The signal number we've received
559 * Results:
560 * None.
562 * Side Effects:
563 * We die by the same signal.
565 *-----------------------------------------------------------------------
567 MAKE_ATTR_DEAD static void
568 JobPassSig_int(int signo)
570 /* Run .INTERRUPT target then exit */
571 JobInterrupt(TRUE, signo);
574 MAKE_ATTR_DEAD static void
575 JobPassSig_term(int signo)
577 /* Dont run .INTERRUPT target then exit */
578 JobInterrupt(FALSE, signo);
581 static void
582 JobPassSig_suspend(int signo)
584 sigset_t nmask, omask;
585 struct sigaction act;
587 /* Suppress job started/continued messages */
588 make_suspended = 1;
590 /* Pass the signal onto every job */
591 JobCondPassSig(signo);
594 * Send ourselves the signal now we've given the message to everyone else.
595 * Note we block everything else possible while we're getting the signal.
596 * This ensures that all our jobs get continued when we wake up before
597 * we take any other signal.
599 sigfillset(&nmask);
600 sigdelset(&nmask, signo);
601 (void)sigprocmask(SIG_SETMASK, &nmask, &omask);
603 act.sa_handler = SIG_DFL;
604 sigemptyset(&act.sa_mask);
605 act.sa_flags = 0;
606 (void)sigaction(signo, &act, NULL);
608 if (DEBUG(JOB)) {
609 (void)fprintf(debug_file,
610 "JobPassSig passing signal %d to self.\n", signo);
613 (void)kill(getpid(), signo);
616 * We've been continued.
618 * A whole host of signals continue to happen!
619 * SIGCHLD for any processes that actually suspended themselves.
620 * SIGCHLD for any processes that exited while we were alseep.
621 * The SIGCONT that actually caused us to wakeup.
623 * Since we defer passing the SIGCONT on to our children until
624 * the main processing loop, we can be sure that all the SIGCHLD
625 * events will have happened by then - and that the waitpid() will
626 * collect the child 'suspended' events.
627 * For correct sequencing we just need to ensure we process the
628 * waitpid() before passign on the SIGCONT.
630 * In any case nothing else is needed here.
633 /* Restore handler and signal mask */
634 act.sa_handler = JobPassSig_suspend;
635 (void)sigaction(signo, &act, NULL);
636 (void)sigprocmask(SIG_SETMASK, &omask, NULL);
640 *-----------------------------------------------------------------------
641 * JobFindPid --
642 * Compare the pid of the job with the given pid and return 0 if they
643 * are equal. This function is called from Job_CatchChildren
644 * to find the job descriptor of the finished job.
646 * Input:
647 * job job to examine
648 * pid process id desired
650 * Results:
651 * Job with matching pid
653 * Side Effects:
654 * None
655 *-----------------------------------------------------------------------
657 static Job *
658 JobFindPid(int pid, int status, Boolean isJobs)
660 Job *job;
662 for (job = job_table; job < job_table_end; job++) {
663 if ((job->job_state == status) && job->pid == pid)
664 return job;
666 if (DEBUG(JOB) && isJobs)
667 job_table_dump("no pid");
668 return NULL;
672 *-----------------------------------------------------------------------
673 * JobPrintCommand --
674 * Put out another command for the given job. If the command starts
675 * with an @ or a - we process it specially. In the former case,
676 * so long as the -s and -n flags weren't given to make, we stick
677 * a shell-specific echoOff command in the script. In the latter,
678 * we ignore errors for the entire job, unless the shell has error
679 * control.
680 * If the command is just "..." we take all future commands for this
681 * job to be commands to be executed once the entire graph has been
682 * made and return non-zero to signal that the end of the commands
683 * was reached. These commands are later attached to the postCommands
684 * node and executed by Job_End when all things are done.
685 * This function is called from JobStart via Lst_ForEach.
687 * Input:
688 * cmdp command string to print
689 * jobp job for which to print it
691 * Results:
692 * Always 0, unless the command was "..."
694 * Side Effects:
695 * If the command begins with a '-' and the shell has no error control,
696 * the JOB_IGNERR flag is set in the job descriptor.
697 * If the command is "..." and we're not ignoring such things,
698 * tailCmds is set to the successor node of the cmd.
699 * numCommands is incremented if the command is actually printed.
700 *-----------------------------------------------------------------------
702 static int
703 JobPrintCommand(void *cmdp, void *jobp)
705 Boolean noSpecials; /* true if we shouldn't worry about
706 * inserting special commands into
707 * the input stream. */
708 Boolean shutUp = FALSE; /* true if we put a no echo command
709 * into the command file */
710 Boolean errOff = FALSE; /* true if we turned error checking
711 * off before printing the command
712 * and need to turn it back on */
713 const char *cmdTemplate; /* Template to use when printing the
714 * command */
715 char *cmdStart; /* Start of expanded command */
716 char *escCmd = NULL; /* Command with quotes/backticks escaped */
717 char *cmd = (char *)cmdp;
718 Job *job = (Job *)jobp;
719 int i, j;
721 noSpecials = NoExecute(job->node);
723 if (strcmp(cmd, "...") == 0) {
724 job->node->type |= OP_SAVE_CMDS;
725 if ((job->flags & JOB_IGNDOTS) == 0) {
726 job->tailCmds = Lst_Succ(Lst_Member(job->node->commands,
727 cmd));
728 return 1;
730 return 0;
733 #define DBPRINTF(fmt, arg) if (DEBUG(JOB)) { \
734 (void)fprintf(debug_file, fmt, arg); \
736 (void)fprintf(job->cmdFILE, fmt, arg); \
737 (void)fflush(job->cmdFILE);
739 numCommands += 1;
741 cmdStart = cmd = Var_Subst(NULL, cmd, job->node, VARF_WANTRES);
743 cmdTemplate = "%s\n";
746 * Check for leading @' and -'s to control echoing and error checking.
748 while (*cmd == '@' || *cmd == '-' || (*cmd == '+')) {
749 switch (*cmd) {
750 case '@':
751 shutUp = DEBUG(LOUD) ? FALSE : TRUE;
752 break;
753 case '-':
754 errOff = TRUE;
755 break;
756 case '+':
757 if (noSpecials) {
759 * We're not actually executing anything...
760 * but this one needs to be - use compat mode just for it.
762 CompatRunCommand(cmdp, job->node);
763 free(cmdStart);
764 return 0;
766 break;
768 cmd++;
771 while (isspace((unsigned char) *cmd))
772 cmd++;
775 * If the shell doesn't have error control the alternate echo'ing will
776 * be done (to avoid showing additional error checking code)
777 * and this will need the characters '$ ` \ "' escaped
780 if (!commandShell->hasErrCtl) {
781 /* Worst that could happen is every char needs escaping. */
782 escCmd = bmake_malloc((strlen(cmd) * 2) + 1);
783 for (i = 0, j= 0; cmd[i] != '\0'; i++, j++) {
784 if (cmd[i] == '$' || cmd[i] == '`' || cmd[i] == '\\' ||
785 cmd[i] == '"')
786 escCmd[j++] = '\\';
787 escCmd[j] = cmd[i];
789 escCmd[j] = 0;
792 if (shutUp) {
793 if (!(job->flags & JOB_SILENT) && !noSpecials &&
794 commandShell->hasEchoCtl) {
795 DBPRINTF("%s\n", commandShell->echoOff);
796 } else {
797 if (commandShell->hasErrCtl)
798 shutUp = FALSE;
802 if (errOff) {
803 if (!noSpecials) {
804 if (commandShell->hasErrCtl) {
806 * we don't want the error-control commands showing
807 * up either, so we turn off echoing while executing
808 * them. We could put another field in the shell
809 * structure to tell JobDoOutput to look for this
810 * string too, but why make it any more complex than
811 * it already is?
813 if (!(job->flags & JOB_SILENT) && !shutUp &&
814 commandShell->hasEchoCtl) {
815 DBPRINTF("%s\n", commandShell->echoOff);
816 DBPRINTF("%s\n", commandShell->ignErr);
817 DBPRINTF("%s\n", commandShell->echoOn);
818 } else {
819 DBPRINTF("%s\n", commandShell->ignErr);
821 } else if (commandShell->ignErr &&
822 (*commandShell->ignErr != '\0'))
825 * The shell has no error control, so we need to be
826 * weird to get it to ignore any errors from the command.
827 * If echoing is turned on, we turn it off and use the
828 * errCheck template to echo the command. Leave echoing
829 * off so the user doesn't see the weirdness we go through
830 * to ignore errors. Set cmdTemplate to use the weirdness
831 * instead of the simple "%s\n" template.
833 job->flags |= JOB_IGNERR;
834 if (!(job->flags & JOB_SILENT) && !shutUp) {
835 if (commandShell->hasEchoCtl) {
836 DBPRINTF("%s\n", commandShell->echoOff);
838 DBPRINTF(commandShell->errCheck, escCmd);
839 shutUp = TRUE;
840 } else {
841 if (!shutUp) {
842 DBPRINTF(commandShell->errCheck, escCmd);
845 cmdTemplate = commandShell->ignErr;
847 * The error ignoration (hee hee) is already taken care
848 * of by the ignErr template, so pretend error checking
849 * is still on.
851 errOff = FALSE;
852 } else {
853 errOff = FALSE;
855 } else {
856 errOff = FALSE;
858 } else {
861 * If errors are being checked and the shell doesn't have error control
862 * but does supply an errOut template, then setup commands to run
863 * through it.
866 if (!commandShell->hasErrCtl && commandShell->errOut &&
867 (*commandShell->errOut != '\0')) {
868 if (!(job->flags & JOB_SILENT) && !shutUp) {
869 if (commandShell->hasEchoCtl) {
870 DBPRINTF("%s\n", commandShell->echoOff);
872 DBPRINTF(commandShell->errCheck, escCmd);
873 shutUp = TRUE;
875 /* If it's a comment line or blank, treat as an ignored error */
876 if ((escCmd[0] == commandShell->commentChar) ||
877 (escCmd[0] == 0))
878 cmdTemplate = commandShell->ignErr;
879 else
880 cmdTemplate = commandShell->errOut;
881 errOff = FALSE;
885 if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0 &&
886 (job->flags & JOB_TRACED) == 0) {
887 DBPRINTF("set -%s\n", "x");
888 job->flags |= JOB_TRACED;
891 DBPRINTF(cmdTemplate, cmd);
892 free(cmdStart);
893 free(escCmd);
894 if (errOff) {
896 * If echoing is already off, there's no point in issuing the
897 * echoOff command. Otherwise we issue it and pretend it was on
898 * for the whole command...
900 if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl){
901 DBPRINTF("%s\n", commandShell->echoOff);
902 shutUp = TRUE;
904 DBPRINTF("%s\n", commandShell->errCheck);
906 if (shutUp && commandShell->hasEchoCtl) {
907 DBPRINTF("%s\n", commandShell->echoOn);
909 return 0;
913 *-----------------------------------------------------------------------
914 * JobSaveCommand --
915 * Save a command to be executed when everything else is done.
916 * Callback function for JobFinish...
918 * Results:
919 * Always returns 0
921 * Side Effects:
922 * The command is tacked onto the end of postCommands's commands list.
924 *-----------------------------------------------------------------------
926 static int
927 JobSaveCommand(void *cmd, void *gn)
929 cmd = Var_Subst(NULL, (char *)cmd, (GNode *)gn, VARF_WANTRES);
930 (void)Lst_AtEnd(postCommands->commands, cmd);
931 return(0);
936 *-----------------------------------------------------------------------
937 * JobClose --
938 * Called to close both input and output pipes when a job is finished.
940 * Results:
941 * Nada
943 * Side Effects:
944 * The file descriptors associated with the job are closed.
946 *-----------------------------------------------------------------------
948 static void
949 JobClose(Job *job)
951 clearfd(job);
952 (void)close(job->outPipe);
953 job->outPipe = -1;
955 JobDoOutput(job, TRUE);
956 (void)close(job->inPipe);
957 job->inPipe = -1;
961 *-----------------------------------------------------------------------
962 * JobFinish --
963 * Do final processing for the given job including updating
964 * parents and starting new jobs as available/necessary. Note
965 * that we pay no attention to the JOB_IGNERR flag here.
966 * This is because when we're called because of a noexecute flag
967 * or something, jstat.w_status is 0 and when called from
968 * Job_CatchChildren, the status is zeroed if it s/b ignored.
970 * Input:
971 * job job to finish
972 * status sub-why job went away
974 * Results:
975 * None
977 * Side Effects:
978 * Final commands for the job are placed on postCommands.
980 * If we got an error and are aborting (aborting == ABORT_ERROR) and
981 * the job list is now empty, we are done for the day.
982 * If we recognized an error (errors !=0), we set the aborting flag
983 * to ABORT_ERROR so no more jobs will be started.
984 *-----------------------------------------------------------------------
986 /*ARGSUSED*/
987 static void
988 JobFinish (Job *job, WAIT_T status)
990 Boolean done, return_job_token;
992 if (DEBUG(JOB)) {
993 fprintf(debug_file, "Jobfinish: %d [%s], status %d\n",
994 job->pid, job->node->name, status);
997 if ((WIFEXITED(status) &&
998 (((WEXITSTATUS(status) != 0) && !(job->flags & JOB_IGNERR)))) ||
999 WIFSIGNALED(status))
1002 * If it exited non-zero and either we're doing things our
1003 * way or we're not ignoring errors, the job is finished.
1004 * Similarly, if the shell died because of a signal
1005 * the job is also finished. In these
1006 * cases, finish out the job's output before printing the exit
1007 * status...
1009 JobClose(job);
1010 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1011 (void)fclose(job->cmdFILE);
1012 job->cmdFILE = NULL;
1014 done = TRUE;
1015 } else if (WIFEXITED(status)) {
1017 * Deal with ignored errors in -B mode. We need to print a message
1018 * telling of the ignored error as well as setting status.w_status
1019 * to 0 so the next command gets run. To do this, we set done to be
1020 * TRUE if in -B mode and the job exited non-zero.
1022 done = WEXITSTATUS(status) != 0;
1024 * Old comment said: "Note we don't
1025 * want to close down any of the streams until we know we're at the
1026 * end."
1027 * But we do. Otherwise when are we going to print the rest of the
1028 * stuff?
1030 JobClose(job);
1031 } else {
1033 * No need to close things down or anything.
1035 done = FALSE;
1038 if (done) {
1039 if (WIFEXITED(status)) {
1040 if (DEBUG(JOB)) {
1041 (void)fprintf(debug_file, "Process %d [%s] exited.\n",
1042 job->pid, job->node->name);
1044 if (WEXITSTATUS(status) != 0) {
1045 if (job->node != lastNode) {
1046 MESSAGE(stdout, job->node);
1047 lastNode = job->node;
1049 #ifdef USE_META
1050 if (useMeta) {
1051 meta_job_error(job, job->node, job->flags, WEXITSTATUS(status));
1053 #endif
1054 (void)fprintf(stderr, "*** [%s] Error code %d%s\n",
1055 job->node->name,
1056 WEXITSTATUS(status),
1057 (job->flags & JOB_IGNERR) ? " (ignored)" : "");
1058 if (job->flags & JOB_IGNERR) {
1059 WAIT_STATUS(status) = 0;
1060 } else {
1061 if (deleteOnError) {
1062 JobDeleteTarget(job->node);
1064 PrintOnError(job->node, NULL);
1066 } else if (DEBUG(JOB)) {
1067 if (job->node != lastNode) {
1068 MESSAGE(stdout, job->node);
1069 lastNode = job->node;
1071 (void)fprintf(stderr, "*** [%s] Completed successfully\n",
1072 job->node->name);
1074 } else {
1075 if (job->node != lastNode) {
1076 MESSAGE(stdout, job->node);
1077 lastNode = job->node;
1079 (void)fprintf(stderr, "*** [%s] Signal %d\n",
1080 job->node->name, WTERMSIG(status));
1081 if (deleteOnError) {
1082 JobDeleteTarget(job->node);
1085 (void)fflush(stdout);
1088 #ifdef USE_META
1089 if (useMeta) {
1090 int x;
1092 if ((x = meta_job_finish(job)) != 0 && status == 0) {
1093 status = x;
1096 #endif
1098 return_job_token = FALSE;
1100 Trace_Log(JOBEND, job);
1101 if (!(job->flags & JOB_SPECIAL)) {
1102 if ((WAIT_STATUS(status) != 0) ||
1103 (aborting == ABORT_ERROR) ||
1104 (aborting == ABORT_INTERRUPT))
1105 return_job_token = TRUE;
1108 if ((aborting != ABORT_ERROR) && (aborting != ABORT_INTERRUPT) &&
1109 (WAIT_STATUS(status) == 0)) {
1111 * As long as we aren't aborting and the job didn't return a non-zero
1112 * status that we shouldn't ignore, we call Make_Update to update
1113 * the parents. In addition, any saved commands for the node are placed
1114 * on the .END target.
1116 if (job->tailCmds != NULL) {
1117 Lst_ForEachFrom(job->node->commands, job->tailCmds,
1118 JobSaveCommand,
1119 job->node);
1121 job->node->made = MADE;
1122 if (!(job->flags & JOB_SPECIAL))
1123 return_job_token = TRUE;
1124 Make_Update(job->node);
1125 job->job_state = JOB_ST_FREE;
1126 } else if (WAIT_STATUS(status)) {
1127 errors += 1;
1128 job->job_state = JOB_ST_FREE;
1132 * Set aborting if any error.
1134 if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
1136 * If we found any errors in this batch of children and the -k flag
1137 * wasn't given, we set the aborting flag so no more jobs get
1138 * started.
1140 aborting = ABORT_ERROR;
1143 if (return_job_token)
1144 Job_TokenReturn();
1146 if (aborting == ABORT_ERROR && jobTokensRunning == 0) {
1148 * If we are aborting and the job table is now empty, we finish.
1150 Finish(errors);
1155 *-----------------------------------------------------------------------
1156 * Job_Touch --
1157 * Touch the given target. Called by JobStart when the -t flag was
1158 * given
1160 * Input:
1161 * gn the node of the file to touch
1162 * silent TRUE if should not print message
1164 * Results:
1165 * None
1167 * Side Effects:
1168 * The data modification of the file is changed. In addition, if the
1169 * file did not exist, it is created.
1170 *-----------------------------------------------------------------------
1172 void
1173 Job_Touch(GNode *gn, Boolean silent)
1175 int streamID; /* ID of stream opened to do the touch */
1176 struct utimbuf times; /* Times for utime() call */
1178 if (gn->type & (OP_JOIN|OP_USE|OP_USEBEFORE|OP_EXEC|OP_OPTIONAL|
1179 OP_SPECIAL|OP_PHONY)) {
1181 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets
1182 * and, as such, shouldn't really be created.
1184 return;
1187 if (!silent || NoExecute(gn)) {
1188 (void)fprintf(stdout, "touch %s\n", gn->name);
1189 (void)fflush(stdout);
1192 if (NoExecute(gn)) {
1193 return;
1196 if (gn->type & OP_ARCHV) {
1197 Arch_Touch(gn);
1198 } else if (gn->type & OP_LIB) {
1199 Arch_TouchLib(gn);
1200 } else {
1201 char *file = gn->path ? gn->path : gn->name;
1203 times.actime = times.modtime = now;
1204 if (utime(file, &times) < 0){
1205 streamID = open(file, O_RDWR | O_CREAT, 0666);
1207 if (streamID >= 0) {
1208 char c;
1211 * Read and write a byte to the file to change the
1212 * modification time, then close the file.
1214 if (read(streamID, &c, 1) == 1) {
1215 (void)lseek(streamID, (off_t)0, SEEK_SET);
1216 while (write(streamID, &c, 1) == -1 && errno == EAGAIN)
1217 continue;
1220 (void)close(streamID);
1221 } else {
1222 (void)fprintf(stderr, "*** couldn't touch %s: %s\n",
1223 file, strerror(errno));
1224 (void)fflush(stderr);
1231 *-----------------------------------------------------------------------
1232 * Job_CheckCommands --
1233 * Make sure the given node has all the commands it needs.
1235 * Input:
1236 * gn The target whose commands need verifying
1237 * abortProc Function to abort with message
1239 * Results:
1240 * TRUE if the commands list is/was ok.
1242 * Side Effects:
1243 * The node will have commands from the .DEFAULT rule added to it
1244 * if it needs them.
1245 *-----------------------------------------------------------------------
1247 Boolean
1248 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1250 if (OP_NOP(gn->type) && Lst_IsEmpty(gn->commands) &&
1251 ((gn->type & OP_LIB) == 0 || Lst_IsEmpty(gn->children))) {
1253 * No commands. Look for .DEFAULT rule from which we might infer
1254 * commands
1256 if ((DEFAULT != NULL) && !Lst_IsEmpty(DEFAULT->commands) &&
1257 (gn->type & OP_SPECIAL) == 0) {
1258 char *p1;
1260 * Make only looks for a .DEFAULT if the node was never the
1261 * target of an operator, so that's what we do too. If
1262 * a .DEFAULT was given, we substitute its commands for gn's
1263 * commands and set the IMPSRC variable to be the target's name
1264 * The DEFAULT node acts like a transformation rule, in that
1265 * gn also inherits any attributes or sources attached to
1266 * .DEFAULT itself.
1268 Make_HandleUse(DEFAULT, gn);
1269 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn, 0);
1270 free(p1);
1271 } else if (Dir_MTime(gn, 0) == 0 && (gn->type & OP_SPECIAL) == 0) {
1273 * The node wasn't the target of an operator we have no .DEFAULT
1274 * rule to go on and the target doesn't already exist. There's
1275 * nothing more we can do for this branch. If the -k flag wasn't
1276 * given, we stop in our tracks, otherwise we just don't update
1277 * this node's parents so they never get examined.
1279 static const char msg[] = ": don't know how to make";
1281 if (gn->flags & FROM_DEPEND) {
1282 if (!Job_RunTarget(".STALE", gn->fname))
1283 fprintf(stdout, "%s: %s, %d: ignoring stale %s for %s\n",
1284 progname, gn->fname, gn->lineno, makeDependfile,
1285 gn->name);
1286 return TRUE;
1289 if (gn->type & OP_OPTIONAL) {
1290 (void)fprintf(stdout, "%s%s %s (ignored)\n", progname,
1291 msg, gn->name);
1292 (void)fflush(stdout);
1293 } else if (keepgoing) {
1294 (void)fprintf(stdout, "%s%s %s (continuing)\n", progname,
1295 msg, gn->name);
1296 (void)fflush(stdout);
1297 return FALSE;
1298 } else {
1299 (*abortProc)("%s%s %s. Stop", progname, msg, gn->name);
1300 return FALSE;
1304 return TRUE;
1308 *-----------------------------------------------------------------------
1309 * JobExec --
1310 * Execute the shell for the given job. Called from JobStart
1312 * Input:
1313 * job Job to execute
1315 * Results:
1316 * None.
1318 * Side Effects:
1319 * A shell is executed, outputs is altered and the Job structure added
1320 * to the job table.
1322 *-----------------------------------------------------------------------
1324 static void
1325 JobExec(Job *job, char **argv)
1327 int cpid; /* ID of new child */
1328 sigset_t mask;
1330 job->flags &= ~JOB_TRACED;
1332 if (DEBUG(JOB)) {
1333 int i;
1335 (void)fprintf(debug_file, "Running %s %sly\n", job->node->name, "local");
1336 (void)fprintf(debug_file, "\tCommand: ");
1337 for (i = 0; argv[i] != NULL; i++) {
1338 (void)fprintf(debug_file, "%s ", argv[i]);
1340 (void)fprintf(debug_file, "\n");
1344 * Some jobs produce no output and it's disconcerting to have
1345 * no feedback of their running (since they produce no output, the
1346 * banner with their name in it never appears). This is an attempt to
1347 * provide that feedback, even if nothing follows it.
1349 if ((lastNode != job->node) && !(job->flags & JOB_SILENT)) {
1350 MESSAGE(stdout, job->node);
1351 lastNode = job->node;
1354 /* No interruptions until this job is on the `jobs' list */
1355 JobSigLock(&mask);
1357 /* Pre-emptively mark job running, pid still zero though */
1358 job->job_state = JOB_ST_RUNNING;
1360 cpid = vFork();
1361 if (cpid == -1)
1362 Punt("Cannot vfork: %s", strerror(errno));
1364 if (cpid == 0) {
1365 /* Child */
1366 sigset_t tmask;
1368 #ifdef USE_META
1369 if (useMeta) {
1370 meta_job_child(job);
1372 #endif
1374 * Reset all signal handlers; this is necessary because we also
1375 * need to unblock signals before we exec(2).
1377 JobSigReset();
1379 /* Now unblock signals */
1380 sigemptyset(&tmask);
1381 JobSigUnlock(&tmask);
1384 * Must duplicate the input stream down to the child's input and
1385 * reset it to the beginning (again). Since the stream was marked
1386 * close-on-exec, we must clear that bit in the new input.
1388 if (dup2(FILENO(job->cmdFILE), 0) == -1) {
1389 execError("dup2", "job->cmdFILE");
1390 _exit(1);
1392 if (fcntl(0, F_SETFD, 0) == -1) {
1393 execError("fcntl clear close-on-exec", "stdin");
1394 _exit(1);
1396 if (lseek(0, (off_t)0, SEEK_SET) == -1) {
1397 execError("lseek to 0", "stdin");
1398 _exit(1);
1401 if (job->node->type & (OP_MAKE | OP_SUBMAKE)) {
1403 * Pass job token pipe to submakes.
1405 if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1) {
1406 execError("clear close-on-exec", "tokenWaitJob.inPipe");
1407 _exit(1);
1409 if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1) {
1410 execError("clear close-on-exec", "tokenWaitJob.outPipe");
1411 _exit(1);
1416 * Set up the child's output to be routed through the pipe
1417 * we've created for it.
1419 if (dup2(job->outPipe, 1) == -1) {
1420 execError("dup2", "job->outPipe");
1421 _exit(1);
1423 if (fcntl(1, F_SETFD, 0) == -1) {
1424 execError("clear close-on-exec", "stdout");
1425 _exit(1);
1429 * We want to switch the child into a different process family so
1430 * we can kill it and all its descendants in one fell swoop,
1431 * by killing its process family, but not commit suicide.
1433 #if defined(HAVE_SETPGID)
1434 (void)setpgid(0, getpid());
1435 #else
1436 #if defined(HAVE_SETSID)
1437 /* XXX: dsl - I'm sure this should be setpgrp()... */
1438 (void)setsid();
1439 #else
1440 (void)setpgrp(0, getpid());
1441 #endif
1442 #endif
1444 Var_ExportVars();
1446 (void)execv(shellPath, argv);
1447 execError("exec", shellPath);
1448 _exit(1);
1451 /* Parent, continuing after the child exec */
1452 job->pid = cpid;
1454 Trace_Log(JOBSTART, job);
1457 * Set the current position in the buffer to the beginning
1458 * and mark another stream to watch in the outputs mask
1460 job->curPos = 0;
1462 watchfd(job);
1464 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1465 (void)fclose(job->cmdFILE);
1466 job->cmdFILE = NULL;
1470 * Now the job is actually running, add it to the table.
1472 if (DEBUG(JOB)) {
1473 fprintf(debug_file, "JobExec(%s): pid %d added to jobs table\n",
1474 job->node->name, job->pid);
1475 job_table_dump("job started");
1477 JobSigUnlock(&mask);
1481 *-----------------------------------------------------------------------
1482 * JobMakeArgv --
1483 * Create the argv needed to execute the shell for a given job.
1486 * Results:
1488 * Side Effects:
1490 *-----------------------------------------------------------------------
1492 static void
1493 JobMakeArgv(Job *job, char **argv)
1495 int argc;
1496 static char args[10]; /* For merged arguments */
1498 argv[0] = UNCONST(shellName);
1499 argc = 1;
1501 if ((commandShell->exit && (*commandShell->exit != '-')) ||
1502 (commandShell->echo && (*commandShell->echo != '-')))
1505 * At least one of the flags doesn't have a minus before it, so
1506 * merge them together. Have to do this because the *(&(@*#*&#$#
1507 * Bourne shell thinks its second argument is a file to source.
1508 * Grrrr. Note the ten-character limitation on the combined arguments.
1510 (void)snprintf(args, sizeof(args), "-%s%s",
1511 ((job->flags & JOB_IGNERR) ? "" :
1512 (commandShell->exit ? commandShell->exit : "")),
1513 ((job->flags & JOB_SILENT) ? "" :
1514 (commandShell->echo ? commandShell->echo : "")));
1516 if (args[1]) {
1517 argv[argc] = args;
1518 argc++;
1520 } else {
1521 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1522 argv[argc] = UNCONST(commandShell->exit);
1523 argc++;
1525 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1526 argv[argc] = UNCONST(commandShell->echo);
1527 argc++;
1530 argv[argc] = NULL;
1534 *-----------------------------------------------------------------------
1535 * JobStart --
1536 * Start a target-creation process going for the target described
1537 * by the graph node gn.
1539 * Input:
1540 * gn target to create
1541 * flags flags for the job to override normal ones.
1542 * e.g. JOB_SPECIAL or JOB_IGNDOTS
1543 * previous The previous Job structure for this node, if any.
1545 * Results:
1546 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1547 * if there isn't actually anything left to do for the job and
1548 * JOB_RUNNING if the job has been started.
1550 * Side Effects:
1551 * A new Job node is created and added to the list of running
1552 * jobs. PMake is forked and a child shell created.
1554 * NB: I'm fairly sure that this code is never called with JOB_SPECIAL set
1555 * JOB_IGNDOTS is never set (dsl)
1556 * Also the return value is ignored by everyone.
1557 *-----------------------------------------------------------------------
1559 static int
1560 JobStart(GNode *gn, int flags)
1562 Job *job; /* new job descriptor */
1563 char *argv[10]; /* Argument vector to shell */
1564 Boolean cmdsOK; /* true if the nodes commands were all right */
1565 Boolean noExec; /* Set true if we decide not to run the job */
1566 int tfd; /* File descriptor to the temp file */
1568 for (job = job_table; job < job_table_end; job++) {
1569 if (job->job_state == JOB_ST_FREE)
1570 break;
1572 if (job >= job_table_end)
1573 Punt("JobStart no job slots vacant");
1575 memset(job, 0, sizeof *job);
1576 job->job_state = JOB_ST_SETUP;
1577 if (gn->type & OP_SPECIAL)
1578 flags |= JOB_SPECIAL;
1580 job->node = gn;
1581 job->tailCmds = NULL;
1584 * Set the initial value of the flags for this job based on the global
1585 * ones and the node's attributes... Any flags supplied by the caller
1586 * are also added to the field.
1588 job->flags = 0;
1589 if (Targ_Ignore(gn)) {
1590 job->flags |= JOB_IGNERR;
1592 if (Targ_Silent(gn)) {
1593 job->flags |= JOB_SILENT;
1595 job->flags |= flags;
1598 * Check the commands now so any attributes from .DEFAULT have a chance
1599 * to migrate to the node
1601 cmdsOK = Job_CheckCommands(gn, Error);
1603 job->inPollfd = NULL;
1605 * If the -n flag wasn't given, we open up OUR (not the child's)
1606 * temporary file to stuff commands in it. The thing is rd/wr so we don't
1607 * need to reopen it to feed it to the shell. If the -n flag *was* given,
1608 * we just set the file to be stdout. Cute, huh?
1610 if (((gn->type & OP_MAKE) && !(noRecursiveExecute)) ||
1611 (!noExecute && !touchFlag)) {
1613 * tfile is the name of a file into which all shell commands are
1614 * put. It is removed before the child shell is executed, unless
1615 * DEBUG(SCRIPT) is set.
1617 char *tfile;
1618 sigset_t mask;
1620 * We're serious here, but if the commands were bogus, we're
1621 * also dead...
1623 if (!cmdsOK) {
1624 PrintOnError(gn, NULL); /* provide some clue */
1625 DieHorribly();
1628 JobSigLock(&mask);
1629 tfd = mkTempFile(TMPPAT, &tfile);
1630 if (!DEBUG(SCRIPT))
1631 (void)eunlink(tfile);
1632 JobSigUnlock(&mask);
1634 job->cmdFILE = fdopen(tfd, "w+");
1635 if (job->cmdFILE == NULL) {
1636 Punt("Could not fdopen %s", tfile);
1638 (void)fcntl(FILENO(job->cmdFILE), F_SETFD, FD_CLOEXEC);
1640 * Send the commands to the command file, flush all its buffers then
1641 * rewind and remove the thing.
1643 noExec = FALSE;
1645 #ifdef USE_META
1646 if (useMeta) {
1647 meta_job_start(job, gn);
1648 if (Targ_Silent(gn)) { /* might have changed */
1649 job->flags |= JOB_SILENT;
1652 #endif
1654 * We can do all the commands at once. hooray for sanity
1656 numCommands = 0;
1657 Lst_ForEach(gn->commands, JobPrintCommand, job);
1660 * If we didn't print out any commands to the shell script,
1661 * there's not much point in executing the shell, is there?
1663 if (numCommands == 0) {
1664 noExec = TRUE;
1667 free(tfile);
1668 } else if (NoExecute(gn)) {
1670 * Not executing anything -- just print all the commands to stdout
1671 * in one fell swoop. This will still set up job->tailCmds correctly.
1673 if (lastNode != gn) {
1674 MESSAGE(stdout, gn);
1675 lastNode = gn;
1677 job->cmdFILE = stdout;
1679 * Only print the commands if they're ok, but don't die if they're
1680 * not -- just let the user know they're bad and keep going. It
1681 * doesn't do any harm in this case and may do some good.
1683 if (cmdsOK) {
1684 Lst_ForEach(gn->commands, JobPrintCommand, job);
1687 * Don't execute the shell, thank you.
1689 noExec = TRUE;
1690 } else {
1692 * Just touch the target and note that no shell should be executed.
1693 * Set cmdFILE to stdout to make life easier. Check the commands, too,
1694 * but don't die if they're no good -- it does no harm to keep working
1695 * up the graph.
1697 job->cmdFILE = stdout;
1698 Job_Touch(gn, job->flags&JOB_SILENT);
1699 noExec = TRUE;
1701 /* Just in case it isn't already... */
1702 (void)fflush(job->cmdFILE);
1705 * If we're not supposed to execute a shell, don't.
1707 if (noExec) {
1708 if (!(job->flags & JOB_SPECIAL))
1709 Job_TokenReturn();
1711 * Unlink and close the command file if we opened one
1713 if (job->cmdFILE != stdout) {
1714 if (job->cmdFILE != NULL) {
1715 (void)fclose(job->cmdFILE);
1716 job->cmdFILE = NULL;
1721 * We only want to work our way up the graph if we aren't here because
1722 * the commands for the job were no good.
1724 if (cmdsOK && aborting == 0) {
1725 if (job->tailCmds != NULL) {
1726 Lst_ForEachFrom(job->node->commands, job->tailCmds,
1727 JobSaveCommand,
1728 job->node);
1730 job->node->made = MADE;
1731 Make_Update(job->node);
1733 job->job_state = JOB_ST_FREE;
1734 return cmdsOK ? JOB_FINISHED : JOB_ERROR;
1738 * Set up the control arguments to the shell. This is based on the flags
1739 * set earlier for this job.
1741 JobMakeArgv(job, argv);
1743 /* Create the pipe by which we'll get the shell's output. */
1744 JobCreatePipe(job, 3);
1746 JobExec(job, argv);
1747 return(JOB_RUNNING);
1750 static char *
1751 JobOutput(Job *job, char *cp, char *endp, int msg)
1753 char *ecp;
1755 if (commandShell->noPrint) {
1756 ecp = Str_FindSubstring(cp, commandShell->noPrint);
1757 while (ecp != NULL) {
1758 if (cp != ecp) {
1759 *ecp = '\0';
1760 if (!beSilent && msg && job->node != lastNode) {
1761 MESSAGE(stdout, job->node);
1762 lastNode = job->node;
1765 * The only way there wouldn't be a newline after
1766 * this line is if it were the last in the buffer.
1767 * however, since the non-printable comes after it,
1768 * there must be a newline, so we don't print one.
1770 (void)fprintf(stdout, "%s", cp);
1771 (void)fflush(stdout);
1773 cp = ecp + commandShell->noPLen;
1774 if (cp != endp) {
1776 * Still more to print, look again after skipping
1777 * the whitespace following the non-printable
1778 * command....
1780 cp++;
1781 while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
1782 cp++;
1784 ecp = Str_FindSubstring(cp, commandShell->noPrint);
1785 } else {
1786 return cp;
1790 return cp;
1794 *-----------------------------------------------------------------------
1795 * JobDoOutput --
1796 * This function is called at different times depending on
1797 * whether the user has specified that output is to be collected
1798 * via pipes or temporary files. In the former case, we are called
1799 * whenever there is something to read on the pipe. We collect more
1800 * output from the given job and store it in the job's outBuf. If
1801 * this makes up a line, we print it tagged by the job's identifier,
1802 * as necessary.
1803 * If output has been collected in a temporary file, we open the
1804 * file and read it line by line, transfering it to our own
1805 * output channel until the file is empty. At which point we
1806 * remove the temporary file.
1807 * In both cases, however, we keep our figurative eye out for the
1808 * 'noPrint' line for the shell from which the output came. If
1809 * we recognize a line, we don't print it. If the command is not
1810 * alone on the line (the character after it is not \0 or \n), we
1811 * do print whatever follows it.
1813 * Input:
1814 * job the job whose output needs printing
1815 * finish TRUE if this is the last time we'll be called
1816 * for this job
1818 * Results:
1819 * None
1821 * Side Effects:
1822 * curPos may be shifted as may the contents of outBuf.
1823 *-----------------------------------------------------------------------
1825 STATIC void
1826 JobDoOutput(Job *job, Boolean finish)
1828 Boolean gotNL = FALSE; /* true if got a newline */
1829 Boolean fbuf; /* true if our buffer filled up */
1830 int nr; /* number of bytes read */
1831 int i; /* auxiliary index into outBuf */
1832 int max; /* limit for i (end of current data) */
1833 int nRead; /* (Temporary) number of bytes read */
1836 * Read as many bytes as will fit in the buffer.
1838 end_loop:
1839 gotNL = FALSE;
1840 fbuf = FALSE;
1842 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1843 JOB_BUFSIZE - job->curPos);
1844 if (nRead < 0) {
1845 if (errno == EAGAIN)
1846 return;
1847 if (DEBUG(JOB)) {
1848 perror("JobDoOutput(piperead)");
1850 nr = 0;
1851 } else {
1852 nr = nRead;
1856 * If we hit the end-of-file (the job is dead), we must flush its
1857 * remaining output, so pretend we read a newline if there's any
1858 * output remaining in the buffer.
1859 * Also clear the 'finish' flag so we stop looping.
1861 if ((nr == 0) && (job->curPos != 0)) {
1862 job->outBuf[job->curPos] = '\n';
1863 nr = 1;
1864 finish = FALSE;
1865 } else if (nr == 0) {
1866 finish = FALSE;
1870 * Look for the last newline in the bytes we just got. If there is
1871 * one, break out of the loop with 'i' as its index and gotNL set
1872 * TRUE.
1874 max = job->curPos + nr;
1875 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1876 if (job->outBuf[i] == '\n') {
1877 gotNL = TRUE;
1878 break;
1879 } else if (job->outBuf[i] == '\0') {
1881 * Why?
1883 job->outBuf[i] = ' ';
1887 if (!gotNL) {
1888 job->curPos += nr;
1889 if (job->curPos == JOB_BUFSIZE) {
1891 * If we've run out of buffer space, we have no choice
1892 * but to print the stuff. sigh.
1894 fbuf = TRUE;
1895 i = job->curPos;
1898 if (gotNL || fbuf) {
1900 * Need to send the output to the screen. Null terminate it
1901 * first, overwriting the newline character if there was one.
1902 * So long as the line isn't one we should filter (according
1903 * to the shell description), we print the line, preceded
1904 * by a target banner if this target isn't the same as the
1905 * one for which we last printed something.
1906 * The rest of the data in the buffer are then shifted down
1907 * to the start of the buffer and curPos is set accordingly.
1909 job->outBuf[i] = '\0';
1910 if (i >= job->curPos) {
1911 char *cp;
1913 cp = JobOutput(job, job->outBuf, &job->outBuf[i], FALSE);
1916 * There's still more in that thar buffer. This time, though,
1917 * we know there's no newline at the end, so we add one of
1918 * our own free will.
1920 if (*cp != '\0') {
1921 if (!beSilent && job->node != lastNode) {
1922 MESSAGE(stdout, job->node);
1923 lastNode = job->node;
1925 #ifdef USE_META
1926 if (useMeta) {
1927 meta_job_output(job, cp, gotNL ? "\n" : "");
1929 #endif
1930 (void)fprintf(stdout, "%s%s", cp, gotNL ? "\n" : "");
1931 (void)fflush(stdout);
1935 * max is the last offset still in the buffer. Move any remaining
1936 * characters to the start of the buffer and update the end marker
1937 * curPos.
1939 if (i < max) {
1940 (void)memmove(job->outBuf, &job->outBuf[i + 1], max - (i + 1));
1941 job->curPos = max - (i + 1);
1942 } else {
1943 assert(i == max);
1944 job->curPos = 0;
1947 if (finish) {
1949 * If the finish flag is true, we must loop until we hit
1950 * end-of-file on the pipe. This is guaranteed to happen
1951 * eventually since the other end of the pipe is now closed
1952 * (we closed it explicitly and the child has exited). When
1953 * we do get an EOF, finish will be set FALSE and we'll fall
1954 * through and out.
1956 goto end_loop;
1960 static void
1961 JobRun(GNode *targ)
1963 #ifdef notyet
1965 * Unfortunately it is too complicated to run .BEGIN, .END,
1966 * and .INTERRUPT job in the parallel job module. This has
1967 * the nice side effect that it avoids a lot of other problems.
1969 Lst lst = Lst_Init(FALSE);
1970 Lst_AtEnd(lst, targ);
1971 (void)Make_Run(lst);
1972 Lst_Destroy(lst, NULL);
1973 JobStart(targ, JOB_SPECIAL);
1974 while (jobTokensRunning) {
1975 Job_CatchOutput();
1977 #else
1978 Compat_Make(targ, targ);
1979 if (targ->made == ERROR) {
1980 PrintOnError(targ, "\n\nStop.");
1981 exit(1);
1983 #endif
1987 *-----------------------------------------------------------------------
1988 * Job_CatchChildren --
1989 * Handle the exit of a child. Called from Make_Make.
1991 * Input:
1992 * block TRUE if should block on the wait
1994 * Results:
1995 * none.
1997 * Side Effects:
1998 * The job descriptor is removed from the list of children.
2000 * Notes:
2001 * We do waits, blocking or not, according to the wisdom of our
2002 * caller, until there are no more children to report. For each
2003 * job, call JobFinish to finish things off.
2005 *-----------------------------------------------------------------------
2008 void
2009 Job_CatchChildren(void)
2011 int pid; /* pid of dead child */
2012 WAIT_T status; /* Exit/termination status */
2015 * Don't even bother if we know there's no one around.
2017 if (jobTokensRunning == 0)
2018 return;
2020 while ((pid = waitpid((pid_t) -1, &status, WNOHANG | WUNTRACED)) > 0) {
2021 if (DEBUG(JOB)) {
2022 (void)fprintf(debug_file, "Process %d exited/stopped status %x.\n", pid,
2023 WAIT_STATUS(status));
2025 JobReapChild(pid, status, TRUE);
2030 * It is possible that wait[pid]() was called from elsewhere,
2031 * this lets us reap jobs regardless.
2033 void
2034 JobReapChild(pid_t pid, WAIT_T status, Boolean isJobs)
2036 Job *job; /* job descriptor for dead child */
2039 * Don't even bother if we know there's no one around.
2041 if (jobTokensRunning == 0)
2042 return;
2044 job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
2045 if (job == NULL) {
2046 if (isJobs) {
2047 if (!lurking_children)
2048 Error("Child (%d) status %x not in table?", pid, status);
2050 return; /* not ours */
2052 if (WIFSTOPPED(status)) {
2053 if (DEBUG(JOB)) {
2054 (void)fprintf(debug_file, "Process %d (%s) stopped.\n",
2055 job->pid, job->node->name);
2057 if (!make_suspended) {
2058 switch (WSTOPSIG(status)) {
2059 case SIGTSTP:
2060 (void)fprintf(stderr, "*** [%s] Suspended\n", job->node->name);
2061 break;
2062 case SIGSTOP:
2063 (void)fprintf(stderr, "*** [%s] Stopped\n", job->node->name);
2064 break;
2065 default:
2066 (void)fprintf(stderr, "*** [%s] Stopped -- signal %d\n",
2067 job->node->name, WSTOPSIG(status));
2069 job->job_suspended = 1;
2071 (void)fflush(stdout);
2072 return;
2075 job->job_state = JOB_ST_FINISHED;
2076 job->exit_status = WAIT_STATUS(status);
2078 JobFinish(job, status);
2082 *-----------------------------------------------------------------------
2083 * Job_CatchOutput --
2084 * Catch the output from our children, if we're using
2085 * pipes do so. Otherwise just block time until we get a
2086 * signal(most likely a SIGCHLD) since there's no point in
2087 * just spinning when there's nothing to do and the reaping
2088 * of a child can wait for a while.
2090 * Results:
2091 * None
2093 * Side Effects:
2094 * Output is read from pipes if we're piping.
2095 * -----------------------------------------------------------------------
2097 void
2098 Job_CatchOutput(void)
2100 int nready;
2101 Job *job;
2102 int i;
2104 (void)fflush(stdout);
2106 /* The first fd in the list is the job token pipe */
2107 do {
2108 nready = poll(fds + 1 - wantToken, nfds - 1 + wantToken, POLL_MSEC);
2109 } while (nready < 0 && errno == EINTR);
2111 if (nready < 0)
2112 Punt("poll: %s", strerror(errno));
2114 if (nready > 0 && readyfd(&childExitJob)) {
2115 char token = 0;
2116 ssize_t count;
2117 count = read(childExitJob.inPipe, &token, 1);
2118 switch (count) {
2119 case 0:
2120 Punt("unexpected eof on token pipe");
2121 case -1:
2122 Punt("token pipe read: %s", strerror(errno));
2123 case 1:
2124 if (token == DO_JOB_RESUME[0])
2125 /* Complete relay requested from our SIGCONT handler */
2126 JobRestartJobs();
2127 break;
2128 default:
2129 abort();
2131 --nready;
2134 Job_CatchChildren();
2135 if (nready == 0)
2136 return;
2138 for (i = 2; i < nfds; i++) {
2139 if (!fds[i].revents)
2140 continue;
2141 job = jobfds[i];
2142 if (job->job_state == JOB_ST_RUNNING)
2143 JobDoOutput(job, FALSE);
2144 if (--nready == 0)
2145 return;
2150 *-----------------------------------------------------------------------
2151 * Job_Make --
2152 * Start the creation of a target. Basically a front-end for
2153 * JobStart used by the Make module.
2155 * Results:
2156 * None.
2158 * Side Effects:
2159 * Another job is started.
2161 *-----------------------------------------------------------------------
2163 void
2164 Job_Make(GNode *gn)
2166 (void)JobStart(gn, 0);
2169 void
2170 Shell_Init(void)
2172 if (shellPath == NULL) {
2174 * We are using the default shell, which may be an absolute
2175 * path if DEFSHELL_CUSTOM is defined.
2177 shellName = commandShell->name;
2178 #ifdef DEFSHELL_CUSTOM
2179 if (*shellName == '/') {
2180 shellPath = shellName;
2181 shellName = strrchr(shellPath, '/');
2182 shellName++;
2183 } else
2184 #endif
2185 shellPath = str_concat(_PATH_DEFSHELLDIR, shellName, STR_ADDSLASH);
2187 if (commandShell->exit == NULL) {
2188 commandShell->exit = "";
2190 if (commandShell->echo == NULL) {
2191 commandShell->echo = "";
2193 if (commandShell->hasErrCtl && *commandShell->exit) {
2194 if (shellErrFlag &&
2195 strcmp(commandShell->exit, &shellErrFlag[1]) != 0) {
2196 free(shellErrFlag);
2197 shellErrFlag = NULL;
2199 if (!shellErrFlag) {
2200 int n = strlen(commandShell->exit) + 2;
2202 shellErrFlag = bmake_malloc(n);
2203 if (shellErrFlag) {
2204 snprintf(shellErrFlag, n, "-%s", commandShell->exit);
2207 } else if (shellErrFlag) {
2208 free(shellErrFlag);
2209 shellErrFlag = NULL;
2214 * Returns the string literal that is used in the current command shell
2215 * to produce a newline character.
2217 const char *
2218 Shell_GetNewline(void)
2221 return commandShell->newline;
2224 void
2225 Job_SetPrefix(void)
2228 if (targPrefix) {
2229 free(targPrefix);
2230 } else if (!Var_Exists(MAKE_JOB_PREFIX, VAR_GLOBAL)) {
2231 Var_Set(MAKE_JOB_PREFIX, "---", VAR_GLOBAL, 0);
2234 targPrefix = Var_Subst(NULL, "${" MAKE_JOB_PREFIX "}",
2235 VAR_GLOBAL, VARF_WANTRES);
2239 *-----------------------------------------------------------------------
2240 * Job_Init --
2241 * Initialize the process module
2243 * Input:
2245 * Results:
2246 * none
2248 * Side Effects:
2249 * lists and counters are initialized
2250 *-----------------------------------------------------------------------
2252 void
2253 Job_Init(void)
2255 Job_SetPrefix();
2256 /* Allocate space for all the job info */
2257 job_table = bmake_malloc(maxJobs * sizeof *job_table);
2258 memset(job_table, 0, maxJobs * sizeof *job_table);
2259 job_table_end = job_table + maxJobs;
2260 wantToken = 0;
2262 aborting = 0;
2263 errors = 0;
2265 lastNode = NULL;
2268 * There is a non-zero chance that we already have children.
2269 * eg after 'make -f- <<EOF'
2270 * Since their termination causes a 'Child (pid) not in table' message,
2271 * Collect the status of any that are already dead, and suppress the
2272 * error message if there are any undead ones.
2274 for (;;) {
2275 int rval, status;
2276 rval = waitpid((pid_t) -1, &status, WNOHANG);
2277 if (rval > 0)
2278 continue;
2279 if (rval == 0)
2280 lurking_children = 1;
2281 break;
2284 Shell_Init();
2286 JobCreatePipe(&childExitJob, 3);
2288 /* We can only need to wait for tokens, children and output from each job */
2289 fds = bmake_malloc(sizeof (*fds) * (2 + maxJobs));
2290 jobfds = bmake_malloc(sizeof (*jobfds) * (2 + maxJobs));
2292 /* These are permanent entries and take slots 0 and 1 */
2293 watchfd(&tokenWaitJob);
2294 watchfd(&childExitJob);
2296 sigemptyset(&caught_signals);
2298 * Install a SIGCHLD handler.
2300 (void)bmake_signal(SIGCHLD, JobChildSig);
2301 sigaddset(&caught_signals, SIGCHLD);
2303 #define ADDSIG(s,h) \
2304 if (bmake_signal(s, SIG_IGN) != SIG_IGN) { \
2305 sigaddset(&caught_signals, s); \
2306 (void)bmake_signal(s, h); \
2310 * Catch the four signals that POSIX specifies if they aren't ignored.
2311 * JobPassSig will take care of calling JobInterrupt if appropriate.
2313 ADDSIG(SIGINT, JobPassSig_int)
2314 ADDSIG(SIGHUP, JobPassSig_term)
2315 ADDSIG(SIGTERM, JobPassSig_term)
2316 ADDSIG(SIGQUIT, JobPassSig_term)
2319 * There are additional signals that need to be caught and passed if
2320 * either the export system wants to be told directly of signals or if
2321 * we're giving each job its own process group (since then it won't get
2322 * signals from the terminal driver as we own the terminal)
2324 ADDSIG(SIGTSTP, JobPassSig_suspend)
2325 ADDSIG(SIGTTOU, JobPassSig_suspend)
2326 ADDSIG(SIGTTIN, JobPassSig_suspend)
2327 ADDSIG(SIGWINCH, JobCondPassSig)
2328 ADDSIG(SIGCONT, JobContinueSig)
2329 #undef ADDSIG
2331 (void)Job_RunTarget(".BEGIN", NULL);
2332 postCommands = Targ_FindNode(".END", TARG_CREATE);
2335 static void JobSigReset(void)
2337 #define DELSIG(s) \
2338 if (sigismember(&caught_signals, s)) { \
2339 (void)bmake_signal(s, SIG_DFL); \
2342 DELSIG(SIGINT)
2343 DELSIG(SIGHUP)
2344 DELSIG(SIGQUIT)
2345 DELSIG(SIGTERM)
2346 DELSIG(SIGTSTP)
2347 DELSIG(SIGTTOU)
2348 DELSIG(SIGTTIN)
2349 DELSIG(SIGWINCH)
2350 DELSIG(SIGCONT)
2351 #undef DELSIG
2352 (void)bmake_signal(SIGCHLD, SIG_DFL);
2356 *-----------------------------------------------------------------------
2357 * JobMatchShell --
2358 * Find a shell in 'shells' given its name.
2360 * Results:
2361 * A pointer to the Shell structure.
2363 * Side Effects:
2364 * None.
2366 *-----------------------------------------------------------------------
2368 static Shell *
2369 JobMatchShell(const char *name)
2371 Shell *sh;
2373 for (sh = shells; sh->name != NULL; sh++) {
2374 if (strcmp(name, sh->name) == 0)
2375 return (sh);
2377 return NULL;
2381 *-----------------------------------------------------------------------
2382 * Job_ParseShell --
2383 * Parse a shell specification and set up commandShell, shellPath
2384 * and shellName appropriately.
2386 * Input:
2387 * line The shell spec
2389 * Results:
2390 * FAILURE if the specification was incorrect.
2392 * Side Effects:
2393 * commandShell points to a Shell structure (either predefined or
2394 * created from the shell spec), shellPath is the full path of the
2395 * shell described by commandShell, while shellName is just the
2396 * final component of shellPath.
2398 * Notes:
2399 * A shell specification consists of a .SHELL target, with dependency
2400 * operator, followed by a series of blank-separated words. Double
2401 * quotes can be used to use blanks in words. A backslash escapes
2402 * anything (most notably a double-quote and a space) and
2403 * provides the functionality it does in C. Each word consists of
2404 * keyword and value separated by an equal sign. There should be no
2405 * unnecessary spaces in the word. The keywords are as follows:
2406 * name Name of shell.
2407 * path Location of shell.
2408 * quiet Command to turn off echoing.
2409 * echo Command to turn echoing on
2410 * filter Result of turning off echoing that shouldn't be
2411 * printed.
2412 * echoFlag Flag to turn echoing on at the start
2413 * errFlag Flag to turn error checking on at the start
2414 * hasErrCtl True if shell has error checking control
2415 * newline String literal to represent a newline char
2416 * check Command to turn on error checking if hasErrCtl
2417 * is TRUE or template of command to echo a command
2418 * for which error checking is off if hasErrCtl is
2419 * FALSE.
2420 * ignore Command to turn off error checking if hasErrCtl
2421 * is TRUE or template of command to execute a
2422 * command so as to ignore any errors it returns if
2423 * hasErrCtl is FALSE.
2425 *-----------------------------------------------------------------------
2427 ReturnStatus
2428 Job_ParseShell(char *line)
2430 char **words;
2431 char **argv;
2432 int argc;
2433 char *path;
2434 Shell newShell;
2435 Boolean fullSpec = FALSE;
2436 Shell *sh;
2438 while (isspace((unsigned char)*line)) {
2439 line++;
2442 free(UNCONST(shellArgv));
2444 memset(&newShell, 0, sizeof(newShell));
2447 * Parse the specification by keyword
2449 words = brk_string(line, &argc, TRUE, &path);
2450 if (words == NULL) {
2451 Error("Unterminated quoted string [%s]", line);
2452 return FAILURE;
2454 shellArgv = path;
2456 for (path = NULL, argv = words; argc != 0; argc--, argv++) {
2457 if (strncmp(*argv, "path=", 5) == 0) {
2458 path = &argv[0][5];
2459 } else if (strncmp(*argv, "name=", 5) == 0) {
2460 newShell.name = &argv[0][5];
2461 } else {
2462 if (strncmp(*argv, "quiet=", 6) == 0) {
2463 newShell.echoOff = &argv[0][6];
2464 } else if (strncmp(*argv, "echo=", 5) == 0) {
2465 newShell.echoOn = &argv[0][5];
2466 } else if (strncmp(*argv, "filter=", 7) == 0) {
2467 newShell.noPrint = &argv[0][7];
2468 newShell.noPLen = strlen(newShell.noPrint);
2469 } else if (strncmp(*argv, "echoFlag=", 9) == 0) {
2470 newShell.echo = &argv[0][9];
2471 } else if (strncmp(*argv, "errFlag=", 8) == 0) {
2472 newShell.exit = &argv[0][8];
2473 } else if (strncmp(*argv, "hasErrCtl=", 10) == 0) {
2474 char c = argv[0][10];
2475 newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
2476 (c != 'T') && (c != 't'));
2477 } else if (strncmp(*argv, "newline=", 8) == 0) {
2478 newShell.newline = &argv[0][8];
2479 } else if (strncmp(*argv, "check=", 6) == 0) {
2480 newShell.errCheck = &argv[0][6];
2481 } else if (strncmp(*argv, "ignore=", 7) == 0) {
2482 newShell.ignErr = &argv[0][7];
2483 } else if (strncmp(*argv, "errout=", 7) == 0) {
2484 newShell.errOut = &argv[0][7];
2485 } else if (strncmp(*argv, "comment=", 8) == 0) {
2486 newShell.commentChar = argv[0][8];
2487 } else {
2488 Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"",
2489 *argv);
2490 free(words);
2491 return(FAILURE);
2493 fullSpec = TRUE;
2497 if (path == NULL) {
2499 * If no path was given, the user wants one of the pre-defined shells,
2500 * yes? So we find the one s/he wants with the help of JobMatchShell
2501 * and set things up the right way. shellPath will be set up by
2502 * Shell_Init.
2504 if (newShell.name == NULL) {
2505 Parse_Error(PARSE_FATAL, "Neither path nor name specified");
2506 free(words);
2507 return(FAILURE);
2508 } else {
2509 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2510 Parse_Error(PARSE_WARNING, "%s: No matching shell",
2511 newShell.name);
2512 free(words);
2513 return(FAILURE);
2515 commandShell = sh;
2516 shellName = newShell.name;
2517 if (shellPath) {
2518 /* Shell_Init has already been called! Do it again. */
2519 free(UNCONST(shellPath));
2520 shellPath = NULL;
2521 Shell_Init();
2524 } else {
2526 * The user provided a path. If s/he gave nothing else (fullSpec is
2527 * FALSE), try and find a matching shell in the ones we know of.
2528 * Else we just take the specification at its word and copy it
2529 * to a new location. In either case, we need to record the
2530 * path the user gave for the shell.
2532 shellPath = path;
2533 path = strrchr(path, '/');
2534 if (path == NULL) {
2535 path = UNCONST(shellPath);
2536 } else {
2537 path += 1;
2539 if (newShell.name != NULL) {
2540 shellName = newShell.name;
2541 } else {
2542 shellName = path;
2544 if (!fullSpec) {
2545 if ((sh = JobMatchShell(shellName)) == NULL) {
2546 Parse_Error(PARSE_WARNING, "%s: No matching shell",
2547 shellName);
2548 free(words);
2549 return(FAILURE);
2551 commandShell = sh;
2552 } else {
2553 commandShell = bmake_malloc(sizeof(Shell));
2554 *commandShell = newShell;
2556 /* this will take care of shellErrFlag */
2557 Shell_Init();
2560 if (commandShell->echoOn && commandShell->echoOff) {
2561 commandShell->hasEchoCtl = TRUE;
2564 if (!commandShell->hasErrCtl) {
2565 if (commandShell->errCheck == NULL) {
2566 commandShell->errCheck = "";
2568 if (commandShell->ignErr == NULL) {
2569 commandShell->ignErr = "%s\n";
2574 * Do not free up the words themselves, since they might be in use by the
2575 * shell specification.
2577 free(words);
2578 return SUCCESS;
2582 *-----------------------------------------------------------------------
2583 * JobInterrupt --
2584 * Handle the receipt of an interrupt.
2586 * Input:
2587 * runINTERRUPT Non-zero if commands for the .INTERRUPT target
2588 * should be executed
2589 * signo signal received
2591 * Results:
2592 * None
2594 * Side Effects:
2595 * All children are killed. Another job will be started if the
2596 * .INTERRUPT target was given.
2597 *-----------------------------------------------------------------------
2599 static void
2600 JobInterrupt(int runINTERRUPT, int signo)
2602 Job *job; /* job descriptor in that element */
2603 GNode *interrupt; /* the node describing the .INTERRUPT target */
2604 sigset_t mask;
2605 GNode *gn;
2607 aborting = ABORT_INTERRUPT;
2609 JobSigLock(&mask);
2611 for (job = job_table; job < job_table_end; job++) {
2612 if (job->job_state != JOB_ST_RUNNING)
2613 continue;
2615 gn = job->node;
2617 JobDeleteTarget(gn);
2618 if (job->pid) {
2619 if (DEBUG(JOB)) {
2620 (void)fprintf(debug_file,
2621 "JobInterrupt passing signal %d to child %d.\n",
2622 signo, job->pid);
2624 KILLPG(job->pid, signo);
2628 JobSigUnlock(&mask);
2630 if (runINTERRUPT && !touchFlag) {
2631 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2632 if (interrupt != NULL) {
2633 ignoreErrors = FALSE;
2634 JobRun(interrupt);
2637 Trace_Log(MAKEINTR, 0);
2638 exit(signo);
2642 *-----------------------------------------------------------------------
2643 * Job_Finish --
2644 * Do final processing such as the running of the commands
2645 * attached to the .END target.
2647 * Results:
2648 * Number of errors reported.
2650 * Side Effects:
2651 * None.
2652 *-----------------------------------------------------------------------
2655 Job_Finish(void)
2657 if (postCommands != NULL &&
2658 (!Lst_IsEmpty(postCommands->commands) ||
2659 !Lst_IsEmpty(postCommands->children))) {
2660 if (errors) {
2661 Error("Errors reported so .END ignored");
2662 } else {
2663 JobRun(postCommands);
2666 return(errors);
2670 *-----------------------------------------------------------------------
2671 * Job_End --
2672 * Cleanup any memory used by the jobs module
2674 * Results:
2675 * None.
2677 * Side Effects:
2678 * Memory is freed
2679 *-----------------------------------------------------------------------
2681 void
2682 Job_End(void)
2684 #ifdef CLEANUP
2685 free(shellArgv);
2686 #endif
2690 *-----------------------------------------------------------------------
2691 * Job_Wait --
2692 * Waits for all running jobs to finish and returns. Sets 'aborting'
2693 * to ABORT_WAIT to prevent other jobs from starting.
2695 * Results:
2696 * None.
2698 * Side Effects:
2699 * Currently running jobs finish.
2701 *-----------------------------------------------------------------------
2703 void
2704 Job_Wait(void)
2706 aborting = ABORT_WAIT;
2707 while (jobTokensRunning != 0) {
2708 Job_CatchOutput();
2710 aborting = 0;
2714 *-----------------------------------------------------------------------
2715 * Job_AbortAll --
2716 * Abort all currently running jobs without handling output or anything.
2717 * This function is to be called only in the event of a major
2718 * error. Most definitely NOT to be called from JobInterrupt.
2720 * Results:
2721 * None
2723 * Side Effects:
2724 * All children are killed, not just the firstborn
2725 *-----------------------------------------------------------------------
2727 void
2728 Job_AbortAll(void)
2730 Job *job; /* the job descriptor in that element */
2731 WAIT_T foo;
2733 aborting = ABORT_ERROR;
2735 if (jobTokensRunning) {
2736 for (job = job_table; job < job_table_end; job++) {
2737 if (job->job_state != JOB_ST_RUNNING)
2738 continue;
2740 * kill the child process with increasingly drastic signals to make
2741 * darn sure it's dead.
2743 KILLPG(job->pid, SIGINT);
2744 KILLPG(job->pid, SIGKILL);
2749 * Catch as many children as want to report in at first, then give up
2751 while (waitpid((pid_t) -1, &foo, WNOHANG) > 0)
2752 continue;
2757 *-----------------------------------------------------------------------
2758 * JobRestartJobs --
2759 * Tries to restart stopped jobs if there are slots available.
2760 * Called in process context in response to a SIGCONT.
2762 * Results:
2763 * None.
2765 * Side Effects:
2766 * Resumes jobs.
2768 *-----------------------------------------------------------------------
2770 static void
2771 JobRestartJobs(void)
2773 Job *job;
2775 for (job = job_table; job < job_table_end; job++) {
2776 if (job->job_state == JOB_ST_RUNNING &&
2777 (make_suspended || job->job_suspended)) {
2778 if (DEBUG(JOB)) {
2779 (void)fprintf(debug_file, "Restarting stopped job pid %d.\n",
2780 job->pid);
2782 if (job->job_suspended) {
2783 (void)fprintf(stderr, "*** [%s] Continued\n", job->node->name);
2784 (void)fflush(stderr);
2786 job->job_suspended = 0;
2787 if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
2788 fprintf(debug_file, "Failed to send SIGCONT to %d\n", job->pid);
2791 if (job->job_state == JOB_ST_FINISHED)
2792 /* Job exit deferred after calling waitpid() in a signal handler */
2793 JobFinish(job, job->exit_status);
2795 make_suspended = 0;
2798 static void
2799 watchfd(Job *job)
2801 if (job->inPollfd != NULL)
2802 Punt("Watching watched job");
2804 fds[nfds].fd = job->inPipe;
2805 fds[nfds].events = POLLIN;
2806 jobfds[nfds] = job;
2807 job->inPollfd = &fds[nfds];
2808 nfds++;
2811 static void
2812 clearfd(Job *job)
2814 int i;
2815 if (job->inPollfd == NULL)
2816 Punt("Unwatching unwatched job");
2817 i = job->inPollfd - fds;
2818 nfds--;
2820 * Move last job in table into hole made by dead job.
2822 if (nfds != i) {
2823 fds[i] = fds[nfds];
2824 jobfds[i] = jobfds[nfds];
2825 jobfds[i]->inPollfd = &fds[i];
2827 job->inPollfd = NULL;
2830 static int
2831 readyfd(Job *job)
2833 if (job->inPollfd == NULL)
2834 Punt("Polling unwatched job");
2835 return (job->inPollfd->revents & POLLIN) != 0;
2839 *-----------------------------------------------------------------------
2840 * JobTokenAdd --
2841 * Put a token into the job pipe so that some make process can start
2842 * another job.
2844 * Side Effects:
2845 * Allows more build jobs to be spawned somewhere.
2847 *-----------------------------------------------------------------------
2850 static void
2851 JobTokenAdd(void)
2853 char tok = JOB_TOKENS[aborting], tok1;
2855 /* If we are depositing an error token flush everything else */
2856 while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2857 continue;
2859 if (DEBUG(JOB))
2860 fprintf(debug_file, "(%d) aborting %d, deposit token %c\n",
2861 getpid(), aborting, JOB_TOKENS[aborting]);
2862 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2863 continue;
2867 *-----------------------------------------------------------------------
2868 * Job_ServerStartTokenAdd --
2869 * Prep the job token pipe in the root make process.
2871 *-----------------------------------------------------------------------
2874 void
2875 Job_ServerStart(int max_tokens, int jp_0, int jp_1)
2877 int i;
2878 char jobarg[64];
2880 if (jp_0 >= 0 && jp_1 >= 0) {
2881 /* Pipe passed in from parent */
2882 tokenWaitJob.inPipe = jp_0;
2883 tokenWaitJob.outPipe = jp_1;
2884 (void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
2885 (void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
2886 return;
2889 JobCreatePipe(&tokenWaitJob, 15);
2891 snprintf(jobarg, sizeof(jobarg), "%d,%d",
2892 tokenWaitJob.inPipe, tokenWaitJob.outPipe);
2894 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
2895 Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
2898 * Preload the job pipe with one token per job, save the one
2899 * "extra" token for the primary job.
2901 * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
2902 * larger than the write buffer size of the pipe, we will
2903 * deadlock here.
2905 for (i = 1; i < max_tokens; i++)
2906 JobTokenAdd();
2910 *-----------------------------------------------------------------------
2911 * Job_TokenReturn --
2912 * Return a withdrawn token to the pool.
2914 *-----------------------------------------------------------------------
2917 void
2918 Job_TokenReturn(void)
2920 jobTokensRunning--;
2921 if (jobTokensRunning < 0)
2922 Punt("token botch");
2923 if (jobTokensRunning || JOB_TOKENS[aborting] != '+')
2924 JobTokenAdd();
2928 *-----------------------------------------------------------------------
2929 * Job_TokenWithdraw --
2930 * Attempt to withdraw a token from the pool.
2932 * Results:
2933 * Returns TRUE if a token was withdrawn, and FALSE if the pool
2934 * is currently empty.
2936 * Side Effects:
2937 * If pool is empty, set wantToken so that we wake up
2938 * when a token is released.
2940 *-----------------------------------------------------------------------
2944 Boolean
2945 Job_TokenWithdraw(void)
2947 char tok, tok1;
2948 int count;
2950 wantToken = 0;
2951 if (DEBUG(JOB))
2952 fprintf(debug_file, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
2953 getpid(), aborting, jobTokensRunning);
2955 if (aborting || (jobTokensRunning >= maxJobs))
2956 return FALSE;
2958 count = read(tokenWaitJob.inPipe, &tok, 1);
2959 if (count == 0)
2960 Fatal("eof on job pipe!");
2961 if (count < 0 && jobTokensRunning != 0) {
2962 if (errno != EAGAIN) {
2963 Fatal("job pipe read: %s", strerror(errno));
2965 if (DEBUG(JOB))
2966 fprintf(debug_file, "(%d) blocked for token\n", getpid());
2967 wantToken = 1;
2968 return FALSE;
2971 if (count == 1 && tok != '+') {
2972 /* make being abvorted - remove any other job tokens */
2973 if (DEBUG(JOB))
2974 fprintf(debug_file, "(%d) aborted by token %c\n", getpid(), tok);
2975 while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2976 continue;
2977 /* And put the stopper back */
2978 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2979 continue;
2980 Fatal("A failure has been detected in another branch of the parallel make");
2983 if (count == 1 && jobTokensRunning == 0)
2984 /* We didn't want the token really */
2985 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2986 continue;
2988 jobTokensRunning++;
2989 if (DEBUG(JOB))
2990 fprintf(debug_file, "(%d) withdrew token\n", getpid());
2991 return TRUE;
2995 *-----------------------------------------------------------------------
2996 * Job_RunTarget --
2997 * Run the named target if found. If a filename is specified, then
2998 * set that to the sources.
3000 * Results:
3001 * None
3003 * Side Effects:
3004 * exits if the target fails.
3006 *-----------------------------------------------------------------------
3008 Boolean
3009 Job_RunTarget(const char *target, const char *fname) {
3010 GNode *gn = Targ_FindNode(target, TARG_NOCREATE);
3012 if (gn == NULL)
3013 return FALSE;
3015 if (fname)
3016 Var_Set(ALLSRC, fname, gn, 0);
3018 JobRun(gn);
3019 if (gn->made == ERROR) {
3020 PrintOnError(gn, "\n\nStop.");
3021 exit(1);
3023 return TRUE;
3026 #ifdef USE_SELECT
3028 emul_poll(struct pollfd *fd, int nfd, int timeout)
3030 fd_set rfds, wfds;
3031 int i, maxfd, nselect, npoll;
3032 struct timeval tv, *tvp;
3033 long usecs;
3035 FD_ZERO(&rfds);
3036 FD_ZERO(&wfds);
3038 maxfd = -1;
3039 for (i = 0; i < nfd; i++) {
3040 fd[i].revents = 0;
3042 if (fd[i].events & POLLIN)
3043 FD_SET(fd[i].fd, &rfds);
3045 if (fd[i].events & POLLOUT)
3046 FD_SET(fd[i].fd, &wfds);
3048 if (fd[i].fd > maxfd)
3049 maxfd = fd[i].fd;
3052 if (maxfd >= FD_SETSIZE) {
3053 Punt("Ran out of fd_set slots; "
3054 "recompile with a larger FD_SETSIZE.");
3057 if (timeout < 0) {
3058 tvp = NULL;
3059 } else {
3060 usecs = timeout * 1000;
3061 tv.tv_sec = usecs / 1000000;
3062 tv.tv_usec = usecs % 1000000;
3063 tvp = &tv;
3066 nselect = select(maxfd + 1, &rfds, &wfds, 0, tvp);
3068 if (nselect <= 0)
3069 return nselect;
3071 npoll = 0;
3072 for (i = 0; i < nfd; i++) {
3073 if (FD_ISSET(fd[i].fd, &rfds))
3074 fd[i].revents |= POLLIN;
3076 if (FD_ISSET(fd[i].fd, &wfds))
3077 fd[i].revents |= POLLOUT;
3079 if (fd[i].revents)
3080 npoll++;
3083 return npoll;
3085 #endif /* USE_SELECT */