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