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