job.c revision 1.187.2.1 1 /* $NetBSD: job.c,v 1.187.2.1 2017/04/26 02:53:35 pgoyette Exp $ */
2
3 /*
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
9 *
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.
21 *
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.
33 */
34
35 /*
36 * Copyright (c) 1988, 1989 by Adam de Boor
37 * Copyright (c) 1989 by Berkeley Softworks
38 * All rights reserved.
39 *
40 * This code is derived from software contributed to Berkeley by
41 * Adam de Boor.
42 *
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.
58 *
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.
70 */
71
72 #ifndef MAKE_NATIVE
73 static char rcsid[] = "$NetBSD: job.c,v 1.187.2.1 2017/04/26 02:53:35 pgoyette 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.187.2.1 2017/04/26 02:53:35 pgoyette Exp $");
81 #endif
82 #endif /* not lint */
83 #endif
84
85 /*-
86 * job.c --
87 * handle the creation etc. of our child processes.
88 *
89 * Interface:
90 * Job_Make Start the creation of the given target.
91 *
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.
97 *
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.
104 *
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.
110 *
111 * Job_End Cleanup any memory used.
112 *
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.
116 *
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.
122 *
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.
127 *
128 * Job_CheckCommands Verify that the commands for a target are
129 * ok. Provide them if necessary and possible.
130 *
131 * Job_Touch Update a target without really updating it.
132 *
133 * Job_Wait Wait for all currently-running jobs to finish.
134 */
135
136 #include <sys/types.h>
137 #include <sys/stat.h>
138 #include <sys/file.h>
139 #include <sys/time.h>
140 #include <sys/wait.h>
141
142 #include <assert.h>
143 #include <errno.h>
144 #ifndef USE_SELECT
145 #include <poll.h>
146 #endif
147 #include <signal.h>
148 #include <stdio.h>
149 #include <string.h>
150 #include <utime.h>
151
152 #include "make.h"
153 #include "hash.h"
154 #include "dir.h"
155 #include "job.h"
156 #include "pathnames.h"
157 #include "trace.h"
158 # define STATIC static
159
160 /*
161 * error handling variables
162 */
163 static int errors = 0; /* number of errors reported */
164 static int aborting = 0; /* why is the make aborting? */
165 #define ABORT_ERROR 1 /* Because of an error */
166 #define ABORT_INTERRUPT 2 /* Because it was interrupted */
167 #define ABORT_WAIT 3 /* Waiting for jobs to finish */
168 #define JOB_TOKENS "+EI+" /* Token to requeue for each abort state */
169
170 /*
171 * this tracks the number of tokens currently "out" to build jobs.
172 */
173 int jobTokensRunning = 0;
174 int not_parallel = 0; /* set if .NOT_PARALLEL */
175
176 /*
177 * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
178 * is a char! So when we go above 127 we turn negative!
179 */
180 #define FILENO(a) ((unsigned) fileno(a))
181
182 /*
183 * post-make command processing. The node postCommands is really just the
184 * .END target but we keep it around to avoid having to search for it
185 * all the time.
186 */
187 static GNode *postCommands = NULL;
188 /* node containing commands to execute when
189 * everything else is done */
190 static int numCommands; /* The number of commands actually printed
191 * for a target. Should this number be
192 * 0, no shell will be executed. */
193
194 /*
195 * Return values from JobStart.
196 */
197 #define JOB_RUNNING 0 /* Job is running */
198 #define JOB_ERROR 1 /* Error in starting the job */
199 #define JOB_FINISHED 2 /* The job is already finished */
200
201 /*
202 * Descriptions for various shells.
203 *
204 * The build environment may set DEFSHELL_INDEX to one of
205 * DEFSHELL_INDEX_SH, DEFSHELL_INDEX_KSH, or DEFSHELL_INDEX_CSH, to
206 * select one of the prefedined shells as the default shell.
207 *
208 * Alternatively, the build environment may set DEFSHELL_CUSTOM to the
209 * name or the full path of a sh-compatible shell, which will be used as
210 * the default shell.
211 *
212 * ".SHELL" lines in Makefiles can choose the default shell from the
213 # set defined here, or add additional shells.
214 */
215
216 #ifdef DEFSHELL_CUSTOM
217 #define DEFSHELL_INDEX_CUSTOM 0
218 #define DEFSHELL_INDEX_SH 1
219 #define DEFSHELL_INDEX_KSH 2
220 #define DEFSHELL_INDEX_CSH 3
221 #else /* !DEFSHELL_CUSTOM */
222 #define DEFSHELL_INDEX_SH 0
223 #define DEFSHELL_INDEX_KSH 1
224 #define DEFSHELL_INDEX_CSH 2
225 #endif /* !DEFSHELL_CUSTOM */
226
227 #ifndef DEFSHELL_INDEX
228 #define DEFSHELL_INDEX 0 /* DEFSHELL_INDEX_CUSTOM or DEFSHELL_INDEX_SH */
229 #endif /* !DEFSHELL_INDEX */
230
231 static Shell shells[] = {
232 #ifdef DEFSHELL_CUSTOM
233 /*
234 * An sh-compatible shell with a non-standard name.
235 *
236 * Keep this in sync with the "sh" description below, but avoid
237 * non-portable features that might not be supplied by all
238 * sh-compatible shells.
239 */
240 {
241 DEFSHELL_CUSTOM,
242 FALSE, "", "", "", 0,
243 FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
244 "",
245 "",
246 },
247 #endif /* DEFSHELL_CUSTOM */
248 /*
249 * SH description. Echo control is also possible and, under
250 * sun UNIX anyway, one can even control error checking.
251 */
252 {
253 "sh",
254 FALSE, "", "", "", 0,
255 FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
256 #if defined(MAKE_NATIVE) && defined(__NetBSD__)
257 "q",
258 #else
259 "",
260 #endif
261 "",
262 },
263 /*
264 * KSH description.
265 */
266 {
267 "ksh",
268 TRUE, "set +v", "set -v", "set +v", 6,
269 FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
270 "v",
271 "",
272 },
273 /*
274 * CSH description. The csh can do echo control by playing
275 * with the setting of the 'echo' shell variable. Sadly,
276 * however, it is unable to do error control nicely.
277 */
278 {
279 "csh",
280 TRUE, "unset verbose", "set verbose", "unset verbose", 10,
281 FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"\n", "", "'\\\n'", '#',
282 "v", "e",
283 },
284 /*
285 * UNKNOWN.
286 */
287 {
288 NULL,
289 FALSE, NULL, NULL, NULL, 0,
290 FALSE, NULL, NULL, NULL, NULL, 0,
291 NULL, NULL,
292 }
293 };
294 static Shell *commandShell = &shells[DEFSHELL_INDEX]; /* this is the shell to
295 * which we pass all
296 * commands in the Makefile.
297 * It is set by the
298 * Job_ParseShell function */
299 const char *shellPath = NULL, /* full pathname of
300 * executable image */
301 *shellName = NULL; /* last component of shell */
302 char *shellErrFlag = NULL;
303 static const char *shellArgv = NULL; /* Custom shell args */
304
305
306 STATIC Job *job_table; /* The structures that describe them */
307 STATIC Job *job_table_end; /* job_table + maxJobs */
308 static int wantToken; /* we want a token */
309 static int lurking_children = 0;
310 static int make_suspended = 0; /* non-zero if we've seen a SIGTSTP (etc) */
311
312 /*
313 * Set of descriptors of pipes connected to
314 * the output channels of children
315 */
316 static struct pollfd *fds = NULL;
317 static Job **jobfds = NULL;
318 static int nfds = 0;
319 static void watchfd(Job *);
320 static void clearfd(Job *);
321 static int readyfd(Job *);
322
323 STATIC GNode *lastNode; /* The node for which output was most recently
324 * produced. */
325 static char *targPrefix = NULL; /* What we print at the start of TARG_FMT */
326 static Job tokenWaitJob; /* token wait pseudo-job */
327
328 static Job childExitJob; /* child exit pseudo-job */
329 #define CHILD_EXIT "."
330 #define DO_JOB_RESUME "R"
331
332 #define TARG_FMT "%s %s ---\n" /* Default format */
333 #define MESSAGE(fp, gn) \
334 if (maxJobs != 1 && targPrefix && *targPrefix) \
335 (void)fprintf(fp, TARG_FMT, targPrefix, gn->name)
336
337 static sigset_t caught_signals; /* Set of signals we handle */
338 #if defined(SYSV)
339 #define KILLPG(pid, sig) kill(-(pid), (sig))
340 #else
341 #define KILLPG(pid, sig) killpg((pid), (sig))
342 #endif
343
344 static void JobChildSig(int);
345 static void JobContinueSig(int);
346 static Job *JobFindPid(int, int, Boolean);
347 static int JobPrintCommand(void *, void *);
348 static int JobSaveCommand(void *, void *);
349 static void JobClose(Job *);
350 static void JobExec(Job *, char **);
351 static void JobMakeArgv(Job *, char **);
352 static int JobStart(GNode *, int);
353 static char *JobOutput(Job *, char *, char *, int);
354 static void JobDoOutput(Job *, Boolean);
355 static Shell *JobMatchShell(const char *);
356 static void JobInterrupt(int, int) MAKE_ATTR_DEAD;
357 static void JobRestartJobs(void);
358 static void JobTokenAdd(void);
359 static void JobSigLock(sigset_t *);
360 static void JobSigUnlock(sigset_t *);
361 static void JobSigReset(void);
362
363 const char *malloc_options="A";
364
365 static void
366 job_table_dump(const char *where)
367 {
368 Job *job;
369
370 fprintf(debug_file, "job table @ %s\n", where);
371 for (job = job_table; job < job_table_end; job++) {
372 fprintf(debug_file, "job %d, status %d, flags %d, pid %d\n",
373 (int)(job - job_table), job->job_state, job->flags, job->pid);
374 }
375 }
376
377 /*
378 * JobSigLock/JobSigUnlock
379 *
380 * Signal lock routines to get exclusive access. Currently used to
381 * protect `jobs' and `stoppedJobs' list manipulations.
382 */
383 static void JobSigLock(sigset_t *omaskp)
384 {
385 if (sigprocmask(SIG_BLOCK, &caught_signals, omaskp) != 0) {
386 Punt("JobSigLock: sigprocmask: %s", strerror(errno));
387 sigemptyset(omaskp);
388 }
389 }
390
391 static void JobSigUnlock(sigset_t *omaskp)
392 {
393 (void)sigprocmask(SIG_SETMASK, omaskp, NULL);
394 }
395
396 static void
397 JobCreatePipe(Job *job, int minfd)
398 {
399 int i, fd, flags;
400
401 if (pipe(job->jobPipe) == -1)
402 Punt("Cannot create pipe: %s", strerror(errno));
403
404 for (i = 0; i < 2; i++) {
405 /* Avoid using low numbered fds */
406 fd = fcntl(job->jobPipe[i], F_DUPFD, minfd);
407 if (fd != -1) {
408 close(job->jobPipe[i]);
409 job->jobPipe[i] = fd;
410 }
411 }
412
413 /* Set close-on-exec flag for both */
414 if (fcntl(job->jobPipe[0], F_SETFD, FD_CLOEXEC) == -1)
415 Punt("Cannot set close-on-exec: %s", strerror(errno));
416 if (fcntl(job->jobPipe[1], F_SETFD, FD_CLOEXEC) == -1)
417 Punt("Cannot set close-on-exec: %s", strerror(errno));
418
419 /*
420 * We mark the input side of the pipe non-blocking; we poll(2) the
421 * pipe when we're waiting for a job token, but we might lose the
422 * race for the token when a new one becomes available, so the read
423 * from the pipe should not block.
424 */
425 flags = fcntl(job->jobPipe[0], F_GETFL, 0);
426 if (flags == -1)
427 Punt("Cannot get flags: %s", strerror(errno));
428 flags |= O_NONBLOCK;
429 if (fcntl(job->jobPipe[0], F_SETFL, flags) == -1)
430 Punt("Cannot set flags: %s", strerror(errno));
431 }
432
433 /*-
434 *-----------------------------------------------------------------------
435 * JobCondPassSig --
436 * Pass a signal to a job
437 *
438 * Input:
439 * signop Signal to send it
440 *
441 * Side Effects:
442 * None, except the job may bite it.
443 *
444 *-----------------------------------------------------------------------
445 */
446 static void
447 JobCondPassSig(int signo)
448 {
449 Job *job;
450
451 if (DEBUG(JOB)) {
452 (void)fprintf(debug_file, "JobCondPassSig(%d) called.\n", signo);
453 }
454
455 for (job = job_table; job < job_table_end; job++) {
456 if (job->job_state != JOB_ST_RUNNING)
457 continue;
458 if (DEBUG(JOB)) {
459 (void)fprintf(debug_file,
460 "JobCondPassSig passing signal %d to child %d.\n",
461 signo, job->pid);
462 }
463 KILLPG(job->pid, signo);
464 }
465 }
466
467 /*-
468 *-----------------------------------------------------------------------
469 * JobChldSig --
470 * SIGCHLD handler.
471 *
472 * Input:
473 * signo The signal number we've received
474 *
475 * Results:
476 * None.
477 *
478 * Side Effects:
479 * Sends a token on the child exit pipe to wake us up from
480 * select()/poll().
481 *
482 *-----------------------------------------------------------------------
483 */
484 static void
485 JobChildSig(int signo MAKE_ATTR_UNUSED)
486 {
487 while (write(childExitJob.outPipe, CHILD_EXIT, 1) == -1 && errno == EAGAIN)
488 continue;
489 }
490
491
492 /*-
493 *-----------------------------------------------------------------------
494 * JobContinueSig --
495 * Resume all stopped jobs.
496 *
497 * Input:
498 * signo The signal number we've received
499 *
500 * Results:
501 * None.
502 *
503 * Side Effects:
504 * Jobs start running again.
505 *
506 *-----------------------------------------------------------------------
507 */
508 static void
509 JobContinueSig(int signo MAKE_ATTR_UNUSED)
510 {
511 /*
512 * Defer sending to SIGCONT to our stopped children until we return
513 * from the signal handler.
514 */
515 while (write(childExitJob.outPipe, DO_JOB_RESUME, 1) == -1 &&
516 errno == EAGAIN)
517 continue;
518 }
519
520 /*-
521 *-----------------------------------------------------------------------
522 * JobPassSig --
523 * Pass a signal on to all jobs, then resend to ourselves.
524 *
525 * Input:
526 * signo The signal number we've received
527 *
528 * Results:
529 * None.
530 *
531 * Side Effects:
532 * We die by the same signal.
533 *
534 *-----------------------------------------------------------------------
535 */
536 MAKE_ATTR_DEAD static void
537 JobPassSig_int(int signo)
538 {
539 /* Run .INTERRUPT target then exit */
540 JobInterrupt(TRUE, signo);
541 }
542
543 MAKE_ATTR_DEAD static void
544 JobPassSig_term(int signo)
545 {
546 /* Dont run .INTERRUPT target then exit */
547 JobInterrupt(FALSE, signo);
548 }
549
550 static void
551 JobPassSig_suspend(int signo)
552 {
553 sigset_t nmask, omask;
554 struct sigaction act;
555
556 /* Suppress job started/continued messages */
557 make_suspended = 1;
558
559 /* Pass the signal onto every job */
560 JobCondPassSig(signo);
561
562 /*
563 * Send ourselves the signal now we've given the message to everyone else.
564 * Note we block everything else possible while we're getting the signal.
565 * This ensures that all our jobs get continued when we wake up before
566 * we take any other signal.
567 */
568 sigfillset(&nmask);
569 sigdelset(&nmask, signo);
570 (void)sigprocmask(SIG_SETMASK, &nmask, &omask);
571
572 act.sa_handler = SIG_DFL;
573 sigemptyset(&act.sa_mask);
574 act.sa_flags = 0;
575 (void)sigaction(signo, &act, NULL);
576
577 if (DEBUG(JOB)) {
578 (void)fprintf(debug_file,
579 "JobPassSig passing signal %d to self.\n", signo);
580 }
581
582 (void)kill(getpid(), signo);
583
584 /*
585 * We've been continued.
586 *
587 * A whole host of signals continue to happen!
588 * SIGCHLD for any processes that actually suspended themselves.
589 * SIGCHLD for any processes that exited while we were alseep.
590 * The SIGCONT that actually caused us to wakeup.
591 *
592 * Since we defer passing the SIGCONT on to our children until
593 * the main processing loop, we can be sure that all the SIGCHLD
594 * events will have happened by then - and that the waitpid() will
595 * collect the child 'suspended' events.
596 * For correct sequencing we just need to ensure we process the
597 * waitpid() before passign on the SIGCONT.
598 *
599 * In any case nothing else is needed here.
600 */
601
602 /* Restore handler and signal mask */
603 act.sa_handler = JobPassSig_suspend;
604 (void)sigaction(signo, &act, NULL);
605 (void)sigprocmask(SIG_SETMASK, &omask, NULL);
606 }
607
608 /*-
609 *-----------------------------------------------------------------------
610 * JobFindPid --
611 * Compare the pid of the job with the given pid and return 0 if they
612 * are equal. This function is called from Job_CatchChildren
613 * to find the job descriptor of the finished job.
614 *
615 * Input:
616 * job job to examine
617 * pid process id desired
618 *
619 * Results:
620 * Job with matching pid
621 *
622 * Side Effects:
623 * None
624 *-----------------------------------------------------------------------
625 */
626 static Job *
627 JobFindPid(int pid, int status, Boolean isJobs)
628 {
629 Job *job;
630
631 for (job = job_table; job < job_table_end; job++) {
632 if ((job->job_state == status) && job->pid == pid)
633 return job;
634 }
635 if (DEBUG(JOB) && isJobs)
636 job_table_dump("no pid");
637 return NULL;
638 }
639
640 /*-
641 *-----------------------------------------------------------------------
642 * JobPrintCommand --
643 * Put out another command for the given job. If the command starts
644 * with an @ or a - we process it specially. In the former case,
645 * so long as the -s and -n flags weren't given to make, we stick
646 * a shell-specific echoOff command in the script. In the latter,
647 * we ignore errors for the entire job, unless the shell has error
648 * control.
649 * If the command is just "..." we take all future commands for this
650 * job to be commands to be executed once the entire graph has been
651 * made and return non-zero to signal that the end of the commands
652 * was reached. These commands are later attached to the postCommands
653 * node and executed by Job_End when all things are done.
654 * This function is called from JobStart via Lst_ForEach.
655 *
656 * Input:
657 * cmdp command string to print
658 * jobp job for which to print it
659 *
660 * Results:
661 * Always 0, unless the command was "..."
662 *
663 * Side Effects:
664 * If the command begins with a '-' and the shell has no error control,
665 * the JOB_IGNERR flag is set in the job descriptor.
666 * If the command is "..." and we're not ignoring such things,
667 * tailCmds is set to the successor node of the cmd.
668 * numCommands is incremented if the command is actually printed.
669 *-----------------------------------------------------------------------
670 */
671 static int
672 JobPrintCommand(void *cmdp, void *jobp)
673 {
674 Boolean noSpecials; /* true if we shouldn't worry about
675 * inserting special commands into
676 * the input stream. */
677 Boolean shutUp = FALSE; /* true if we put a no echo command
678 * into the command file */
679 Boolean errOff = FALSE; /* true if we turned error checking
680 * off before printing the command
681 * and need to turn it back on */
682 const char *cmdTemplate; /* Template to use when printing the
683 * command */
684 char *cmdStart; /* Start of expanded command */
685 char *escCmd = NULL; /* Command with quotes/backticks escaped */
686 char *cmd = (char *)cmdp;
687 Job *job = (Job *)jobp;
688 int i, j;
689
690 noSpecials = NoExecute(job->node);
691
692 if (strcmp(cmd, "...") == 0) {
693 job->node->type |= OP_SAVE_CMDS;
694 if ((job->flags & JOB_IGNDOTS) == 0) {
695 job->tailCmds = Lst_Succ(Lst_Member(job->node->commands,
696 cmd));
697 return 1;
698 }
699 return 0;
700 }
701
702 #define DBPRINTF(fmt, arg) if (DEBUG(JOB)) { \
703 (void)fprintf(debug_file, fmt, arg); \
704 } \
705 (void)fprintf(job->cmdFILE, fmt, arg); \
706 (void)fflush(job->cmdFILE);
707
708 numCommands += 1;
709
710 cmdStart = cmd = Var_Subst(NULL, cmd, job->node, VARF_WANTRES);
711
712 cmdTemplate = "%s\n";
713
714 /*
715 * Check for leading @' and -'s to control echoing and error checking.
716 */
717 while (*cmd == '@' || *cmd == '-' || (*cmd == '+')) {
718 switch (*cmd) {
719 case '@':
720 shutUp = DEBUG(LOUD) ? FALSE : TRUE;
721 break;
722 case '-':
723 errOff = TRUE;
724 break;
725 case '+':
726 if (noSpecials) {
727 /*
728 * We're not actually executing anything...
729 * but this one needs to be - use compat mode just for it.
730 */
731 CompatRunCommand(cmdp, job->node);
732 free(cmdStart);
733 return 0;
734 }
735 break;
736 }
737 cmd++;
738 }
739
740 while (isspace((unsigned char) *cmd))
741 cmd++;
742
743 /*
744 * If the shell doesn't have error control the alternate echo'ing will
745 * be done (to avoid showing additional error checking code)
746 * and this will need the characters '$ ` \ "' escaped
747 */
748
749 if (!commandShell->hasErrCtl) {
750 /* Worst that could happen is every char needs escaping. */
751 escCmd = bmake_malloc((strlen(cmd) * 2) + 1);
752 for (i = 0, j= 0; cmd[i] != '\0'; i++, j++) {
753 if (cmd[i] == '$' || cmd[i] == '`' || cmd[i] == '\\' ||
754 cmd[i] == '"')
755 escCmd[j++] = '\\';
756 escCmd[j] = cmd[i];
757 }
758 escCmd[j] = 0;
759 }
760
761 if (shutUp) {
762 if (!(job->flags & JOB_SILENT) && !noSpecials &&
763 commandShell->hasEchoCtl) {
764 DBPRINTF("%s\n", commandShell->echoOff);
765 } else {
766 if (commandShell->hasErrCtl)
767 shutUp = FALSE;
768 }
769 }
770
771 if (errOff) {
772 if (!noSpecials) {
773 if (commandShell->hasErrCtl) {
774 /*
775 * we don't want the error-control commands showing
776 * up either, so we turn off echoing while executing
777 * them. We could put another field in the shell
778 * structure to tell JobDoOutput to look for this
779 * string too, but why make it any more complex than
780 * it already is?
781 */
782 if (!(job->flags & JOB_SILENT) && !shutUp &&
783 commandShell->hasEchoCtl) {
784 DBPRINTF("%s\n", commandShell->echoOff);
785 DBPRINTF("%s\n", commandShell->ignErr);
786 DBPRINTF("%s\n", commandShell->echoOn);
787 } else {
788 DBPRINTF("%s\n", commandShell->ignErr);
789 }
790 } else if (commandShell->ignErr &&
791 (*commandShell->ignErr != '\0'))
792 {
793 /*
794 * The shell has no error control, so we need to be
795 * weird to get it to ignore any errors from the command.
796 * If echoing is turned on, we turn it off and use the
797 * errCheck template to echo the command. Leave echoing
798 * off so the user doesn't see the weirdness we go through
799 * to ignore errors. Set cmdTemplate to use the weirdness
800 * instead of the simple "%s\n" template.
801 */
802 job->flags |= JOB_IGNERR;
803 if (!(job->flags & JOB_SILENT) && !shutUp) {
804 if (commandShell->hasEchoCtl) {
805 DBPRINTF("%s\n", commandShell->echoOff);
806 }
807 DBPRINTF(commandShell->errCheck, escCmd);
808 shutUp = TRUE;
809 } else {
810 if (!shutUp) {
811 DBPRINTF(commandShell->errCheck, escCmd);
812 }
813 }
814 cmdTemplate = commandShell->ignErr;
815 /*
816 * The error ignoration (hee hee) is already taken care
817 * of by the ignErr template, so pretend error checking
818 * is still on.
819 */
820 errOff = FALSE;
821 } else {
822 errOff = FALSE;
823 }
824 } else {
825 errOff = FALSE;
826 }
827 } else {
828
829 /*
830 * If errors are being checked and the shell doesn't have error control
831 * but does supply an errOut template, then setup commands to run
832 * through it.
833 */
834
835 if (!commandShell->hasErrCtl && commandShell->errOut &&
836 (*commandShell->errOut != '\0')) {
837 if (!(job->flags & JOB_SILENT) && !shutUp) {
838 if (commandShell->hasEchoCtl) {
839 DBPRINTF("%s\n", commandShell->echoOff);
840 }
841 DBPRINTF(commandShell->errCheck, escCmd);
842 shutUp = TRUE;
843 }
844 /* If it's a comment line or blank, treat as an ignored error */
845 if ((escCmd[0] == commandShell->commentChar) ||
846 (escCmd[0] == 0))
847 cmdTemplate = commandShell->ignErr;
848 else
849 cmdTemplate = commandShell->errOut;
850 errOff = FALSE;
851 }
852 }
853
854 if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0 &&
855 (job->flags & JOB_TRACED) == 0) {
856 DBPRINTF("set -%s\n", "x");
857 job->flags |= JOB_TRACED;
858 }
859
860 DBPRINTF(cmdTemplate, cmd);
861 free(cmdStart);
862 free(escCmd);
863 if (errOff) {
864 /*
865 * If echoing is already off, there's no point in issuing the
866 * echoOff command. Otherwise we issue it and pretend it was on
867 * for the whole command...
868 */
869 if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl){
870 DBPRINTF("%s\n", commandShell->echoOff);
871 shutUp = TRUE;
872 }
873 DBPRINTF("%s\n", commandShell->errCheck);
874 }
875 if (shutUp && commandShell->hasEchoCtl) {
876 DBPRINTF("%s\n", commandShell->echoOn);
877 }
878 return 0;
879 }
880
881 /*-
882 *-----------------------------------------------------------------------
883 * JobSaveCommand --
884 * Save a command to be executed when everything else is done.
885 * Callback function for JobFinish...
886 *
887 * Results:
888 * Always returns 0
889 *
890 * Side Effects:
891 * The command is tacked onto the end of postCommands's commands list.
892 *
893 *-----------------------------------------------------------------------
894 */
895 static int
896 JobSaveCommand(void *cmd, void *gn)
897 {
898 cmd = Var_Subst(NULL, (char *)cmd, (GNode *)gn, VARF_WANTRES);
899 (void)Lst_AtEnd(postCommands->commands, cmd);
900 return(0);
901 }
902
903
904 /*-
905 *-----------------------------------------------------------------------
906 * JobClose --
907 * Called to close both input and output pipes when a job is finished.
908 *
909 * Results:
910 * Nada
911 *
912 * Side Effects:
913 * The file descriptors associated with the job are closed.
914 *
915 *-----------------------------------------------------------------------
916 */
917 static void
918 JobClose(Job *job)
919 {
920 clearfd(job);
921 (void)close(job->outPipe);
922 job->outPipe = -1;
923
924 JobDoOutput(job, TRUE);
925 (void)close(job->inPipe);
926 job->inPipe = -1;
927 }
928
929 /*-
930 *-----------------------------------------------------------------------
931 * JobFinish --
932 * Do final processing for the given job including updating
933 * parents and starting new jobs as available/necessary. Note
934 * that we pay no attention to the JOB_IGNERR flag here.
935 * This is because when we're called because of a noexecute flag
936 * or something, jstat.w_status is 0 and when called from
937 * Job_CatchChildren, the status is zeroed if it s/b ignored.
938 *
939 * Input:
940 * job job to finish
941 * status sub-why job went away
942 *
943 * Results:
944 * None
945 *
946 * Side Effects:
947 * Final commands for the job are placed on postCommands.
948 *
949 * If we got an error and are aborting (aborting == ABORT_ERROR) and
950 * the job list is now empty, we are done for the day.
951 * If we recognized an error (errors !=0), we set the aborting flag
952 * to ABORT_ERROR so no more jobs will be started.
953 *-----------------------------------------------------------------------
954 */
955 /*ARGSUSED*/
956 static void
957 JobFinish(Job *job, int status)
958 {
959 Boolean done, return_job_token;
960
961 if (DEBUG(JOB)) {
962 fprintf(debug_file, "Jobfinish: %d [%s], status %d\n",
963 job->pid, job->node->name, status);
964 }
965
966 if ((WIFEXITED(status) &&
967 (((WEXITSTATUS(status) != 0) && !(job->flags & JOB_IGNERR)))) ||
968 WIFSIGNALED(status))
969 {
970 /*
971 * If it exited non-zero and either we're doing things our
972 * way or we're not ignoring errors, the job is finished.
973 * Similarly, if the shell died because of a signal
974 * the job is also finished. In these
975 * cases, finish out the job's output before printing the exit
976 * status...
977 */
978 JobClose(job);
979 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
980 (void)fclose(job->cmdFILE);
981 job->cmdFILE = NULL;
982 }
983 done = TRUE;
984 } else if (WIFEXITED(status)) {
985 /*
986 * Deal with ignored errors in -B mode. We need to print a message
987 * telling of the ignored error as well as setting status.w_status
988 * to 0 so the next command gets run. To do this, we set done to be
989 * TRUE if in -B mode and the job exited non-zero.
990 */
991 done = WEXITSTATUS(status) != 0;
992 /*
993 * Old comment said: "Note we don't
994 * want to close down any of the streams until we know we're at the
995 * end."
996 * But we do. Otherwise when are we going to print the rest of the
997 * stuff?
998 */
999 JobClose(job);
1000 } else {
1001 /*
1002 * No need to close things down or anything.
1003 */
1004 done = FALSE;
1005 }
1006
1007 if (done) {
1008 if (WIFEXITED(status)) {
1009 if (DEBUG(JOB)) {
1010 (void)fprintf(debug_file, "Process %d [%s] exited.\n",
1011 job->pid, job->node->name);
1012 }
1013 if (WEXITSTATUS(status) != 0) {
1014 if (job->node != lastNode) {
1015 MESSAGE(stdout, job->node);
1016 lastNode = job->node;
1017 }
1018 #ifdef USE_META
1019 if (useMeta) {
1020 meta_job_error(job, job->node, job->flags, WEXITSTATUS(status));
1021 }
1022 #endif
1023 (void)printf("*** [%s] Error code %d%s\n",
1024 job->node->name,
1025 WEXITSTATUS(status),
1026 (job->flags & JOB_IGNERR) ? " (ignored)" : "");
1027 if (job->flags & JOB_IGNERR) {
1028 status = 0;
1029 } else {
1030 PrintOnError(job->node, NULL);
1031 }
1032 } else if (DEBUG(JOB)) {
1033 if (job->node != lastNode) {
1034 MESSAGE(stdout, job->node);
1035 lastNode = job->node;
1036 }
1037 (void)printf("*** [%s] Completed successfully\n",
1038 job->node->name);
1039 }
1040 } else {
1041 if (job->node != lastNode) {
1042 MESSAGE(stdout, job->node);
1043 lastNode = job->node;
1044 }
1045 (void)printf("*** [%s] Signal %d\n",
1046 job->node->name, WTERMSIG(status));
1047 }
1048 (void)fflush(stdout);
1049 }
1050
1051 #ifdef USE_META
1052 if (useMeta) {
1053 int x;
1054
1055 if ((x = meta_job_finish(job)) != 0 && status == 0) {
1056 status = x;
1057 }
1058 }
1059 #endif
1060
1061 return_job_token = FALSE;
1062
1063 Trace_Log(JOBEND, job);
1064 if (!(job->flags & JOB_SPECIAL)) {
1065 if ((status != 0) ||
1066 (aborting == ABORT_ERROR) ||
1067 (aborting == ABORT_INTERRUPT))
1068 return_job_token = TRUE;
1069 }
1070
1071 if ((aborting != ABORT_ERROR) && (aborting != ABORT_INTERRUPT) && (status == 0)) {
1072 /*
1073 * As long as we aren't aborting and the job didn't return a non-zero
1074 * status that we shouldn't ignore, we call Make_Update to update
1075 * the parents. In addition, any saved commands for the node are placed
1076 * on the .END target.
1077 */
1078 if (job->tailCmds != NULL) {
1079 Lst_ForEachFrom(job->node->commands, job->tailCmds,
1080 JobSaveCommand,
1081 job->node);
1082 }
1083 job->node->made = MADE;
1084 if (!(job->flags & JOB_SPECIAL))
1085 return_job_token = TRUE;
1086 Make_Update(job->node);
1087 job->job_state = JOB_ST_FREE;
1088 } else if (status != 0) {
1089 errors += 1;
1090 job->job_state = JOB_ST_FREE;
1091 }
1092
1093 /*
1094 * Set aborting if any error.
1095 */
1096 if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
1097 /*
1098 * If we found any errors in this batch of children and the -k flag
1099 * wasn't given, we set the aborting flag so no more jobs get
1100 * started.
1101 */
1102 aborting = ABORT_ERROR;
1103 }
1104
1105 if (return_job_token)
1106 Job_TokenReturn();
1107
1108 if (aborting == ABORT_ERROR && jobTokensRunning == 0) {
1109 /*
1110 * If we are aborting and the job table is now empty, we finish.
1111 */
1112 Finish(errors);
1113 }
1114 }
1115
1116 /*-
1117 *-----------------------------------------------------------------------
1118 * Job_Touch --
1119 * Touch the given target. Called by JobStart when the -t flag was
1120 * given
1121 *
1122 * Input:
1123 * gn the node of the file to touch
1124 * silent TRUE if should not print message
1125 *
1126 * Results:
1127 * None
1128 *
1129 * Side Effects:
1130 * The data modification of the file is changed. In addition, if the
1131 * file did not exist, it is created.
1132 *-----------------------------------------------------------------------
1133 */
1134 void
1135 Job_Touch(GNode *gn, Boolean silent)
1136 {
1137 int streamID; /* ID of stream opened to do the touch */
1138 struct utimbuf times; /* Times for utime() call */
1139
1140 if (gn->type & (OP_JOIN|OP_USE|OP_USEBEFORE|OP_EXEC|OP_OPTIONAL|
1141 OP_SPECIAL|OP_PHONY)) {
1142 /*
1143 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets
1144 * and, as such, shouldn't really be created.
1145 */
1146 return;
1147 }
1148
1149 if (!silent || NoExecute(gn)) {
1150 (void)fprintf(stdout, "touch %s\n", gn->name);
1151 (void)fflush(stdout);
1152 }
1153
1154 if (NoExecute(gn)) {
1155 return;
1156 }
1157
1158 if (gn->type & OP_ARCHV) {
1159 Arch_Touch(gn);
1160 } else if (gn->type & OP_LIB) {
1161 Arch_TouchLib(gn);
1162 } else {
1163 char *file = gn->path ? gn->path : gn->name;
1164
1165 times.actime = times.modtime = now;
1166 if (utime(file, ×) < 0){
1167 streamID = open(file, O_RDWR | O_CREAT, 0666);
1168
1169 if (streamID >= 0) {
1170 char c;
1171
1172 /*
1173 * Read and write a byte to the file to change the
1174 * modification time, then close the file.
1175 */
1176 if (read(streamID, &c, 1) == 1) {
1177 (void)lseek(streamID, (off_t)0, SEEK_SET);
1178 while (write(streamID, &c, 1) == -1 && errno == EAGAIN)
1179 continue;
1180 }
1181
1182 (void)close(streamID);
1183 } else {
1184 (void)fprintf(stdout, "*** couldn't touch %s: %s",
1185 file, strerror(errno));
1186 (void)fflush(stdout);
1187 }
1188 }
1189 }
1190 }
1191
1192 /*-
1193 *-----------------------------------------------------------------------
1194 * Job_CheckCommands --
1195 * Make sure the given node has all the commands it needs.
1196 *
1197 * Input:
1198 * gn The target whose commands need verifying
1199 * abortProc Function to abort with message
1200 *
1201 * Results:
1202 * TRUE if the commands list is/was ok.
1203 *
1204 * Side Effects:
1205 * The node will have commands from the .DEFAULT rule added to it
1206 * if it needs them.
1207 *-----------------------------------------------------------------------
1208 */
1209 Boolean
1210 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1211 {
1212 if (OP_NOP(gn->type) && Lst_IsEmpty(gn->commands) &&
1213 ((gn->type & OP_LIB) == 0 || Lst_IsEmpty(gn->children))) {
1214 /*
1215 * No commands. Look for .DEFAULT rule from which we might infer
1216 * commands
1217 */
1218 if ((DEFAULT != NULL) && !Lst_IsEmpty(DEFAULT->commands) &&
1219 (gn->type & OP_SPECIAL) == 0) {
1220 char *p1;
1221 /*
1222 * Make only looks for a .DEFAULT if the node was never the
1223 * target of an operator, so that's what we do too. If
1224 * a .DEFAULT was given, we substitute its commands for gn's
1225 * commands and set the IMPSRC variable to be the target's name
1226 * The DEFAULT node acts like a transformation rule, in that
1227 * gn also inherits any attributes or sources attached to
1228 * .DEFAULT itself.
1229 */
1230 Make_HandleUse(DEFAULT, gn);
1231 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn, 0);
1232 free(p1);
1233 } else if (Dir_MTime(gn, 0) == 0 && (gn->type & OP_SPECIAL) == 0) {
1234 /*
1235 * The node wasn't the target of an operator we have no .DEFAULT
1236 * rule to go on and the target doesn't already exist. There's
1237 * nothing more we can do for this branch. If the -k flag wasn't
1238 * given, we stop in our tracks, otherwise we just don't update
1239 * this node's parents so they never get examined.
1240 */
1241 static const char msg[] = ": don't know how to make";
1242
1243 if (gn->flags & FROM_DEPEND) {
1244 if (!Job_RunTarget(".STALE", gn->fname))
1245 fprintf(stdout, "%s: %s, %d: ignoring stale %s for %s\n",
1246 progname, gn->fname, gn->lineno, makeDependfile,
1247 gn->name);
1248 return TRUE;
1249 }
1250
1251 if (gn->type & OP_OPTIONAL) {
1252 (void)fprintf(stdout, "%s%s %s (ignored)\n", progname,
1253 msg, gn->name);
1254 (void)fflush(stdout);
1255 } else if (keepgoing) {
1256 (void)fprintf(stdout, "%s%s %s (continuing)\n", progname,
1257 msg, gn->name);
1258 (void)fflush(stdout);
1259 return FALSE;
1260 } else {
1261 (*abortProc)("%s%s %s. Stop", progname, msg, gn->name);
1262 return FALSE;
1263 }
1264 }
1265 }
1266 return TRUE;
1267 }
1268
1269 /*-
1270 *-----------------------------------------------------------------------
1271 * JobExec --
1272 * Execute the shell for the given job. Called from JobStart
1273 *
1274 * Input:
1275 * job Job to execute
1276 *
1277 * Results:
1278 * None.
1279 *
1280 * Side Effects:
1281 * A shell is executed, outputs is altered and the Job structure added
1282 * to the job table.
1283 *
1284 *-----------------------------------------------------------------------
1285 */
1286 static void
1287 JobExec(Job *job, char **argv)
1288 {
1289 int cpid; /* ID of new child */
1290 sigset_t mask;
1291
1292 job->flags &= ~JOB_TRACED;
1293
1294 if (DEBUG(JOB)) {
1295 int i;
1296
1297 (void)fprintf(debug_file, "Running %s %sly\n", job->node->name, "local");
1298 (void)fprintf(debug_file, "\tCommand: ");
1299 for (i = 0; argv[i] != NULL; i++) {
1300 (void)fprintf(debug_file, "%s ", argv[i]);
1301 }
1302 (void)fprintf(debug_file, "\n");
1303 }
1304
1305 /*
1306 * Some jobs produce no output and it's disconcerting to have
1307 * no feedback of their running (since they produce no output, the
1308 * banner with their name in it never appears). This is an attempt to
1309 * provide that feedback, even if nothing follows it.
1310 */
1311 if ((lastNode != job->node) && !(job->flags & JOB_SILENT)) {
1312 MESSAGE(stdout, job->node);
1313 lastNode = job->node;
1314 }
1315
1316 /* No interruptions until this job is on the `jobs' list */
1317 JobSigLock(&mask);
1318
1319 /* Pre-emptively mark job running, pid still zero though */
1320 job->job_state = JOB_ST_RUNNING;
1321
1322 cpid = vFork();
1323 if (cpid == -1)
1324 Punt("Cannot vfork: %s", strerror(errno));
1325
1326 if (cpid == 0) {
1327 /* Child */
1328 sigset_t tmask;
1329
1330 #ifdef USE_META
1331 if (useMeta) {
1332 meta_job_child(job);
1333 }
1334 #endif
1335 /*
1336 * Reset all signal handlers; this is necessary because we also
1337 * need to unblock signals before we exec(2).
1338 */
1339 JobSigReset();
1340
1341 /* Now unblock signals */
1342 sigemptyset(&tmask);
1343 JobSigUnlock(&tmask);
1344
1345 /*
1346 * Must duplicate the input stream down to the child's input and
1347 * reset it to the beginning (again). Since the stream was marked
1348 * close-on-exec, we must clear that bit in the new input.
1349 */
1350 if (dup2(FILENO(job->cmdFILE), 0) == -1) {
1351 execError("dup2", "job->cmdFILE");
1352 _exit(1);
1353 }
1354 if (fcntl(0, F_SETFD, 0) == -1) {
1355 execError("fcntl clear close-on-exec", "stdin");
1356 _exit(1);
1357 }
1358 if (lseek(0, (off_t)0, SEEK_SET) == -1) {
1359 execError("lseek to 0", "stdin");
1360 _exit(1);
1361 }
1362
1363 if (job->node->type & (OP_MAKE | OP_SUBMAKE)) {
1364 /*
1365 * Pass job token pipe to submakes.
1366 */
1367 if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1) {
1368 execError("clear close-on-exec", "tokenWaitJob.inPipe");
1369 _exit(1);
1370 }
1371 if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1) {
1372 execError("clear close-on-exec", "tokenWaitJob.outPipe");
1373 _exit(1);
1374 }
1375 }
1376
1377 /*
1378 * Set up the child's output to be routed through the pipe
1379 * we've created for it.
1380 */
1381 if (dup2(job->outPipe, 1) == -1) {
1382 execError("dup2", "job->outPipe");
1383 _exit(1);
1384 }
1385 /*
1386 * The output channels are marked close on exec. This bit was
1387 * duplicated by the dup2(on some systems), so we have to clear
1388 * it before routing the shell's error output to the same place as
1389 * its standard output.
1390 */
1391 if (fcntl(1, F_SETFD, 0) == -1) {
1392 execError("clear close-on-exec", "stdout");
1393 _exit(1);
1394 }
1395 if (dup2(1, 2) == -1) {
1396 execError("dup2", "1, 2");
1397 _exit(1);
1398 }
1399
1400 /*
1401 * We want to switch the child into a different process family so
1402 * we can kill it and all its descendants in one fell swoop,
1403 * by killing its process family, but not commit suicide.
1404 */
1405 #if defined(MAKE_NATIVE) || defined(HAVE_SETPGID)
1406 #if defined(SYSV)
1407 /* XXX: dsl - I'm sure this should be setpgrp()... */
1408 (void)setsid();
1409 #else
1410 (void)setpgid(0, getpid());
1411 #endif
1412 #endif
1413
1414 Var_ExportVars();
1415
1416 (void)execv(shellPath, argv);
1417 execError("exec", shellPath);
1418 _exit(1);
1419 }
1420
1421 /* Parent, continuing after the child exec */
1422 job->pid = cpid;
1423
1424 Trace_Log(JOBSTART, job);
1425
1426 /*
1427 * Set the current position in the buffer to the beginning
1428 * and mark another stream to watch in the outputs mask
1429 */
1430 job->curPos = 0;
1431
1432 watchfd(job);
1433
1434 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1435 (void)fclose(job->cmdFILE);
1436 job->cmdFILE = NULL;
1437 }
1438
1439 /*
1440 * Now the job is actually running, add it to the table.
1441 */
1442 if (DEBUG(JOB)) {
1443 fprintf(debug_file, "JobExec(%s): pid %d added to jobs table\n",
1444 job->node->name, job->pid);
1445 job_table_dump("job started");
1446 }
1447 JobSigUnlock(&mask);
1448 }
1449
1450 /*-
1451 *-----------------------------------------------------------------------
1452 * JobMakeArgv --
1453 * Create the argv needed to execute the shell for a given job.
1454 *
1455 *
1456 * Results:
1457 *
1458 * Side Effects:
1459 *
1460 *-----------------------------------------------------------------------
1461 */
1462 static void
1463 JobMakeArgv(Job *job, char **argv)
1464 {
1465 int argc;
1466 static char args[10]; /* For merged arguments */
1467
1468 argv[0] = UNCONST(shellName);
1469 argc = 1;
1470
1471 if ((commandShell->exit && (*commandShell->exit != '-')) ||
1472 (commandShell->echo && (*commandShell->echo != '-')))
1473 {
1474 /*
1475 * At least one of the flags doesn't have a minus before it, so
1476 * merge them together. Have to do this because the *(&(@*#*&#$#
1477 * Bourne shell thinks its second argument is a file to source.
1478 * Grrrr. Note the ten-character limitation on the combined arguments.
1479 */
1480 (void)snprintf(args, sizeof(args), "-%s%s",
1481 ((job->flags & JOB_IGNERR) ? "" :
1482 (commandShell->exit ? commandShell->exit : "")),
1483 ((job->flags & JOB_SILENT) ? "" :
1484 (commandShell->echo ? commandShell->echo : "")));
1485
1486 if (args[1]) {
1487 argv[argc] = args;
1488 argc++;
1489 }
1490 } else {
1491 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1492 argv[argc] = UNCONST(commandShell->exit);
1493 argc++;
1494 }
1495 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1496 argv[argc] = UNCONST(commandShell->echo);
1497 argc++;
1498 }
1499 }
1500 argv[argc] = NULL;
1501 }
1502
1503 /*-
1504 *-----------------------------------------------------------------------
1505 * JobStart --
1506 * Start a target-creation process going for the target described
1507 * by the graph node gn.
1508 *
1509 * Input:
1510 * gn target to create
1511 * flags flags for the job to override normal ones.
1512 * e.g. JOB_SPECIAL or JOB_IGNDOTS
1513 * previous The previous Job structure for this node, if any.
1514 *
1515 * Results:
1516 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1517 * if there isn't actually anything left to do for the job and
1518 * JOB_RUNNING if the job has been started.
1519 *
1520 * Side Effects:
1521 * A new Job node is created and added to the list of running
1522 * jobs. PMake is forked and a child shell created.
1523 *
1524 * NB: I'm fairly sure that this code is never called with JOB_SPECIAL set
1525 * JOB_IGNDOTS is never set (dsl)
1526 * Also the return value is ignored by everyone.
1527 *-----------------------------------------------------------------------
1528 */
1529 static int
1530 JobStart(GNode *gn, int flags)
1531 {
1532 Job *job; /* new job descriptor */
1533 char *argv[10]; /* Argument vector to shell */
1534 Boolean cmdsOK; /* true if the nodes commands were all right */
1535 Boolean noExec; /* Set true if we decide not to run the job */
1536 int tfd; /* File descriptor to the temp file */
1537
1538 for (job = job_table; job < job_table_end; job++) {
1539 if (job->job_state == JOB_ST_FREE)
1540 break;
1541 }
1542 if (job >= job_table_end)
1543 Punt("JobStart no job slots vacant");
1544
1545 memset(job, 0, sizeof *job);
1546 job->job_state = JOB_ST_SETUP;
1547 if (gn->type & OP_SPECIAL)
1548 flags |= JOB_SPECIAL;
1549
1550 job->node = gn;
1551 job->tailCmds = NULL;
1552
1553 /*
1554 * Set the initial value of the flags for this job based on the global
1555 * ones and the node's attributes... Any flags supplied by the caller
1556 * are also added to the field.
1557 */
1558 job->flags = 0;
1559 if (Targ_Ignore(gn)) {
1560 job->flags |= JOB_IGNERR;
1561 }
1562 if (Targ_Silent(gn)) {
1563 job->flags |= JOB_SILENT;
1564 }
1565 job->flags |= flags;
1566
1567 /*
1568 * Check the commands now so any attributes from .DEFAULT have a chance
1569 * to migrate to the node
1570 */
1571 cmdsOK = Job_CheckCommands(gn, Error);
1572
1573 job->inPollfd = NULL;
1574 /*
1575 * If the -n flag wasn't given, we open up OUR (not the child's)
1576 * temporary file to stuff commands in it. The thing is rd/wr so we don't
1577 * need to reopen it to feed it to the shell. If the -n flag *was* given,
1578 * we just set the file to be stdout. Cute, huh?
1579 */
1580 if (((gn->type & OP_MAKE) && !(noRecursiveExecute)) ||
1581 (!noExecute && !touchFlag)) {
1582 /*
1583 * tfile is the name of a file into which all shell commands are
1584 * put. It is removed before the child shell is executed, unless
1585 * DEBUG(SCRIPT) is set.
1586 */
1587 char *tfile;
1588 sigset_t mask;
1589 /*
1590 * We're serious here, but if the commands were bogus, we're
1591 * also dead...
1592 */
1593 if (!cmdsOK) {
1594 PrintOnError(gn, NULL); /* provide some clue */
1595 DieHorribly();
1596 }
1597
1598 JobSigLock(&mask);
1599 tfd = mkTempFile(TMPPAT, &tfile);
1600 if (!DEBUG(SCRIPT))
1601 (void)eunlink(tfile);
1602 JobSigUnlock(&mask);
1603
1604 job->cmdFILE = fdopen(tfd, "w+");
1605 if (job->cmdFILE == NULL) {
1606 Punt("Could not fdopen %s", tfile);
1607 }
1608 (void)fcntl(FILENO(job->cmdFILE), F_SETFD, FD_CLOEXEC);
1609 /*
1610 * Send the commands to the command file, flush all its buffers then
1611 * rewind and remove the thing.
1612 */
1613 noExec = FALSE;
1614
1615 #ifdef USE_META
1616 if (useMeta) {
1617 meta_job_start(job, gn);
1618 if (Targ_Silent(gn)) { /* might have changed */
1619 job->flags |= JOB_SILENT;
1620 }
1621 }
1622 #endif
1623 /*
1624 * We can do all the commands at once. hooray for sanity
1625 */
1626 numCommands = 0;
1627 Lst_ForEach(gn->commands, JobPrintCommand, job);
1628
1629 /*
1630 * If we didn't print out any commands to the shell script,
1631 * there's not much point in executing the shell, is there?
1632 */
1633 if (numCommands == 0) {
1634 noExec = TRUE;
1635 }
1636
1637 free(tfile);
1638 } else if (NoExecute(gn)) {
1639 /*
1640 * Not executing anything -- just print all the commands to stdout
1641 * in one fell swoop. This will still set up job->tailCmds correctly.
1642 */
1643 if (lastNode != gn) {
1644 MESSAGE(stdout, gn);
1645 lastNode = gn;
1646 }
1647 job->cmdFILE = stdout;
1648 /*
1649 * Only print the commands if they're ok, but don't die if they're
1650 * not -- just let the user know they're bad and keep going. It
1651 * doesn't do any harm in this case and may do some good.
1652 */
1653 if (cmdsOK) {
1654 Lst_ForEach(gn->commands, JobPrintCommand, job);
1655 }
1656 /*
1657 * Don't execute the shell, thank you.
1658 */
1659 noExec = TRUE;
1660 } else {
1661 /*
1662 * Just touch the target and note that no shell should be executed.
1663 * Set cmdFILE to stdout to make life easier. Check the commands, too,
1664 * but don't die if they're no good -- it does no harm to keep working
1665 * up the graph.
1666 */
1667 job->cmdFILE = stdout;
1668 Job_Touch(gn, job->flags&JOB_SILENT);
1669 noExec = TRUE;
1670 }
1671 /* Just in case it isn't already... */
1672 (void)fflush(job->cmdFILE);
1673
1674 /*
1675 * If we're not supposed to execute a shell, don't.
1676 */
1677 if (noExec) {
1678 if (!(job->flags & JOB_SPECIAL))
1679 Job_TokenReturn();
1680 /*
1681 * Unlink and close the command file if we opened one
1682 */
1683 if (job->cmdFILE != stdout) {
1684 if (job->cmdFILE != NULL) {
1685 (void)fclose(job->cmdFILE);
1686 job->cmdFILE = NULL;
1687 }
1688 }
1689
1690 /*
1691 * We only want to work our way up the graph if we aren't here because
1692 * the commands for the job were no good.
1693 */
1694 if (cmdsOK && aborting == 0) {
1695 if (job->tailCmds != NULL) {
1696 Lst_ForEachFrom(job->node->commands, job->tailCmds,
1697 JobSaveCommand,
1698 job->node);
1699 }
1700 job->node->made = MADE;
1701 Make_Update(job->node);
1702 }
1703 job->job_state = JOB_ST_FREE;
1704 return cmdsOK ? JOB_FINISHED : JOB_ERROR;
1705 }
1706
1707 /*
1708 * Set up the control arguments to the shell. This is based on the flags
1709 * set earlier for this job.
1710 */
1711 JobMakeArgv(job, argv);
1712
1713 /* Create the pipe by which we'll get the shell's output. */
1714 JobCreatePipe(job, 3);
1715
1716 JobExec(job, argv);
1717 return(JOB_RUNNING);
1718 }
1719
1720 static char *
1721 JobOutput(Job *job, char *cp, char *endp, int msg)
1722 {
1723 char *ecp;
1724
1725 if (commandShell->noPrint) {
1726 ecp = Str_FindSubstring(cp, commandShell->noPrint);
1727 while (ecp != NULL) {
1728 if (cp != ecp) {
1729 *ecp = '\0';
1730 if (!beSilent && msg && job->node != lastNode) {
1731 MESSAGE(stdout, job->node);
1732 lastNode = job->node;
1733 }
1734 /*
1735 * The only way there wouldn't be a newline after
1736 * this line is if it were the last in the buffer.
1737 * however, since the non-printable comes after it,
1738 * there must be a newline, so we don't print one.
1739 */
1740 (void)fprintf(stdout, "%s", cp);
1741 (void)fflush(stdout);
1742 }
1743 cp = ecp + commandShell->noPLen;
1744 if (cp != endp) {
1745 /*
1746 * Still more to print, look again after skipping
1747 * the whitespace following the non-printable
1748 * command....
1749 */
1750 cp++;
1751 while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
1752 cp++;
1753 }
1754 ecp = Str_FindSubstring(cp, commandShell->noPrint);
1755 } else {
1756 return cp;
1757 }
1758 }
1759 }
1760 return cp;
1761 }
1762
1763 /*-
1764 *-----------------------------------------------------------------------
1765 * JobDoOutput --
1766 * This function is called at different times depending on
1767 * whether the user has specified that output is to be collected
1768 * via pipes or temporary files. In the former case, we are called
1769 * whenever there is something to read on the pipe. We collect more
1770 * output from the given job and store it in the job's outBuf. If
1771 * this makes up a line, we print it tagged by the job's identifier,
1772 * as necessary.
1773 * If output has been collected in a temporary file, we open the
1774 * file and read it line by line, transfering it to our own
1775 * output channel until the file is empty. At which point we
1776 * remove the temporary file.
1777 * In both cases, however, we keep our figurative eye out for the
1778 * 'noPrint' line for the shell from which the output came. If
1779 * we recognize a line, we don't print it. If the command is not
1780 * alone on the line (the character after it is not \0 or \n), we
1781 * do print whatever follows it.
1782 *
1783 * Input:
1784 * job the job whose output needs printing
1785 * finish TRUE if this is the last time we'll be called
1786 * for this job
1787 *
1788 * Results:
1789 * None
1790 *
1791 * Side Effects:
1792 * curPos may be shifted as may the contents of outBuf.
1793 *-----------------------------------------------------------------------
1794 */
1795 STATIC void
1796 JobDoOutput(Job *job, Boolean finish)
1797 {
1798 Boolean gotNL = FALSE; /* true if got a newline */
1799 Boolean fbuf; /* true if our buffer filled up */
1800 int nr; /* number of bytes read */
1801 int i; /* auxiliary index into outBuf */
1802 int max; /* limit for i (end of current data) */
1803 int nRead; /* (Temporary) number of bytes read */
1804
1805 /*
1806 * Read as many bytes as will fit in the buffer.
1807 */
1808 end_loop:
1809 gotNL = FALSE;
1810 fbuf = FALSE;
1811
1812 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1813 JOB_BUFSIZE - job->curPos);
1814 if (nRead < 0) {
1815 if (errno == EAGAIN)
1816 return;
1817 if (DEBUG(JOB)) {
1818 perror("JobDoOutput(piperead)");
1819 }
1820 nr = 0;
1821 } else {
1822 nr = nRead;
1823 }
1824
1825 /*
1826 * If we hit the end-of-file (the job is dead), we must flush its
1827 * remaining output, so pretend we read a newline if there's any
1828 * output remaining in the buffer.
1829 * Also clear the 'finish' flag so we stop looping.
1830 */
1831 if ((nr == 0) && (job->curPos != 0)) {
1832 job->outBuf[job->curPos] = '\n';
1833 nr = 1;
1834 finish = FALSE;
1835 } else if (nr == 0) {
1836 finish = FALSE;
1837 }
1838
1839 /*
1840 * Look for the last newline in the bytes we just got. If there is
1841 * one, break out of the loop with 'i' as its index and gotNL set
1842 * TRUE.
1843 */
1844 max = job->curPos + nr;
1845 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1846 if (job->outBuf[i] == '\n') {
1847 gotNL = TRUE;
1848 break;
1849 } else if (job->outBuf[i] == '\0') {
1850 /*
1851 * Why?
1852 */
1853 job->outBuf[i] = ' ';
1854 }
1855 }
1856
1857 if (!gotNL) {
1858 job->curPos += nr;
1859 if (job->curPos == JOB_BUFSIZE) {
1860 /*
1861 * If we've run out of buffer space, we have no choice
1862 * but to print the stuff. sigh.
1863 */
1864 fbuf = TRUE;
1865 i = job->curPos;
1866 }
1867 }
1868 if (gotNL || fbuf) {
1869 /*
1870 * Need to send the output to the screen. Null terminate it
1871 * first, overwriting the newline character if there was one.
1872 * So long as the line isn't one we should filter (according
1873 * to the shell description), we print the line, preceded
1874 * by a target banner if this target isn't the same as the
1875 * one for which we last printed something.
1876 * The rest of the data in the buffer are then shifted down
1877 * to the start of the buffer and curPos is set accordingly.
1878 */
1879 job->outBuf[i] = '\0';
1880 if (i >= job->curPos) {
1881 char *cp;
1882
1883 cp = JobOutput(job, job->outBuf, &job->outBuf[i], FALSE);
1884
1885 /*
1886 * There's still more in that thar buffer. This time, though,
1887 * we know there's no newline at the end, so we add one of
1888 * our own free will.
1889 */
1890 if (*cp != '\0') {
1891 if (!beSilent && job->node != lastNode) {
1892 MESSAGE(stdout, job->node);
1893 lastNode = job->node;
1894 }
1895 #ifdef USE_META
1896 if (useMeta) {
1897 meta_job_output(job, cp, gotNL ? "\n" : "");
1898 }
1899 #endif
1900 (void)fprintf(stdout, "%s%s", cp, gotNL ? "\n" : "");
1901 (void)fflush(stdout);
1902 }
1903 }
1904 /*
1905 * max is the last offset still in the buffer. Move any remaining
1906 * characters to the start of the buffer and update the end marker
1907 * curPos.
1908 */
1909 if (i < max) {
1910 (void)memmove(job->outBuf, &job->outBuf[i + 1], max - (i + 1));
1911 job->curPos = max - (i + 1);
1912 } else {
1913 assert(i == max);
1914 job->curPos = 0;
1915 }
1916 }
1917 if (finish) {
1918 /*
1919 * If the finish flag is true, we must loop until we hit
1920 * end-of-file on the pipe. This is guaranteed to happen
1921 * eventually since the other end of the pipe is now closed
1922 * (we closed it explicitly and the child has exited). When
1923 * we do get an EOF, finish will be set FALSE and we'll fall
1924 * through and out.
1925 */
1926 goto end_loop;
1927 }
1928 }
1929
1930 static void
1931 JobRun(GNode *targ)
1932 {
1933 #ifdef notyet
1934 /*
1935 * Unfortunately it is too complicated to run .BEGIN, .END,
1936 * and .INTERRUPT job in the parallel job module. This has
1937 * the nice side effect that it avoids a lot of other problems.
1938 */
1939 Lst lst = Lst_Init(FALSE);
1940 Lst_AtEnd(lst, targ);
1941 (void)Make_Run(lst);
1942 Lst_Destroy(lst, NULL);
1943 JobStart(targ, JOB_SPECIAL);
1944 while (jobTokensRunning) {
1945 Job_CatchOutput();
1946 }
1947 #else
1948 Compat_Make(targ, targ);
1949 if (targ->made == ERROR) {
1950 PrintOnError(targ, "\n\nStop.");
1951 exit(1);
1952 }
1953 #endif
1954 }
1955
1956 /*-
1957 *-----------------------------------------------------------------------
1958 * Job_CatchChildren --
1959 * Handle the exit of a child. Called from Make_Make.
1960 *
1961 * Input:
1962 * block TRUE if should block on the wait
1963 *
1964 * Results:
1965 * none.
1966 *
1967 * Side Effects:
1968 * The job descriptor is removed from the list of children.
1969 *
1970 * Notes:
1971 * We do waits, blocking or not, according to the wisdom of our
1972 * caller, until there are no more children to report. For each
1973 * job, call JobFinish to finish things off.
1974 *
1975 *-----------------------------------------------------------------------
1976 */
1977
1978 void
1979 Job_CatchChildren(void)
1980 {
1981 int pid; /* pid of dead child */
1982 int status; /* Exit/termination status */
1983
1984 /*
1985 * Don't even bother if we know there's no one around.
1986 */
1987 if (jobTokensRunning == 0)
1988 return;
1989
1990 while ((pid = waitpid((pid_t) -1, &status, WNOHANG | WUNTRACED)) > 0) {
1991 if (DEBUG(JOB)) {
1992 (void)fprintf(debug_file, "Process %d exited/stopped status %x.\n", pid,
1993 status);
1994 }
1995 JobReapChild(pid, status, TRUE);
1996 }
1997 }
1998
1999 /*
2000 * It is possible that wait[pid]() was called from elsewhere,
2001 * this lets us reap jobs regardless.
2002 */
2003 void
2004 JobReapChild(pid_t pid, int status, Boolean isJobs)
2005 {
2006 Job *job; /* job descriptor for dead child */
2007
2008 /*
2009 * Don't even bother if we know there's no one around.
2010 */
2011 if (jobTokensRunning == 0)
2012 return;
2013
2014 job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
2015 if (job == NULL) {
2016 if (isJobs) {
2017 if (!lurking_children)
2018 Error("Child (%d) status %x not in table?", pid, status);
2019 }
2020 return; /* not ours */
2021 }
2022 if (WIFSTOPPED(status)) {
2023 if (DEBUG(JOB)) {
2024 (void)fprintf(debug_file, "Process %d (%s) stopped.\n",
2025 job->pid, job->node->name);
2026 }
2027 if (!make_suspended) {
2028 switch (WSTOPSIG(status)) {
2029 case SIGTSTP:
2030 (void)printf("*** [%s] Suspended\n", job->node->name);
2031 break;
2032 case SIGSTOP:
2033 (void)printf("*** [%s] Stopped\n", job->node->name);
2034 break;
2035 default:
2036 (void)printf("*** [%s] Stopped -- signal %d\n",
2037 job->node->name, WSTOPSIG(status));
2038 }
2039 job->job_suspended = 1;
2040 }
2041 (void)fflush(stdout);
2042 return;
2043 }
2044
2045 job->job_state = JOB_ST_FINISHED;
2046 job->exit_status = status;
2047
2048 JobFinish(job, status);
2049 }
2050
2051 /*-
2052 *-----------------------------------------------------------------------
2053 * Job_CatchOutput --
2054 * Catch the output from our children, if we're using
2055 * pipes do so. Otherwise just block time until we get a
2056 * signal(most likely a SIGCHLD) since there's no point in
2057 * just spinning when there's nothing to do and the reaping
2058 * of a child can wait for a while.
2059 *
2060 * Results:
2061 * None
2062 *
2063 * Side Effects:
2064 * Output is read from pipes if we're piping.
2065 * -----------------------------------------------------------------------
2066 */
2067 void
2068 Job_CatchOutput(void)
2069 {
2070 int nready;
2071 Job *job;
2072 int i;
2073
2074 (void)fflush(stdout);
2075
2076 /* The first fd in the list is the job token pipe */
2077 do {
2078 nready = poll(fds + 1 - wantToken, nfds - 1 + wantToken, POLL_MSEC);
2079 } while (nready < 0 && errno == EINTR);
2080
2081 if (nready < 0)
2082 Punt("poll: %s", strerror(errno));
2083
2084 if (nready > 0 && readyfd(&childExitJob)) {
2085 char token = 0;
2086 ssize_t count;
2087 count = read(childExitJob.inPipe, &token, 1);
2088 switch (count) {
2089 case 0:
2090 Punt("unexpected eof on token pipe");
2091 case -1:
2092 Punt("token pipe read: %s", strerror(errno));
2093 case 1:
2094 if (token == DO_JOB_RESUME[0])
2095 /* Complete relay requested from our SIGCONT handler */
2096 JobRestartJobs();
2097 break;
2098 default:
2099 abort();
2100 }
2101 --nready;
2102 }
2103
2104 Job_CatchChildren();
2105 if (nready == 0)
2106 return;
2107
2108 for (i = 2; i < nfds; i++) {
2109 if (!fds[i].revents)
2110 continue;
2111 job = jobfds[i];
2112 if (job->job_state == JOB_ST_RUNNING)
2113 JobDoOutput(job, FALSE);
2114 if (--nready == 0)
2115 return;
2116 }
2117 }
2118
2119 /*-
2120 *-----------------------------------------------------------------------
2121 * Job_Make --
2122 * Start the creation of a target. Basically a front-end for
2123 * JobStart used by the Make module.
2124 *
2125 * Results:
2126 * None.
2127 *
2128 * Side Effects:
2129 * Another job is started.
2130 *
2131 *-----------------------------------------------------------------------
2132 */
2133 void
2134 Job_Make(GNode *gn)
2135 {
2136 (void)JobStart(gn, 0);
2137 }
2138
2139 void
2140 Shell_Init(void)
2141 {
2142 if (shellPath == NULL) {
2143 /*
2144 * We are using the default shell, which may be an absolute
2145 * path if DEFSHELL_CUSTOM is defined.
2146 */
2147 shellName = commandShell->name;
2148 #ifdef DEFSHELL_CUSTOM
2149 if (*shellName == '/') {
2150 shellPath = shellName;
2151 shellName = strrchr(shellPath, '/');
2152 shellName++;
2153 } else
2154 #endif
2155 shellPath = str_concat(_PATH_DEFSHELLDIR, shellName, STR_ADDSLASH);
2156 }
2157 if (commandShell->exit == NULL) {
2158 commandShell->exit = "";
2159 }
2160 if (commandShell->echo == NULL) {
2161 commandShell->echo = "";
2162 }
2163 if (commandShell->hasErrCtl && *commandShell->exit) {
2164 if (shellErrFlag &&
2165 strcmp(commandShell->exit, &shellErrFlag[1]) != 0) {
2166 free(shellErrFlag);
2167 shellErrFlag = NULL;
2168 }
2169 if (!shellErrFlag) {
2170 int n = strlen(commandShell->exit) + 2;
2171
2172 shellErrFlag = bmake_malloc(n);
2173 if (shellErrFlag) {
2174 snprintf(shellErrFlag, n, "-%s", commandShell->exit);
2175 }
2176 }
2177 } else if (shellErrFlag) {
2178 free(shellErrFlag);
2179 shellErrFlag = NULL;
2180 }
2181 }
2182
2183 /*-
2184 * Returns the string literal that is used in the current command shell
2185 * to produce a newline character.
2186 */
2187 const char *
2188 Shell_GetNewline(void)
2189 {
2190
2191 return commandShell->newline;
2192 }
2193
2194 void
2195 Job_SetPrefix(void)
2196 {
2197
2198 if (targPrefix) {
2199 free(targPrefix);
2200 } else if (!Var_Exists(MAKE_JOB_PREFIX, VAR_GLOBAL)) {
2201 Var_Set(MAKE_JOB_PREFIX, "---", VAR_GLOBAL, 0);
2202 }
2203
2204 targPrefix = Var_Subst(NULL, "${" MAKE_JOB_PREFIX "}",
2205 VAR_GLOBAL, VARF_WANTRES);
2206 }
2207
2208 /*-
2209 *-----------------------------------------------------------------------
2210 * Job_Init --
2211 * Initialize the process module
2212 *
2213 * Input:
2214 *
2215 * Results:
2216 * none
2217 *
2218 * Side Effects:
2219 * lists and counters are initialized
2220 *-----------------------------------------------------------------------
2221 */
2222 void
2223 Job_Init(void)
2224 {
2225 Job_SetPrefix();
2226 /* Allocate space for all the job info */
2227 job_table = bmake_malloc(maxJobs * sizeof *job_table);
2228 memset(job_table, 0, maxJobs * sizeof *job_table);
2229 job_table_end = job_table + maxJobs;
2230 wantToken = 0;
2231
2232 aborting = 0;
2233 errors = 0;
2234
2235 lastNode = NULL;
2236
2237 /*
2238 * There is a non-zero chance that we already have children.
2239 * eg after 'make -f- <<EOF'
2240 * Since their termination causes a 'Child (pid) not in table' message,
2241 * Collect the status of any that are already dead, and suppress the
2242 * error message if there are any undead ones.
2243 */
2244 for (;;) {
2245 int rval, status;
2246 rval = waitpid((pid_t) -1, &status, WNOHANG);
2247 if (rval > 0)
2248 continue;
2249 if (rval == 0)
2250 lurking_children = 1;
2251 break;
2252 }
2253
2254 Shell_Init();
2255
2256 JobCreatePipe(&childExitJob, 3);
2257
2258 /* We can only need to wait for tokens, children and output from each job */
2259 fds = bmake_malloc(sizeof (*fds) * (2 + maxJobs));
2260 jobfds = bmake_malloc(sizeof (*jobfds) * (2 + maxJobs));
2261
2262 /* These are permanent entries and take slots 0 and 1 */
2263 watchfd(&tokenWaitJob);
2264 watchfd(&childExitJob);
2265
2266 sigemptyset(&caught_signals);
2267 /*
2268 * Install a SIGCHLD handler.
2269 */
2270 (void)bmake_signal(SIGCHLD, JobChildSig);
2271 sigaddset(&caught_signals, SIGCHLD);
2272
2273 #define ADDSIG(s,h) \
2274 if (bmake_signal(s, SIG_IGN) != SIG_IGN) { \
2275 sigaddset(&caught_signals, s); \
2276 (void)bmake_signal(s, h); \
2277 }
2278
2279 /*
2280 * Catch the four signals that POSIX specifies if they aren't ignored.
2281 * JobPassSig will take care of calling JobInterrupt if appropriate.
2282 */
2283 ADDSIG(SIGINT, JobPassSig_int)
2284 ADDSIG(SIGHUP, JobPassSig_term)
2285 ADDSIG(SIGTERM, JobPassSig_term)
2286 ADDSIG(SIGQUIT, JobPassSig_term)
2287
2288 /*
2289 * There are additional signals that need to be caught and passed if
2290 * either the export system wants to be told directly of signals or if
2291 * we're giving each job its own process group (since then it won't get
2292 * signals from the terminal driver as we own the terminal)
2293 */
2294 ADDSIG(SIGTSTP, JobPassSig_suspend)
2295 ADDSIG(SIGTTOU, JobPassSig_suspend)
2296 ADDSIG(SIGTTIN, JobPassSig_suspend)
2297 ADDSIG(SIGWINCH, JobCondPassSig)
2298 ADDSIG(SIGCONT, JobContinueSig)
2299 #undef ADDSIG
2300
2301 (void)Job_RunTarget(".BEGIN", NULL);
2302 postCommands = Targ_FindNode(".END", TARG_CREATE);
2303 }
2304
2305 static void JobSigReset(void)
2306 {
2307 #define DELSIG(s) \
2308 if (sigismember(&caught_signals, s)) { \
2309 (void)bmake_signal(s, SIG_DFL); \
2310 }
2311
2312 DELSIG(SIGINT)
2313 DELSIG(SIGHUP)
2314 DELSIG(SIGQUIT)
2315 DELSIG(SIGTERM)
2316 DELSIG(SIGTSTP)
2317 DELSIG(SIGTTOU)
2318 DELSIG(SIGTTIN)
2319 DELSIG(SIGWINCH)
2320 DELSIG(SIGCONT)
2321 #undef DELSIG
2322 (void)bmake_signal(SIGCHLD, SIG_DFL);
2323 }
2324
2325 /*-
2326 *-----------------------------------------------------------------------
2327 * JobMatchShell --
2328 * Find a shell in 'shells' given its name.
2329 *
2330 * Results:
2331 * A pointer to the Shell structure.
2332 *
2333 * Side Effects:
2334 * None.
2335 *
2336 *-----------------------------------------------------------------------
2337 */
2338 static Shell *
2339 JobMatchShell(const char *name)
2340 {
2341 Shell *sh;
2342
2343 for (sh = shells; sh->name != NULL; sh++) {
2344 if (strcmp(name, sh->name) == 0)
2345 return (sh);
2346 }
2347 return NULL;
2348 }
2349
2350 /*-
2351 *-----------------------------------------------------------------------
2352 * Job_ParseShell --
2353 * Parse a shell specification and set up commandShell, shellPath
2354 * and shellName appropriately.
2355 *
2356 * Input:
2357 * line The shell spec
2358 *
2359 * Results:
2360 * FAILURE if the specification was incorrect.
2361 *
2362 * Side Effects:
2363 * commandShell points to a Shell structure (either predefined or
2364 * created from the shell spec), shellPath is the full path of the
2365 * shell described by commandShell, while shellName is just the
2366 * final component of shellPath.
2367 *
2368 * Notes:
2369 * A shell specification consists of a .SHELL target, with dependency
2370 * operator, followed by a series of blank-separated words. Double
2371 * quotes can be used to use blanks in words. A backslash escapes
2372 * anything (most notably a double-quote and a space) and
2373 * provides the functionality it does in C. Each word consists of
2374 * keyword and value separated by an equal sign. There should be no
2375 * unnecessary spaces in the word. The keywords are as follows:
2376 * name Name of shell.
2377 * path Location of shell.
2378 * quiet Command to turn off echoing.
2379 * echo Command to turn echoing on
2380 * filter Result of turning off echoing that shouldn't be
2381 * printed.
2382 * echoFlag Flag to turn echoing on at the start
2383 * errFlag Flag to turn error checking on at the start
2384 * hasErrCtl True if shell has error checking control
2385 * newline String literal to represent a newline char
2386 * check Command to turn on error checking if hasErrCtl
2387 * is TRUE or template of command to echo a command
2388 * for which error checking is off if hasErrCtl is
2389 * FALSE.
2390 * ignore Command to turn off error checking if hasErrCtl
2391 * is TRUE or template of command to execute a
2392 * command so as to ignore any errors it returns if
2393 * hasErrCtl is FALSE.
2394 *
2395 *-----------------------------------------------------------------------
2396 */
2397 ReturnStatus
2398 Job_ParseShell(char *line)
2399 {
2400 char **words;
2401 char **argv;
2402 int argc;
2403 char *path;
2404 Shell newShell;
2405 Boolean fullSpec = FALSE;
2406 Shell *sh;
2407
2408 while (isspace((unsigned char)*line)) {
2409 line++;
2410 }
2411
2412 free(UNCONST(shellArgv));
2413
2414 memset(&newShell, 0, sizeof(newShell));
2415
2416 /*
2417 * Parse the specification by keyword
2418 */
2419 words = brk_string(line, &argc, TRUE, &path);
2420 if (words == NULL) {
2421 Error("Unterminated quoted string [%s]", line);
2422 return FAILURE;
2423 }
2424 shellArgv = path;
2425
2426 for (path = NULL, argv = words; argc != 0; argc--, argv++) {
2427 if (strncmp(*argv, "path=", 5) == 0) {
2428 path = &argv[0][5];
2429 } else if (strncmp(*argv, "name=", 5) == 0) {
2430 newShell.name = &argv[0][5];
2431 } else {
2432 if (strncmp(*argv, "quiet=", 6) == 0) {
2433 newShell.echoOff = &argv[0][6];
2434 } else if (strncmp(*argv, "echo=", 5) == 0) {
2435 newShell.echoOn = &argv[0][5];
2436 } else if (strncmp(*argv, "filter=", 7) == 0) {
2437 newShell.noPrint = &argv[0][7];
2438 newShell.noPLen = strlen(newShell.noPrint);
2439 } else if (strncmp(*argv, "echoFlag=", 9) == 0) {
2440 newShell.echo = &argv[0][9];
2441 } else if (strncmp(*argv, "errFlag=", 8) == 0) {
2442 newShell.exit = &argv[0][8];
2443 } else if (strncmp(*argv, "hasErrCtl=", 10) == 0) {
2444 char c = argv[0][10];
2445 newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
2446 (c != 'T') && (c != 't'));
2447 } else if (strncmp(*argv, "newline=", 8) == 0) {
2448 newShell.newline = &argv[0][8];
2449 } else if (strncmp(*argv, "check=", 6) == 0) {
2450 newShell.errCheck = &argv[0][6];
2451 } else if (strncmp(*argv, "ignore=", 7) == 0) {
2452 newShell.ignErr = &argv[0][7];
2453 } else if (strncmp(*argv, "errout=", 7) == 0) {
2454 newShell.errOut = &argv[0][7];
2455 } else if (strncmp(*argv, "comment=", 8) == 0) {
2456 newShell.commentChar = argv[0][8];
2457 } else {
2458 Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"",
2459 *argv);
2460 free(words);
2461 return(FAILURE);
2462 }
2463 fullSpec = TRUE;
2464 }
2465 }
2466
2467 if (path == NULL) {
2468 /*
2469 * If no path was given, the user wants one of the pre-defined shells,
2470 * yes? So we find the one s/he wants with the help of JobMatchShell
2471 * and set things up the right way. shellPath will be set up by
2472 * Shell_Init.
2473 */
2474 if (newShell.name == NULL) {
2475 Parse_Error(PARSE_FATAL, "Neither path nor name specified");
2476 free(words);
2477 return(FAILURE);
2478 } else {
2479 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2480 Parse_Error(PARSE_WARNING, "%s: No matching shell",
2481 newShell.name);
2482 free(words);
2483 return(FAILURE);
2484 }
2485 commandShell = sh;
2486 shellName = newShell.name;
2487 if (shellPath) {
2488 /* Shell_Init has already been called! Do it again. */
2489 free(UNCONST(shellPath));
2490 shellPath = NULL;
2491 Shell_Init();
2492 }
2493 }
2494 } else {
2495 /*
2496 * The user provided a path. If s/he gave nothing else (fullSpec is
2497 * FALSE), try and find a matching shell in the ones we know of.
2498 * Else we just take the specification at its word and copy it
2499 * to a new location. In either case, we need to record the
2500 * path the user gave for the shell.
2501 */
2502 shellPath = path;
2503 path = strrchr(path, '/');
2504 if (path == NULL) {
2505 path = UNCONST(shellPath);
2506 } else {
2507 path += 1;
2508 }
2509 if (newShell.name != NULL) {
2510 shellName = newShell.name;
2511 } else {
2512 shellName = path;
2513 }
2514 if (!fullSpec) {
2515 if ((sh = JobMatchShell(shellName)) == NULL) {
2516 Parse_Error(PARSE_WARNING, "%s: No matching shell",
2517 shellName);
2518 free(words);
2519 return(FAILURE);
2520 }
2521 commandShell = sh;
2522 } else {
2523 commandShell = bmake_malloc(sizeof(Shell));
2524 *commandShell = newShell;
2525 }
2526 /* this will take care of shellErrFlag */
2527 Shell_Init();
2528 }
2529
2530 if (commandShell->echoOn && commandShell->echoOff) {
2531 commandShell->hasEchoCtl = TRUE;
2532 }
2533
2534 if (!commandShell->hasErrCtl) {
2535 if (commandShell->errCheck == NULL) {
2536 commandShell->errCheck = "";
2537 }
2538 if (commandShell->ignErr == NULL) {
2539 commandShell->ignErr = "%s\n";
2540 }
2541 }
2542
2543 /*
2544 * Do not free up the words themselves, since they might be in use by the
2545 * shell specification.
2546 */
2547 free(words);
2548 return SUCCESS;
2549 }
2550
2551 /*-
2552 *-----------------------------------------------------------------------
2553 * JobInterrupt --
2554 * Handle the receipt of an interrupt.
2555 *
2556 * Input:
2557 * runINTERRUPT Non-zero if commands for the .INTERRUPT target
2558 * should be executed
2559 * signo signal received
2560 *
2561 * Results:
2562 * None
2563 *
2564 * Side Effects:
2565 * All children are killed. Another job will be started if the
2566 * .INTERRUPT target was given.
2567 *-----------------------------------------------------------------------
2568 */
2569 static void
2570 JobInterrupt(int runINTERRUPT, int signo)
2571 {
2572 Job *job; /* job descriptor in that element */
2573 GNode *interrupt; /* the node describing the .INTERRUPT target */
2574 sigset_t mask;
2575 GNode *gn;
2576
2577 aborting = ABORT_INTERRUPT;
2578
2579 JobSigLock(&mask);
2580
2581 for (job = job_table; job < job_table_end; job++) {
2582 if (job->job_state != JOB_ST_RUNNING)
2583 continue;
2584
2585 gn = job->node;
2586
2587 if ((gn->type & (OP_JOIN|OP_PHONY)) == 0 && !Targ_Precious(gn)) {
2588 char *file = (gn->path == NULL ? gn->name : gn->path);
2589 if (!noExecute && eunlink(file) != -1) {
2590 Error("*** %s removed", file);
2591 }
2592 }
2593 if (job->pid) {
2594 if (DEBUG(JOB)) {
2595 (void)fprintf(debug_file,
2596 "JobInterrupt passing signal %d to child %d.\n",
2597 signo, job->pid);
2598 }
2599 KILLPG(job->pid, signo);
2600 }
2601 }
2602
2603 JobSigUnlock(&mask);
2604
2605 if (runINTERRUPT && !touchFlag) {
2606 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2607 if (interrupt != NULL) {
2608 ignoreErrors = FALSE;
2609 JobRun(interrupt);
2610 }
2611 }
2612 Trace_Log(MAKEINTR, 0);
2613 exit(signo);
2614 }
2615
2616 /*
2617 *-----------------------------------------------------------------------
2618 * Job_Finish --
2619 * Do final processing such as the running of the commands
2620 * attached to the .END target.
2621 *
2622 * Results:
2623 * Number of errors reported.
2624 *
2625 * Side Effects:
2626 * None.
2627 *-----------------------------------------------------------------------
2628 */
2629 int
2630 Job_Finish(void)
2631 {
2632 if (postCommands != NULL &&
2633 (!Lst_IsEmpty(postCommands->commands) ||
2634 !Lst_IsEmpty(postCommands->children))) {
2635 if (errors) {
2636 Error("Errors reported so .END ignored");
2637 } else {
2638 JobRun(postCommands);
2639 }
2640 }
2641 return(errors);
2642 }
2643
2644 /*-
2645 *-----------------------------------------------------------------------
2646 * Job_End --
2647 * Cleanup any memory used by the jobs module
2648 *
2649 * Results:
2650 * None.
2651 *
2652 * Side Effects:
2653 * Memory is freed
2654 *-----------------------------------------------------------------------
2655 */
2656 void
2657 Job_End(void)
2658 {
2659 #ifdef CLEANUP
2660 free(shellArgv);
2661 #endif
2662 }
2663
2664 /*-
2665 *-----------------------------------------------------------------------
2666 * Job_Wait --
2667 * Waits for all running jobs to finish and returns. Sets 'aborting'
2668 * to ABORT_WAIT to prevent other jobs from starting.
2669 *
2670 * Results:
2671 * None.
2672 *
2673 * Side Effects:
2674 * Currently running jobs finish.
2675 *
2676 *-----------------------------------------------------------------------
2677 */
2678 void
2679 Job_Wait(void)
2680 {
2681 aborting = ABORT_WAIT;
2682 while (jobTokensRunning != 0) {
2683 Job_CatchOutput();
2684 }
2685 aborting = 0;
2686 }
2687
2688 /*-
2689 *-----------------------------------------------------------------------
2690 * Job_AbortAll --
2691 * Abort all currently running jobs without handling output or anything.
2692 * This function is to be called only in the event of a major
2693 * error. Most definitely NOT to be called from JobInterrupt.
2694 *
2695 * Results:
2696 * None
2697 *
2698 * Side Effects:
2699 * All children are killed, not just the firstborn
2700 *-----------------------------------------------------------------------
2701 */
2702 void
2703 Job_AbortAll(void)
2704 {
2705 Job *job; /* the job descriptor in that element */
2706 int foo;
2707
2708 aborting = ABORT_ERROR;
2709
2710 if (jobTokensRunning) {
2711 for (job = job_table; job < job_table_end; job++) {
2712 if (job->job_state != JOB_ST_RUNNING)
2713 continue;
2714 /*
2715 * kill the child process with increasingly drastic signals to make
2716 * darn sure it's dead.
2717 */
2718 KILLPG(job->pid, SIGINT);
2719 KILLPG(job->pid, SIGKILL);
2720 }
2721 }
2722
2723 /*
2724 * Catch as many children as want to report in at first, then give up
2725 */
2726 while (waitpid((pid_t) -1, &foo, WNOHANG) > 0)
2727 continue;
2728 }
2729
2730
2731 /*-
2733 *-----------------------------------------------------------------------
2734 * JobRestartJobs --
2735 * Tries to restart stopped jobs if there are slots available.
2736 * Called in process context in response to a SIGCONT.
2737 *
2738 * Results:
2739 * None.
2740 *
2741 * Side Effects:
2742 * Resumes jobs.
2743 *
2744 *-----------------------------------------------------------------------
2745 */
2746 static void
2747 JobRestartJobs(void)
2748 {
2749 Job *job;
2750
2751 for (job = job_table; job < job_table_end; job++) {
2752 if (job->job_state == JOB_ST_RUNNING &&
2753 (make_suspended || job->job_suspended)) {
2754 if (DEBUG(JOB)) {
2755 (void)fprintf(debug_file, "Restarting stopped job pid %d.\n",
2756 job->pid);
2757 }
2758 if (job->job_suspended) {
2759 (void)printf("*** [%s] Continued\n", job->node->name);
2760 (void)fflush(stdout);
2761 }
2762 job->job_suspended = 0;
2763 if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
2764 fprintf(debug_file, "Failed to send SIGCONT to %d\n", job->pid);
2765 }
2766 }
2767 if (job->job_state == JOB_ST_FINISHED)
2768 /* Job exit deferred after calling waitpid() in a signal handler */
2769 JobFinish(job, job->exit_status);
2770 }
2771 make_suspended = 0;
2772 }
2773
2774 static void
2775 watchfd(Job *job)
2776 {
2777 if (job->inPollfd != NULL)
2778 Punt("Watching watched job");
2779
2780 fds[nfds].fd = job->inPipe;
2781 fds[nfds].events = POLLIN;
2782 jobfds[nfds] = job;
2783 job->inPollfd = &fds[nfds];
2784 nfds++;
2785 }
2786
2787 static void
2788 clearfd(Job *job)
2789 {
2790 int i;
2791 if (job->inPollfd == NULL)
2792 Punt("Unwatching unwatched job");
2793 i = job->inPollfd - fds;
2794 nfds--;
2795 /*
2796 * Move last job in table into hole made by dead job.
2797 */
2798 if (nfds != i) {
2799 fds[i] = fds[nfds];
2800 jobfds[i] = jobfds[nfds];
2801 jobfds[i]->inPollfd = &fds[i];
2802 }
2803 job->inPollfd = NULL;
2804 }
2805
2806 static int
2807 readyfd(Job *job)
2808 {
2809 if (job->inPollfd == NULL)
2810 Punt("Polling unwatched job");
2811 return (job->inPollfd->revents & POLLIN) != 0;
2812 }
2813
2814 /*-
2815 *-----------------------------------------------------------------------
2816 * JobTokenAdd --
2817 * Put a token into the job pipe so that some make process can start
2818 * another job.
2819 *
2820 * Side Effects:
2821 * Allows more build jobs to be spawned somewhere.
2822 *
2823 *-----------------------------------------------------------------------
2824 */
2825
2826 static void
2827 JobTokenAdd(void)
2828 {
2829 char tok = JOB_TOKENS[aborting], tok1;
2830
2831 /* If we are depositing an error token flush everything else */
2832 while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2833 continue;
2834
2835 if (DEBUG(JOB))
2836 fprintf(debug_file, "(%d) aborting %d, deposit token %c\n",
2837 getpid(), aborting, JOB_TOKENS[aborting]);
2838 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2839 continue;
2840 }
2841
2842 /*-
2843 *-----------------------------------------------------------------------
2844 * Job_ServerStartTokenAdd --
2845 * Prep the job token pipe in the root make process.
2846 *
2847 *-----------------------------------------------------------------------
2848 */
2849
2850 void
2851 Job_ServerStart(int max_tokens, int jp_0, int jp_1)
2852 {
2853 int i;
2854 char jobarg[64];
2855
2856 if (jp_0 >= 0 && jp_1 >= 0) {
2857 /* Pipe passed in from parent */
2858 tokenWaitJob.inPipe = jp_0;
2859 tokenWaitJob.outPipe = jp_1;
2860 (void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
2861 (void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
2862 return;
2863 }
2864
2865 JobCreatePipe(&tokenWaitJob, 15);
2866
2867 snprintf(jobarg, sizeof(jobarg), "%d,%d",
2868 tokenWaitJob.inPipe, tokenWaitJob.outPipe);
2869
2870 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
2871 Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
2872
2873 /*
2874 * Preload the job pipe with one token per job, save the one
2875 * "extra" token for the primary job.
2876 *
2877 * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
2878 * larger than the write buffer size of the pipe, we will
2879 * deadlock here.
2880 */
2881 for (i = 1; i < max_tokens; i++)
2882 JobTokenAdd();
2883 }
2884
2885 /*-
2886 *-----------------------------------------------------------------------
2887 * Job_TokenReturn --
2888 * Return a withdrawn token to the pool.
2889 *
2890 *-----------------------------------------------------------------------
2891 */
2892
2893 void
2894 Job_TokenReturn(void)
2895 {
2896 jobTokensRunning--;
2897 if (jobTokensRunning < 0)
2898 Punt("token botch");
2899 if (jobTokensRunning || JOB_TOKENS[aborting] != '+')
2900 JobTokenAdd();
2901 }
2902
2903 /*-
2904 *-----------------------------------------------------------------------
2905 * Job_TokenWithdraw --
2906 * Attempt to withdraw a token from the pool.
2907 *
2908 * Results:
2909 * Returns TRUE if a token was withdrawn, and FALSE if the pool
2910 * is currently empty.
2911 *
2912 * Side Effects:
2913 * If pool is empty, set wantToken so that we wake up
2914 * when a token is released.
2915 *
2916 *-----------------------------------------------------------------------
2917 */
2918
2919
2920 Boolean
2921 Job_TokenWithdraw(void)
2922 {
2923 char tok, tok1;
2924 int count;
2925
2926 wantToken = 0;
2927 if (DEBUG(JOB))
2928 fprintf(debug_file, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
2929 getpid(), aborting, jobTokensRunning);
2930
2931 if (aborting || (jobTokensRunning >= maxJobs))
2932 return FALSE;
2933
2934 count = read(tokenWaitJob.inPipe, &tok, 1);
2935 if (count == 0)
2936 Fatal("eof on job pipe!");
2937 if (count < 0 && jobTokensRunning != 0) {
2938 if (errno != EAGAIN) {
2939 Fatal("job pipe read: %s", strerror(errno));
2940 }
2941 if (DEBUG(JOB))
2942 fprintf(debug_file, "(%d) blocked for token\n", getpid());
2943 wantToken = 1;
2944 return FALSE;
2945 }
2946
2947 if (count == 1 && tok != '+') {
2948 /* make being abvorted - remove any other job tokens */
2949 if (DEBUG(JOB))
2950 fprintf(debug_file, "(%d) aborted by token %c\n", getpid(), tok);
2951 while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2952 continue;
2953 /* And put the stopper back */
2954 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2955 continue;
2956 Fatal("A failure has been detected in another branch of the parallel make");
2957 }
2958
2959 if (count == 1 && jobTokensRunning == 0)
2960 /* We didn't want the token really */
2961 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2962 continue;
2963
2964 jobTokensRunning++;
2965 if (DEBUG(JOB))
2966 fprintf(debug_file, "(%d) withdrew token\n", getpid());
2967 return TRUE;
2968 }
2969
2970 /*-
2971 *-----------------------------------------------------------------------
2972 * Job_RunTarget --
2973 * Run the named target if found. If a filename is specified, then
2974 * set that to the sources.
2975 *
2976 * Results:
2977 * None
2978 *
2979 * Side Effects:
2980 * exits if the target fails.
2981 *
2982 *-----------------------------------------------------------------------
2983 */
2984 Boolean
2985 Job_RunTarget(const char *target, const char *fname) {
2986 GNode *gn = Targ_FindNode(target, TARG_NOCREATE);
2987
2988 if (gn == NULL)
2989 return FALSE;
2990
2991 if (fname)
2992 Var_Set(ALLSRC, fname, gn, 0);
2993
2994 JobRun(gn);
2995 if (gn->made == ERROR) {
2996 PrintOnError(gn, "\n\nStop.");
2997 exit(1);
2998 }
2999 return TRUE;
3000 }
3001
3002 #ifdef USE_SELECT
3003 int
3004 emul_poll(struct pollfd *fd, int nfd, int timeout)
3005 {
3006 fd_set rfds, wfds;
3007 int i, maxfd, nselect, npoll;
3008 struct timeval tv, *tvp;
3009 long usecs;
3010
3011 FD_ZERO(&rfds);
3012 FD_ZERO(&wfds);
3013
3014 maxfd = -1;
3015 for (i = 0; i < nfd; i++) {
3016 fd[i].revents = 0;
3017
3018 if (fd[i].events & POLLIN)
3019 FD_SET(fd[i].fd, &rfds);
3020
3021 if (fd[i].events & POLLOUT)
3022 FD_SET(fd[i].fd, &wfds);
3023
3024 if (fd[i].fd > maxfd)
3025 maxfd = fd[i].fd;
3026 }
3027
3028 if (maxfd >= FD_SETSIZE) {
3029 Punt("Ran out of fd_set slots; "
3030 "recompile with a larger FD_SETSIZE.");
3031 }
3032
3033 if (timeout < 0) {
3034 tvp = NULL;
3035 } else {
3036 usecs = timeout * 1000;
3037 tv.tv_sec = usecs / 1000000;
3038 tv.tv_usec = usecs % 1000000;
3039 tvp = &tv;
3040 }
3041
3042 nselect = select(maxfd + 1, &rfds, &wfds, 0, tvp);
3043
3044 if (nselect <= 0)
3045 return nselect;
3046
3047 npoll = 0;
3048 for (i = 0; i < nfd; i++) {
3049 if (FD_ISSET(fd[i].fd, &rfds))
3050 fd[i].revents |= POLLIN;
3051
3052 if (FD_ISSET(fd[i].fd, &wfds))
3053 fd[i].revents |= POLLOUT;
3054
3055 if (fd[i].revents)
3056 npoll++;
3057 }
3058
3059 return npoll;
3060 }
3061 #endif /* USE_SELECT */
3062