job.c revision 1.366 1 /* $NetBSD: job.c,v 1.366 2020/12/11 00:29:01 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.366 2020/12/11 00:29:01 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 *const job, const char *const escCmd,
809 Boolean const run, CommandFlags *const inout_cmdFlags,
810 const char **const inout_cmdTemplate)
811 {
812 if (!run)
813 inout_cmdFlags->ignerr = FALSE;
814 else if (shell->hasErrCtl)
815 JobPrintSpecialsErrCtl(job, inout_cmdFlags->echo);
816 else if (shell->runIgnTmpl != NULL && shell->runIgnTmpl[0] != '\0') {
817 JobPrintSpecialsEchoCtl(job, inout_cmdFlags, escCmd,
818 inout_cmdTemplate);
819 } else
820 inout_cmdFlags->ignerr = FALSE;
821 }
822
823 /*
824 * Put out another command for the given job.
825 *
826 * If the command starts with '@' and neither the -s nor the -n flag was
827 * given to make, we stick a shell-specific echoOff command in the script.
828 *
829 * If the command starts with '-' and the shell has no error control (none
830 * of the predefined shells has that), we ignore errors for the entire job.
831 * XXX: Why ignore errors for the entire job?
832 * XXX: Even ignore errors for the commands before this command?
833 *
834 * If the command is just "...", all further commands of this job are skipped
835 * for now. They are attached to the .END node and will be run by Job_Finish
836 * after all other targets have been made.
837 */
838 static void
839 JobPrintCommand(Job *job, const char * const ucmd)
840 {
841 Boolean run;
842
843 CommandFlags cmdFlags;
844 /* Template for printing a command to the shell file */
845 const char *cmdTemplate;
846 char *xcmd; /* The expanded command */
847 char *xcmdStart;
848 char *escCmd; /* xcmd escaped to be used in double quotes */
849
850 run = GNode_ShouldExecute(job->node);
851
852 Var_Subst(ucmd, job->node, VARE_WANTRES, &xcmd);
853 /* TODO: handle errors */
854 xcmdStart = xcmd;
855
856 cmdTemplate = "%s\n";
857
858 ParseRunOptions(&xcmd, &cmdFlags);
859
860 /* The '+' command flag overrides the -n or -N options. */
861 if (cmdFlags.always && !run) {
862 /*
863 * We're not actually executing anything...
864 * but this one needs to be - use compat mode just for it.
865 */
866 Compat_RunCommand(ucmd, job->node);
867 free(xcmdStart);
868 return;
869 }
870
871 /*
872 * If the shell doesn't have error control, the alternate echoing
873 * will be done (to avoid showing additional error checking code)
874 * and this needs some characters escaped.
875 */
876 escCmd = shell->hasErrCtl ? NULL : EscapeShellDblQuot(xcmd);
877
878 if (!cmdFlags.echo) {
879 if (job->echo && run && shell->hasEchoCtl) {
880 JobPrintln(job, shell->echoOff);
881 } else {
882 if (shell->hasErrCtl)
883 cmdFlags.echo = TRUE;
884 }
885 }
886
887 if (cmdFlags.ignerr) {
888 JobPrintSpecials(job, escCmd, run, &cmdFlags, &cmdTemplate);
889 } else {
890
891 /*
892 * If errors are being checked and the shell doesn't have
893 * error control but does supply an runChkTmpl template, then
894 * set up commands to run through it.
895 */
896
897 if (!shell->hasErrCtl && shell->runChkTmpl &&
898 shell->runChkTmpl[0] != '\0') {
899 if (job->echo && cmdFlags.echo) {
900 if (shell->hasEchoCtl)
901 JobPrintln(job, shell->echoOff);
902 JobPrintf(job, shell->echoTmpl, escCmd);
903 cmdFlags.echo = FALSE;
904 }
905 /*
906 * If it's a comment line or blank, treat as an
907 * ignored error.
908 */
909 if (escCmd[0] == shell->commentChar ||
910 (escCmd[0] == '\0'))
911 cmdTemplate = shell->runIgnTmpl;
912 else
913 cmdTemplate = shell->runChkTmpl;
914 cmdFlags.ignerr = FALSE;
915 }
916 }
917
918 if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0 && !job->xtraced) {
919 JobPrintln(job, "set -x");
920 job->xtraced = TRUE;
921 }
922
923 JobPrintf(job, cmdTemplate, xcmd);
924 free(xcmdStart);
925 free(escCmd);
926 if (cmdFlags.ignerr) {
927 /*
928 * If echoing is already off, there's no point in issuing the
929 * echoOff command. Otherwise we issue it and pretend it was on
930 * for the whole command...
931 */
932 if (cmdFlags.echo && job->echo && shell->hasEchoCtl) {
933 JobPrintln(job, shell->echoOff);
934 cmdFlags.echo = FALSE;
935 }
936 JobPrintln(job, shell->errOn);
937 }
938 if (!cmdFlags.echo && shell->hasEchoCtl)
939 JobPrintln(job, shell->echoOn);
940 }
941
942 /*
943 * Print all commands to the shell file that is later executed.
944 *
945 * The special command "..." stops printing and saves the remaining commands
946 * to be executed later.
947 *
948 * Return whether at least one command was written to the shell file.
949 */
950 static Boolean
951 JobPrintCommands(Job *job)
952 {
953 StringListNode *ln;
954 Boolean seen = FALSE;
955
956 for (ln = job->node->commands.first; ln != NULL; ln = ln->next) {
957 const char *cmd = ln->datum;
958
959 if (strcmp(cmd, "...") == 0) {
960 job->node->type |= OP_SAVE_CMDS;
961 job->tailCmds = ln->next;
962 break;
963 }
964
965 JobPrintCommand(job, ln->datum);
966 seen = TRUE;
967 }
968
969 return seen;
970 }
971
972 /* Save the delayed commands, to be executed when everything else is done. */
973 static void
974 JobSaveCommands(Job *job)
975 {
976 StringListNode *ln;
977
978 for (ln = job->tailCmds; ln != NULL; ln = ln->next) {
979 const char *cmd = ln->datum;
980 char *expanded_cmd;
981 /* XXX: This Var_Subst is only intended to expand the dynamic
982 * variables such as .TARGET, .IMPSRC. It is not intended to
983 * expand the other variables as well; see deptgt-end.mk. */
984 (void)Var_Subst(cmd, job->node, VARE_WANTRES, &expanded_cmd);
985 /* TODO: handle errors */
986 Lst_Append(&Targ_GetEndNode()->commands, expanded_cmd);
987 }
988 }
989
990
991 /* Called to close both input and output pipes when a job is finished. */
992 static void
993 JobClosePipes(Job *job)
994 {
995 clearfd(job);
996 (void)close(job->outPipe);
997 job->outPipe = -1;
998
999 JobDoOutput(job, TRUE);
1000 (void)close(job->inPipe);
1001 job->inPipe = -1;
1002 }
1003
1004 /*
1005 * Do final processing for the given job including updating parent nodes and
1006 * starting new jobs as available/necessary.
1007 *
1008 * Deferred commands for the job are placed on the .END node.
1009 *
1010 * If there was a serious error (job_errors != 0; not an ignored one), no more
1011 * jobs will be started.
1012 *
1013 * Input:
1014 * job job to finish
1015 * status sub-why job went away
1016 */
1017 static void
1018 JobFinish(Job *job, int status)
1019 {
1020 Boolean done, return_job_token;
1021
1022 DEBUG3(JOB, "JobFinish: %d [%s], status %d\n",
1023 job->pid, job->node->name, status);
1024
1025 if ((WIFEXITED(status) &&
1026 ((WEXITSTATUS(status) != 0 && !job->ignerr))) ||
1027 WIFSIGNALED(status)) {
1028 /*
1029 * If it exited non-zero and either we're doing things our
1030 * way or we're not ignoring errors, the job is finished.
1031 * Similarly, if the shell died because of a signal
1032 * the job is also finished. In these
1033 * cases, finish out the job's output before printing the exit
1034 * status...
1035 */
1036 JobClosePipes(job);
1037 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1038 (void)fclose(job->cmdFILE);
1039 job->cmdFILE = NULL;
1040 }
1041 done = TRUE;
1042 } else if (WIFEXITED(status)) {
1043 /*
1044 * Deal with ignored errors in -B mode. We need to print a
1045 * message telling of the ignored error as well as to run
1046 * the next command.
1047 */
1048 done = WEXITSTATUS(status) != 0;
1049 JobClosePipes(job);
1050 } else {
1051 /*
1052 * No need to close things down or anything.
1053 */
1054 done = FALSE;
1055 }
1056
1057 if (done) {
1058 if (WIFEXITED(status)) {
1059 DEBUG2(JOB, "Process %d [%s] exited.\n",
1060 job->pid, job->node->name);
1061 if (WEXITSTATUS(status) != 0) {
1062 SwitchOutputTo(job->node);
1063 #ifdef USE_META
1064 if (useMeta) {
1065 meta_job_error(job, job->node,
1066 job->ignerr, WEXITSTATUS(status));
1067 }
1068 #endif
1069 if (!shouldDieQuietly(job->node, -1))
1070 (void)printf(
1071 "*** [%s] Error code %d%s\n",
1072 job->node->name,
1073 WEXITSTATUS(status),
1074 job->ignerr ? " (ignored)" : "");
1075 if (job->ignerr) {
1076 status = 0;
1077 } else {
1078 if (deleteOnError) {
1079 JobDeleteTarget(job->node);
1080 }
1081 PrintOnError(job->node, NULL);
1082 }
1083 } else if (DEBUG(JOB)) {
1084 SwitchOutputTo(job->node);
1085 (void)printf(
1086 "*** [%s] Completed successfully\n",
1087 job->node->name);
1088 }
1089 } else {
1090 SwitchOutputTo(job->node);
1091 (void)printf("*** [%s] Signal %d\n",
1092 job->node->name, WTERMSIG(status));
1093 if (deleteOnError) {
1094 JobDeleteTarget(job->node);
1095 }
1096 }
1097 (void)fflush(stdout);
1098 }
1099
1100 #ifdef USE_META
1101 if (useMeta) {
1102 int meta_status = meta_job_finish(job);
1103 if (meta_status != 0 && status == 0)
1104 status = meta_status;
1105 }
1106 #endif
1107
1108 return_job_token = FALSE;
1109
1110 Trace_Log(JOBEND, job);
1111 if (!job->special) {
1112 if (status != 0 ||
1113 (aborting == ABORT_ERROR) || aborting == ABORT_INTERRUPT)
1114 return_job_token = TRUE;
1115 }
1116
1117 if (aborting != ABORT_ERROR && aborting != ABORT_INTERRUPT &&
1118 (status == 0)) {
1119 /*
1120 * As long as we aren't aborting and the job didn't return a
1121 * non-zero status that we shouldn't ignore, we call
1122 * Make_Update to update the parents.
1123 */
1124 JobSaveCommands(job);
1125 job->node->made = MADE;
1126 if (!job->special)
1127 return_job_token = TRUE;
1128 Make_Update(job->node);
1129 job->status = JOB_ST_FREE;
1130 } else if (status != 0) {
1131 job_errors++;
1132 job->status = JOB_ST_FREE;
1133 }
1134
1135 if (job_errors > 0 && !opts.keepgoing && aborting != ABORT_INTERRUPT) {
1136 /* Prevent more jobs from getting started. */
1137 aborting = ABORT_ERROR;
1138 }
1139
1140 if (return_job_token)
1141 Job_TokenReturn();
1142
1143 if (aborting == ABORT_ERROR && jobTokensRunning == 0)
1144 Finish(job_errors);
1145 }
1146
1147 static void
1148 TouchRegular(GNode *gn)
1149 {
1150 const char *file = GNode_Path(gn);
1151 struct utimbuf times = { now, now };
1152 int fd;
1153 char c;
1154
1155 if (utime(file, ×) >= 0)
1156 return;
1157
1158 fd = open(file, O_RDWR | O_CREAT, 0666);
1159 if (fd < 0) {
1160 (void)fprintf(stderr, "*** couldn't touch %s: %s\n",
1161 file, strerror(errno));
1162 (void)fflush(stderr);
1163 return; /* XXX: What about propagating the error? */
1164 }
1165
1166 /* Last resort: update the file's time stamps in the traditional way.
1167 * XXX: This doesn't work for empty files, which are sometimes used
1168 * as marker files. */
1169 if (read(fd, &c, 1) == 1) {
1170 (void)lseek(fd, 0, SEEK_SET);
1171 while (write(fd, &c, 1) == -1 && errno == EAGAIN)
1172 continue;
1173 }
1174 (void)close(fd); /* XXX: What about propagating the error? */
1175 }
1176
1177 /* Touch the given target. Called by JobStart when the -t flag was given.
1178 *
1179 * The modification date of the file is changed.
1180 * If the file did not exist, it is created. */
1181 void
1182 Job_Touch(GNode *gn, Boolean echo)
1183 {
1184 if (gn->type &
1185 (OP_JOIN | OP_USE | OP_USEBEFORE | OP_EXEC | OP_OPTIONAL |
1186 OP_SPECIAL | OP_PHONY)) {
1187 /*
1188 * These are "virtual" targets and should not really be
1189 * created.
1190 */
1191 return;
1192 }
1193
1194 if (echo || !GNode_ShouldExecute(gn)) {
1195 (void)fprintf(stdout, "touch %s\n", gn->name);
1196 (void)fflush(stdout);
1197 }
1198
1199 if (!GNode_ShouldExecute(gn))
1200 return;
1201
1202 if (gn->type & OP_ARCHV) {
1203 Arch_Touch(gn);
1204 return;
1205 }
1206
1207 if (gn->type & OP_LIB) {
1208 Arch_TouchLib(gn);
1209 return;
1210 }
1211
1212 TouchRegular(gn);
1213 }
1214
1215 /* Make sure the given node has all the commands it needs.
1216 *
1217 * The node will have commands from the .DEFAULT rule added to it if it
1218 * needs them.
1219 *
1220 * Input:
1221 * gn The target whose commands need verifying
1222 * abortProc Function to abort with message
1223 *
1224 * Results:
1225 * TRUE if the commands list is/was ok.
1226 */
1227 Boolean
1228 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1229 {
1230 if (GNode_IsTarget(gn))
1231 return TRUE;
1232 if (!Lst_IsEmpty(&gn->commands))
1233 return TRUE;
1234 if ((gn->type & OP_LIB) && !Lst_IsEmpty(&gn->children))
1235 return TRUE;
1236
1237 /*
1238 * No commands. Look for .DEFAULT rule from which we might infer
1239 * commands.
1240 */
1241 if (defaultNode != NULL && !Lst_IsEmpty(&defaultNode->commands) &&
1242 !(gn->type & OP_SPECIAL)) {
1243 /*
1244 * The traditional Make only looks for a .DEFAULT if the node
1245 * was never the target of an operator, so that's what we do
1246 * too.
1247 *
1248 * The .DEFAULT node acts like a transformation rule, in that
1249 * gn also inherits any attributes or sources attached to
1250 * .DEFAULT itself.
1251 */
1252 Make_HandleUse(defaultNode, gn);
1253 Var_Set(IMPSRC, GNode_VarTarget(gn), gn);
1254 return TRUE;
1255 }
1256
1257 Dir_UpdateMTime(gn, FALSE);
1258 if (gn->mtime != 0 || (gn->type & OP_SPECIAL))
1259 return TRUE;
1260
1261 /*
1262 * The node wasn't the target of an operator. We have no .DEFAULT
1263 * rule to go on and the target doesn't already exist. There's
1264 * nothing more we can do for this branch. If the -k flag wasn't
1265 * given, we stop in our tracks, otherwise we just don't update
1266 * this node's parents so they never get examined.
1267 */
1268
1269 if (gn->flags & FROM_DEPEND) {
1270 if (!Job_RunTarget(".STALE", gn->fname))
1271 fprintf(stdout,
1272 "%s: %s, %d: ignoring stale %s for %s\n",
1273 progname, gn->fname, gn->lineno, makeDependfile,
1274 gn->name);
1275 return TRUE;
1276 }
1277
1278 if (gn->type & OP_OPTIONAL) {
1279 (void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
1280 progname, gn->name, "ignored");
1281 (void)fflush(stdout);
1282 return TRUE;
1283 }
1284
1285 if (opts.keepgoing) {
1286 (void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
1287 progname, gn->name, "continuing");
1288 (void)fflush(stdout);
1289 return FALSE;
1290 }
1291
1292 abortProc("%s: don't know how to make %s. Stop", progname, gn->name);
1293 return FALSE;
1294 }
1295
1296 /* Execute the shell for the given job.
1297 *
1298 * See Job_CatchOutput for handling the output of the shell. */
1299 static void
1300 JobExec(Job *job, char **argv)
1301 {
1302 int cpid; /* ID of new child */
1303 sigset_t mask;
1304
1305 job->xtraced = FALSE;
1306
1307 if (DEBUG(JOB)) {
1308 int i;
1309
1310 debug_printf("Running %s\n", job->node->name);
1311 debug_printf("\tCommand: ");
1312 for (i = 0; argv[i] != NULL; i++) {
1313 debug_printf("%s ", argv[i]);
1314 }
1315 debug_printf("\n");
1316 }
1317
1318 /*
1319 * Some jobs produce no output and it's disconcerting to have
1320 * no feedback of their running (since they produce no output, the
1321 * banner with their name in it never appears). This is an attempt to
1322 * provide that feedback, even if nothing follows it.
1323 */
1324 if (job->echo)
1325 SwitchOutputTo(job->node);
1326
1327 /* No interruptions until this job is on the `jobs' list */
1328 JobSigLock(&mask);
1329
1330 /* Pre-emptively mark job running, pid still zero though */
1331 job->status = JOB_ST_RUNNING;
1332
1333 cpid = vFork();
1334 if (cpid == -1)
1335 Punt("Cannot vfork: %s", strerror(errno));
1336
1337 if (cpid == 0) {
1338 /* Child */
1339 sigset_t tmask;
1340
1341 #ifdef USE_META
1342 if (useMeta) {
1343 meta_job_child(job);
1344 }
1345 #endif
1346 /*
1347 * Reset all signal handlers; this is necessary because we
1348 * also need to unblock signals before we exec(2).
1349 */
1350 JobSigReset();
1351
1352 /* Now unblock signals */
1353 sigemptyset(&tmask);
1354 JobSigUnlock(&tmask);
1355
1356 /*
1357 * Must duplicate the input stream down to the child's input
1358 * and reset it to the beginning (again). Since the stream
1359 * was marked close-on-exec, we must clear that bit in the
1360 * new input.
1361 */
1362 if (dup2(fileno(job->cmdFILE), 0) == -1)
1363 execDie("dup2", "job->cmdFILE");
1364 if (fcntl(0, F_SETFD, 0) == -1)
1365 execDie("fcntl clear close-on-exec", "stdin");
1366 if (lseek(0, 0, SEEK_SET) == -1)
1367 execDie("lseek to 0", "stdin");
1368
1369 if (job->node->type & (OP_MAKE | OP_SUBMAKE)) {
1370 /*
1371 * Pass job token pipe to submakes.
1372 */
1373 if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1)
1374 execDie("clear close-on-exec",
1375 "tokenWaitJob.inPipe");
1376 if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1)
1377 execDie("clear close-on-exec",
1378 "tokenWaitJob.outPipe");
1379 }
1380
1381 /*
1382 * Set up the child's output to be routed through the pipe
1383 * we've created for it.
1384 */
1385 if (dup2(job->outPipe, 1) == -1)
1386 execDie("dup2", "job->outPipe");
1387
1388 /*
1389 * The output channels are marked close on exec. This bit
1390 * was duplicated by the dup2(on some systems), so we have
1391 * to clear it before routing the shell's error output to
1392 * the same place as its standard output.
1393 */
1394 if (fcntl(1, F_SETFD, 0) == -1)
1395 execDie("clear close-on-exec", "stdout");
1396 if (dup2(1, 2) == -1)
1397 execDie("dup2", "1, 2");
1398
1399 /*
1400 * We want to switch the child into a different process
1401 * family so we can kill it and all its descendants in
1402 * one fell swoop, by killing its process family, but not
1403 * commit suicide.
1404 */
1405 #if defined(MAKE_NATIVE) || defined(HAVE_SETPGID)
1406 # if defined(SYSV)
1407 /* XXX: dsl - I'm sure this should be setpgrp()... */
1408 (void)setsid();
1409 # else
1410 (void)setpgid(0, getpid());
1411 # endif
1412 #endif
1413
1414 Var_ExportVars();
1415
1416 (void)execv(shellPath, argv);
1417 execDie("exec", shellPath);
1418 }
1419
1420 /* Parent, continuing after the child exec */
1421 job->pid = cpid;
1422
1423 Trace_Log(JOBSTART, job);
1424
1425 #ifdef USE_META
1426 if (useMeta) {
1427 meta_job_parent(job, cpid);
1428 }
1429 #endif
1430
1431 /*
1432 * Set the current position in the buffer to the beginning
1433 * and mark another stream to watch in the outputs mask
1434 */
1435 job->curPos = 0;
1436
1437 watchfd(job);
1438
1439 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1440 (void)fclose(job->cmdFILE);
1441 job->cmdFILE = NULL;
1442 }
1443
1444 /*
1445 * Now the job is actually running, add it to the table.
1446 */
1447 if (DEBUG(JOB)) {
1448 debug_printf("JobExec(%s): pid %d added to jobs table\n",
1449 job->node->name, job->pid);
1450 job_table_dump("job started");
1451 }
1452 JobSigUnlock(&mask);
1453 }
1454
1455 /* Create the argv needed to execute the shell for a given job. */
1456 static void
1457 JobMakeArgv(Job *job, char **argv)
1458 {
1459 int argc;
1460 static char args[10]; /* For merged arguments */
1461
1462 argv[0] = UNCONST(shellName);
1463 argc = 1;
1464
1465 if ((shell->exitFlag != NULL && shell->exitFlag[0] != '-') ||
1466 (shell->echoFlag != NULL && shell->echoFlag[0] != '-')) {
1467 /*
1468 * At least one of the flags doesn't have a minus before it,
1469 * so merge them together. Have to do this because the Bourne
1470 * shell thinks its second argument is a file to source.
1471 * Grrrr. Note the ten-character limitation on the combined
1472 * arguments.
1473 *
1474 * TODO: Research until when the above comments were
1475 * practically relevant.
1476 */
1477 (void)snprintf(args, sizeof args, "-%s%s",
1478 (job->ignerr ? "" :
1479 (shell->exitFlag != NULL ? shell->exitFlag : "")),
1480 (!job->echo ? "" :
1481 (shell->echoFlag != NULL ? shell->echoFlag : "")));
1482
1483 if (args[1]) {
1484 argv[argc] = args;
1485 argc++;
1486 }
1487 } else {
1488 if (!job->ignerr && shell->exitFlag) {
1489 argv[argc] = UNCONST(shell->exitFlag);
1490 argc++;
1491 }
1492 if (job->echo && shell->echoFlag) {
1493 argv[argc] = UNCONST(shell->echoFlag);
1494 argc++;
1495 }
1496 }
1497 argv[argc] = NULL;
1498 }
1499
1500 static void
1501 JobOpenTmpFile(Job *job, GNode *gn, Boolean cmdsOK, Boolean *out_run)
1502 {
1503 /*
1504 * tfile is the name of a file into which all shell commands
1505 * are put. It is removed before the child shell is executed,
1506 * unless DEBUG(SCRIPT) is set.
1507 */
1508 char *tfile;
1509 sigset_t mask;
1510 int tfd; /* File descriptor to the temp file */
1511
1512 /*
1513 * We're serious here, but if the commands were bogus, we're
1514 * also dead...
1515 */
1516 if (!cmdsOK) {
1517 PrintOnError(gn, NULL); /* provide some clue */
1518 DieHorribly();
1519 }
1520
1521 JobSigLock(&mask);
1522 tfd = mkTempFile(TMPPAT, &tfile);
1523 if (!DEBUG(SCRIPT))
1524 (void)eunlink(tfile);
1525 JobSigUnlock(&mask);
1526
1527 job->cmdFILE = fdopen(tfd, "w+");
1528 if (job->cmdFILE == NULL)
1529 Punt("Could not fdopen %s", tfile);
1530
1531 (void)fcntl(fileno(job->cmdFILE), F_SETFD, FD_CLOEXEC);
1532 /*
1533 * Send the commands to the command file, flush all its
1534 * buffers then rewind and remove the thing.
1535 */
1536 *out_run = TRUE;
1537
1538 #ifdef USE_META
1539 if (useMeta) {
1540 meta_job_start(job, gn);
1541 if (Targ_Silent(gn)) /* might have changed */
1542 job->echo = FALSE;
1543 }
1544 #endif
1545
1546 /* We can do all the commands at once. hooray for sanity */
1547 if (!JobPrintCommands(job))
1548 *out_run = FALSE;
1549
1550 free(tfile);
1551 }
1552
1553 /*
1554 * Start a target-creation process going for the target described by the
1555 * graph node gn.
1556 *
1557 * Input:
1558 * gn target to create
1559 * flags flags for the job to override normal ones.
1560 * previous The previous Job structure for this node, if any.
1561 *
1562 * Results:
1563 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1564 * if there isn't actually anything left to do for the job and
1565 * JOB_RUNNING if the job has been started.
1566 *
1567 * Side Effects:
1568 * A new Job node is created and added to the list of running
1569 * jobs. PMake is forked and a child shell created.
1570 *
1571 * NB: The return value is ignored by everyone.
1572 */
1573 static JobStartResult
1574 JobStart(GNode *gn, Boolean special)
1575 {
1576 Job *job; /* new job descriptor */
1577 char *argv[10]; /* Argument vector to shell */
1578 Boolean cmdsOK; /* true if the nodes commands were all right */
1579 Boolean run;
1580
1581 for (job = job_table; job < job_table_end; job++) {
1582 if (job->status == JOB_ST_FREE)
1583 break;
1584 }
1585 if (job >= job_table_end)
1586 Punt("JobStart no job slots vacant");
1587
1588 memset(job, 0, sizeof *job);
1589 job->node = gn;
1590 job->tailCmds = NULL;
1591 job->status = JOB_ST_SET_UP;
1592
1593 job->special = special || (gn->type & OP_SPECIAL);
1594 job->ignerr = Targ_Ignore(gn);
1595 job->echo = !Targ_Silent(gn);
1596 job->xtraced = FALSE;
1597
1598 /*
1599 * Check the commands now so any attributes from .DEFAULT have a
1600 * chance to migrate to the node.
1601 */
1602 cmdsOK = Job_CheckCommands(gn, Error);
1603
1604 job->inPollfd = NULL;
1605 /*
1606 * If the -n flag wasn't given, we open up OUR (not the child's)
1607 * temporary file to stuff commands in it. The thing is rd/wr so
1608 * we don't need to reopen it to feed it to the shell. If the -n
1609 * flag *was* given, we just set the file to be stdout. Cute, huh?
1610 */
1611 if (((gn->type & OP_MAKE) && !opts.noRecursiveExecute) ||
1612 (!opts.noExecute && !opts.touchFlag)) {
1613 JobOpenTmpFile(job, gn, cmdsOK, &run);
1614 } else if (!GNode_ShouldExecute(gn)) {
1615 /*
1616 * Not executing anything -- just print all the commands to
1617 * stdout in one fell swoop. This will still set up
1618 * job->tailCmds correctly.
1619 */
1620 SwitchOutputTo(gn);
1621 job->cmdFILE = stdout;
1622 /*
1623 * Only print the commands if they're ok, but don't die if
1624 * they're not -- just let the user know they're bad and
1625 * keep going. It doesn't do any harm in this case and may
1626 * do some good.
1627 */
1628 if (cmdsOK)
1629 JobPrintCommands(job);
1630 /* Don't execute the shell, thank you. */
1631 run = FALSE;
1632 } else {
1633 /*
1634 * Just touch the target and note that no shell should be
1635 * executed. Set cmdFILE to stdout to make life easier.
1636 * Check the commands, too, but don't die if they're no
1637 * good -- it does no harm to keep working up the graph.
1638 */
1639 job->cmdFILE = stdout;
1640 Job_Touch(gn, job->echo);
1641 run = FALSE;
1642 }
1643 /* Just in case it isn't already... */
1644 (void)fflush(job->cmdFILE);
1645
1646 /* If we're not supposed to execute a shell, don't. */
1647 if (!run) {
1648 if (!job->special)
1649 Job_TokenReturn();
1650 /* Unlink and close the command file if we opened one */
1651 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1652 (void)fclose(job->cmdFILE);
1653 job->cmdFILE = NULL;
1654 }
1655
1656 /*
1657 * We only want to work our way up the graph if we aren't
1658 * here because the commands for the job were no good.
1659 */
1660 if (cmdsOK && aborting == ABORT_NONE) {
1661 JobSaveCommands(job);
1662 job->node->made = MADE;
1663 Make_Update(job->node);
1664 }
1665 job->status = JOB_ST_FREE;
1666 return cmdsOK ? JOB_FINISHED : JOB_ERROR;
1667 }
1668
1669 /*
1670 * Set up the control arguments to the shell. This is based on the
1671 * flags set earlier for this job.
1672 */
1673 JobMakeArgv(job, argv);
1674
1675 /* Create the pipe by which we'll get the shell's output. */
1676 JobCreatePipe(job, 3);
1677
1678 JobExec(job, argv);
1679 return JOB_RUNNING;
1680 }
1681
1682 /*
1683 * Print the output of the shell command, skipping the noPrint command of
1684 * the shell, if any.
1685 */
1686 static char *
1687 JobOutput(char *cp, char *endp)
1688 {
1689 char *ecp;
1690
1691 if (shell->noPrint == NULL || shell->noPrint[0] == '\0')
1692 return cp;
1693
1694 while ((ecp = strstr(cp, shell->noPrint)) != NULL) {
1695 if (ecp != cp) {
1696 *ecp = '\0';
1697 /*
1698 * The only way there wouldn't be a newline after
1699 * this line is if it were the last in the buffer.
1700 * however, since the non-printable comes after it,
1701 * there must be a newline, so we don't print one.
1702 */
1703 (void)fprintf(stdout, "%s", cp);
1704 (void)fflush(stdout);
1705 }
1706 cp = ecp + shell->noPrintLen;
1707 if (cp != endp) {
1708 /*
1709 * Still more to print, look again after skipping
1710 * the whitespace following the non-printable
1711 * command.
1712 */
1713 cp++;
1714 pp_skip_whitespace(&cp);
1715 } else {
1716 return cp;
1717 }
1718 }
1719 return cp;
1720 }
1721
1722 /*
1723 * This function is called whenever there is something to read on the pipe.
1724 * We collect more output from the given job and store it in the job's
1725 * outBuf. If this makes up a line, we print it tagged by the job's
1726 * identifier, as necessary.
1727 *
1728 * In the output of the shell, the 'noPrint' lines are removed. If the
1729 * command is not alone on the line (the character after it is not \0 or
1730 * \n), we do print whatever follows it.
1731 *
1732 * Input:
1733 * job the job whose output needs printing
1734 * finish TRUE if this is the last time we'll be called
1735 * for this job
1736 */
1737 static void
1738 JobDoOutput(Job *job, Boolean finish)
1739 {
1740 Boolean gotNL; /* true if got a newline */
1741 Boolean fbuf; /* true if our buffer filled up */
1742 size_t nr; /* number of bytes read */
1743 size_t i; /* auxiliary index into outBuf */
1744 size_t max; /* limit for i (end of current data) */
1745 ssize_t nRead; /* (Temporary) number of bytes read */
1746
1747 /* Read as many bytes as will fit in the buffer. */
1748 again:
1749 gotNL = FALSE;
1750 fbuf = FALSE;
1751
1752 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1753 JOB_BUFSIZE - job->curPos);
1754 if (nRead < 0) {
1755 if (errno == EAGAIN)
1756 return;
1757 if (DEBUG(JOB)) {
1758 perror("JobDoOutput(piperead)");
1759 }
1760 nr = 0;
1761 } else {
1762 nr = (size_t)nRead;
1763 }
1764
1765 /*
1766 * If we hit the end-of-file (the job is dead), we must flush its
1767 * remaining output, so pretend we read a newline if there's any
1768 * output remaining in the buffer.
1769 * Also clear the 'finish' flag so we stop looping.
1770 */
1771 if (nr == 0 && job->curPos != 0) {
1772 job->outBuf[job->curPos] = '\n';
1773 nr = 1;
1774 finish = FALSE;
1775 } else if (nr == 0) {
1776 finish = FALSE;
1777 }
1778
1779 /*
1780 * Look for the last newline in the bytes we just got. If there is
1781 * one, break out of the loop with 'i' as its index and gotNL set
1782 * TRUE.
1783 */
1784 max = job->curPos + nr;
1785 for (i = job->curPos + nr - 1;
1786 i >= job->curPos && i != (size_t)-1; i--) {
1787 if (job->outBuf[i] == '\n') {
1788 gotNL = TRUE;
1789 break;
1790 } else if (job->outBuf[i] == '\0') {
1791 /*
1792 * Why?
1793 */
1794 job->outBuf[i] = ' ';
1795 }
1796 }
1797
1798 if (!gotNL) {
1799 job->curPos += nr;
1800 if (job->curPos == JOB_BUFSIZE) {
1801 /*
1802 * If we've run out of buffer space, we have no choice
1803 * but to print the stuff. sigh.
1804 */
1805 fbuf = TRUE;
1806 i = job->curPos;
1807 }
1808 }
1809 if (gotNL || fbuf) {
1810 /*
1811 * Need to send the output to the screen. Null terminate it
1812 * first, overwriting the newline character if there was one.
1813 * So long as the line isn't one we should filter (according
1814 * to the shell description), we print the line, preceded
1815 * by a target banner if this target isn't the same as the
1816 * one for which we last printed something.
1817 * The rest of the data in the buffer are then shifted down
1818 * to the start of the buffer and curPos is set accordingly.
1819 */
1820 job->outBuf[i] = '\0';
1821 if (i >= job->curPos) {
1822 char *cp;
1823
1824 cp = JobOutput(job->outBuf, &job->outBuf[i]);
1825
1826 /*
1827 * There's still more in that thar buffer. This time,
1828 * though, we know there's no newline at the end, so
1829 * we add one of our own free will.
1830 */
1831 if (*cp != '\0') {
1832 if (!opts.beSilent)
1833 SwitchOutputTo(job->node);
1834 #ifdef USE_META
1835 if (useMeta) {
1836 meta_job_output(job, cp,
1837 gotNL ? "\n" : "");
1838 }
1839 #endif
1840 (void)fprintf(stdout, "%s%s", cp,
1841 gotNL ? "\n" : "");
1842 (void)fflush(stdout);
1843 }
1844 }
1845 /*
1846 * max is the last offset still in the buffer. Move any
1847 * remaining characters to the start of the buffer and
1848 * update the end marker curPos.
1849 */
1850 if (i < max) {
1851 (void)memmove(job->outBuf, &job->outBuf[i + 1],
1852 max - (i + 1));
1853 job->curPos = max - (i + 1);
1854 } else {
1855 assert(i == max);
1856 job->curPos = 0;
1857 }
1858 }
1859 if (finish) {
1860 /*
1861 * If the finish flag is true, we must loop until we hit
1862 * end-of-file on the pipe. This is guaranteed to happen
1863 * eventually since the other end of the pipe is now closed
1864 * (we closed it explicitly and the child has exited). When
1865 * we do get an EOF, finish will be set FALSE and we'll fall
1866 * through and out.
1867 */
1868 goto again;
1869 }
1870 }
1871
1872 static void
1873 JobRun(GNode *targ)
1874 {
1875 #if 0
1876 /*
1877 * Unfortunately it is too complicated to run .BEGIN, .END, and
1878 * .INTERRUPT job in the parallel job module. As of 2020-09-25,
1879 * unit-tests/deptgt-end-jobs.mk hangs in an endless loop.
1880 *
1881 * Running these jobs in compat mode also guarantees that these
1882 * jobs do not overlap with other unrelated jobs.
1883 */
1884 List *lst = Lst_New();
1885 Lst_Append(lst, targ);
1886 (void)Make_Run(lst);
1887 Lst_Destroy(lst, NULL);
1888 JobStart(targ, JOB_SPECIAL);
1889 while (jobTokensRunning != 0) {
1890 Job_CatchOutput();
1891 }
1892 #else
1893 Compat_Make(targ, targ);
1894 /* XXX: Replace with GNode_IsError(gn) */
1895 if (targ->made == ERROR) {
1896 PrintOnError(targ, "\n\nStop.");
1897 exit(1);
1898 }
1899 #endif
1900 }
1901
1902 /* Handle the exit of a child. Called from Make_Make.
1903 *
1904 * The job descriptor is removed from the list of children.
1905 *
1906 * Notes:
1907 * We do waits, blocking or not, according to the wisdom of our
1908 * caller, until there are no more children to report. For each
1909 * job, call JobFinish to finish things off.
1910 */
1911 void
1912 Job_CatchChildren(void)
1913 {
1914 int pid; /* pid of dead child */
1915 int status; /* Exit/termination status */
1916
1917 /* Don't even bother if we know there's no one around. */
1918 if (jobTokensRunning == 0)
1919 return;
1920
1921 while ((pid = waitpid((pid_t)-1, &status, WNOHANG | WUNTRACED)) > 0) {
1922 DEBUG2(JOB, "Process %d exited/stopped status %x.\n",
1923 pid, status);
1924 JobReapChild(pid, status, TRUE);
1925 }
1926 }
1927
1928 /*
1929 * It is possible that wait[pid]() was called from elsewhere,
1930 * this lets us reap jobs regardless.
1931 */
1932 void
1933 JobReapChild(pid_t pid, int status, Boolean isJobs)
1934 {
1935 Job *job; /* job descriptor for dead child */
1936
1937 /* Don't even bother if we know there's no one around. */
1938 if (jobTokensRunning == 0)
1939 return;
1940
1941 job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
1942 if (job == NULL) {
1943 if (isJobs) {
1944 if (!lurking_children)
1945 Error("Child (%d) status %x not in table?",
1946 pid, status);
1947 }
1948 return; /* not ours */
1949 }
1950 if (WIFSTOPPED(status)) {
1951 DEBUG2(JOB, "Process %d (%s) stopped.\n",
1952 job->pid, job->node->name);
1953 if (!make_suspended) {
1954 switch (WSTOPSIG(status)) {
1955 case SIGTSTP:
1956 (void)printf("*** [%s] Suspended\n",
1957 job->node->name);
1958 break;
1959 case SIGSTOP:
1960 (void)printf("*** [%s] Stopped\n",
1961 job->node->name);
1962 break;
1963 default:
1964 (void)printf("*** [%s] Stopped -- signal %d\n",
1965 job->node->name, WSTOPSIG(status));
1966 }
1967 job->suspended = TRUE;
1968 }
1969 (void)fflush(stdout);
1970 return;
1971 }
1972
1973 job->status = JOB_ST_FINISHED;
1974 job->exit_status = status;
1975
1976 JobFinish(job, status);
1977 }
1978
1979 /* Catch the output from our children, if we're using pipes do so. Otherwise
1980 * just block time until we get a signal(most likely a SIGCHLD) since there's
1981 * no point in just spinning when there's nothing to do and the reaping of a
1982 * child can wait for a while. */
1983 void
1984 Job_CatchOutput(void)
1985 {
1986 int nready;
1987 Job *job;
1988 unsigned int i;
1989
1990 (void)fflush(stdout);
1991
1992 /* The first fd in the list is the job token pipe */
1993 do {
1994 nready = poll(fds + 1 - wantToken, nJobs - 1 + wantToken,
1995 POLL_MSEC);
1996 } while (nready < 0 && errno == EINTR);
1997
1998 if (nready < 0)
1999 Punt("poll: %s", strerror(errno));
2000
2001 if (nready > 0 && readyfd(&childExitJob)) {
2002 char token = 0;
2003 ssize_t count;
2004 count = read(childExitJob.inPipe, &token, 1);
2005 switch (count) {
2006 case 0:
2007 Punt("unexpected eof on token pipe");
2008 case -1:
2009 Punt("token pipe read: %s", strerror(errno));
2010 case 1:
2011 if (token == DO_JOB_RESUME[0])
2012 /*
2013 * Complete relay requested from our SIGCONT
2014 * handler
2015 */
2016 JobRestartJobs();
2017 break;
2018 default:
2019 abort();
2020 }
2021 nready--;
2022 }
2023
2024 Job_CatchChildren();
2025 if (nready == 0)
2026 return;
2027
2028 for (i = npseudojobs * nfds_per_job(); i < nJobs; i++) {
2029 if (!fds[i].revents)
2030 continue;
2031 job = allJobs[i];
2032 if (job->status == JOB_ST_RUNNING)
2033 JobDoOutput(job, FALSE);
2034 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2035 /*
2036 * With meta mode, we may have activity on the job's filemon
2037 * descriptor too, which at the moment is any pollfd other
2038 * than job->inPollfd.
2039 */
2040 if (useMeta && job->inPollfd != &fds[i]) {
2041 if (meta_job_event(job) <= 0) {
2042 fds[i].events = 0; /* never mind */
2043 }
2044 }
2045 #endif
2046 if (--nready == 0)
2047 return;
2048 }
2049 }
2050
2051 /* Start the creation of a target. Basically a front-end for JobStart used by
2052 * the Make module. */
2053 void
2054 Job_Make(GNode *gn)
2055 {
2056 (void)JobStart(gn, FALSE);
2057 }
2058
2059 static void
2060 InitShellNameAndPath(void)
2061 {
2062 shellName = shell->name;
2063
2064 #ifdef DEFSHELL_CUSTOM
2065 if (shellName[0] == '/') {
2066 shellPath = shellName;
2067 shellName = strrchr(shellPath, '/') + 1;
2068 return;
2069 }
2070 #endif
2071
2072 shellPath = str_concat3(_PATH_DEFSHELLDIR, "/", shellName);
2073 }
2074
2075 void
2076 Shell_Init(void)
2077 {
2078 if (shellPath == NULL)
2079 InitShellNameAndPath();
2080
2081 Var_SetWithFlags(".SHELL", shellPath, VAR_CMDLINE, VAR_SET_READONLY);
2082 if (shell->exitFlag == NULL)
2083 shell->exitFlag = "";
2084 if (shell->echoFlag == NULL)
2085 shell->echoFlag = "";
2086 if (shell->hasErrCtl && shell->exitFlag[0] != '\0') {
2087 if (shellErrFlag &&
2088 strcmp(shell->exitFlag, &shellErrFlag[1]) != 0) {
2089 free(shellErrFlag);
2090 shellErrFlag = NULL;
2091 }
2092 if (shellErrFlag == NULL) {
2093 size_t n = strlen(shell->exitFlag) + 2;
2094
2095 shellErrFlag = bmake_malloc(n);
2096 if (shellErrFlag != NULL)
2097 snprintf(shellErrFlag, n, "-%s",
2098 shell->exitFlag);
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 shell->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 'shell', 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 * 'shell' 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 'shell', 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.echoFlag = arg + 9;
2345 } else if (strncmp(arg, "errFlag=", 8) == 0) {
2346 newShell.exitFlag = 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 /* Before 2020-12-10, these two variables
2355 * had been a single variable. */
2356 newShell.errOn = arg + 6;
2357 newShell.echoTmpl = arg + 6;
2358 } else if (strncmp(arg, "ignore=", 7) == 0) {
2359 /* Before 2020-12-10, these two variables
2360 * had been a single variable. */
2361 newShell.errOff = arg + 7;
2362 newShell.runIgnTmpl = arg + 7;
2363 } else if (strncmp(arg, "errout=", 7) == 0) {
2364 newShell.runChkTmpl = arg + 7;
2365 } else if (strncmp(arg, "comment=", 8) == 0) {
2366 newShell.commentChar = arg[8];
2367 } else {
2368 Parse_Error(PARSE_FATAL,
2369 "Unknown keyword \"%s\"", arg);
2370 free(words);
2371 return FALSE;
2372 }
2373 fullSpec = TRUE;
2374 }
2375 }
2376
2377 if (path == NULL) {
2378 /*
2379 * If no path was given, the user wants one of the
2380 * pre-defined shells, yes? So we find the one s/he wants
2381 * with the help of FindShellByName and set things up the
2382 * right way. shellPath will be set up by Shell_Init.
2383 */
2384 if (newShell.name == NULL) {
2385 Parse_Error(PARSE_FATAL,
2386 "Neither path nor name specified");
2387 free(words);
2388 return FALSE;
2389 } else {
2390 if ((sh = FindShellByName(newShell.name)) == NULL) {
2391 Parse_Error(PARSE_WARNING,
2392 "%s: No matching shell", newShell.name);
2393 free(words);
2394 return FALSE;
2395 }
2396 shell = sh;
2397 shellName = newShell.name;
2398 if (shellPath != NULL) {
2399 /*
2400 * Shell_Init has already been called!
2401 * Do it again.
2402 */
2403 free(UNCONST(shellPath));
2404 shellPath = NULL;
2405 Shell_Init();
2406 }
2407 }
2408 } else {
2409 /*
2410 * The user provided a path. If s/he gave nothing else
2411 * (fullSpec is FALSE), try and find a matching shell in the
2412 * ones we know of. Else we just take the specification at
2413 * its word and copy it to a new location. In either case,
2414 * we need to record the path the user gave for the shell.
2415 */
2416 shellPath = path;
2417 path = strrchr(path, '/');
2418 if (path == NULL) {
2419 path = UNCONST(shellPath);
2420 } else {
2421 path++;
2422 }
2423 if (newShell.name != NULL) {
2424 shellName = newShell.name;
2425 } else {
2426 shellName = path;
2427 }
2428 if (!fullSpec) {
2429 if ((sh = FindShellByName(shellName)) == NULL) {
2430 Parse_Error(PARSE_WARNING,
2431 "%s: No matching shell", shellName);
2432 free(words);
2433 return FALSE;
2434 }
2435 shell = sh;
2436 } else {
2437 shell = bmake_malloc(sizeof *shell);
2438 *shell = newShell;
2439 }
2440 /* this will take care of shellErrFlag */
2441 Shell_Init();
2442 }
2443
2444 if (shell->echoOn && shell->echoOff)
2445 shell->hasEchoCtl = TRUE;
2446
2447 if (!shell->hasErrCtl) {
2448 if (shell->echoTmpl == NULL)
2449 shell->echoTmpl = "";
2450 if (shell->runIgnTmpl == NULL)
2451 shell->runIgnTmpl = "%s\n";
2452 }
2453
2454 /*
2455 * Do not free up the words themselves, since they might be in use
2456 * by the shell specification.
2457 */
2458 free(words);
2459 return TRUE;
2460 }
2461
2462 /*
2463 * Handle the receipt of an interrupt.
2464 *
2465 * All children are killed. Another job will be started if the .INTERRUPT
2466 * target is defined.
2467 *
2468 * Input:
2469 * runINTERRUPT Non-zero if commands for the .INTERRUPT target
2470 * should be executed
2471 * signo signal received
2472 */
2473 static void
2474 JobInterrupt(int runINTERRUPT, int signo)
2475 {
2476 Job *job; /* job descriptor in that element */
2477 GNode *interrupt; /* the node describing the .INTERRUPT target */
2478 sigset_t mask;
2479 GNode *gn;
2480
2481 aborting = ABORT_INTERRUPT;
2482
2483 JobSigLock(&mask);
2484
2485 for (job = job_table; job < job_table_end; job++) {
2486 if (job->status != JOB_ST_RUNNING)
2487 continue;
2488
2489 gn = job->node;
2490
2491 JobDeleteTarget(gn);
2492 if (job->pid) {
2493 DEBUG2(JOB,
2494 "JobInterrupt passing signal %d to child %d.\n",
2495 signo, job->pid);
2496 KILLPG(job->pid, signo);
2497 }
2498 }
2499
2500 JobSigUnlock(&mask);
2501
2502 if (runINTERRUPT && !opts.touchFlag) {
2503 interrupt = Targ_FindNode(".INTERRUPT");
2504 if (interrupt != NULL) {
2505 opts.ignoreErrors = FALSE;
2506 JobRun(interrupt);
2507 }
2508 }
2509 Trace_Log(MAKEINTR, NULL);
2510 exit(signo);
2511 }
2512
2513 /*
2514 * Do the final processing, i.e. run the commands attached to the .END target.
2515 *
2516 * Return the number of errors reported.
2517 */
2518 int
2519 Job_Finish(void)
2520 {
2521 GNode *endNode = Targ_GetEndNode();
2522 if (!Lst_IsEmpty(&endNode->commands) ||
2523 !Lst_IsEmpty(&endNode->children)) {
2524 if (job_errors != 0) {
2525 Error("Errors reported so .END ignored");
2526 } else {
2527 JobRun(endNode);
2528 }
2529 }
2530 return job_errors;
2531 }
2532
2533 /* Clean up any memory used by the jobs module. */
2534 void
2535 Job_End(void)
2536 {
2537 #ifdef CLEANUP
2538 free(shellArgv);
2539 #endif
2540 }
2541
2542 /*
2543 * Waits for all running jobs to finish and returns.
2544 * Sets 'aborting' to ABORT_WAIT to prevent other jobs from starting.
2545 */
2546 void
2547 Job_Wait(void)
2548 {
2549 aborting = ABORT_WAIT;
2550 while (jobTokensRunning != 0) {
2551 Job_CatchOutput();
2552 }
2553 aborting = ABORT_NONE;
2554 }
2555
2556 /*
2557 * Abort all currently running jobs without handling output or anything.
2558 * This function is to be called only in the event of a major error.
2559 * Most definitely NOT to be called from JobInterrupt.
2560 *
2561 * All children are killed, not just the firstborn.
2562 */
2563 void
2564 Job_AbortAll(void)
2565 {
2566 Job *job; /* the job descriptor in that element */
2567 int foo;
2568
2569 aborting = ABORT_ERROR;
2570
2571 if (jobTokensRunning != 0) {
2572 for (job = job_table; job < job_table_end; job++) {
2573 if (job->status != JOB_ST_RUNNING)
2574 continue;
2575 /*
2576 * kill the child process with increasingly drastic
2577 * signals to make darn sure it's dead.
2578 */
2579 KILLPG(job->pid, SIGINT);
2580 KILLPG(job->pid, SIGKILL);
2581 }
2582 }
2583
2584 /*
2585 * Catch as many children as want to report in at first, then give up
2586 */
2587 while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2588 continue;
2589 }
2590
2591 /*
2592 * Tries to restart stopped jobs if there are slots available.
2593 * Called in process context in response to a SIGCONT.
2594 */
2595 static void
2596 JobRestartJobs(void)
2597 {
2598 Job *job;
2599
2600 for (job = job_table; job < job_table_end; job++) {
2601 if (job->status == JOB_ST_RUNNING &&
2602 (make_suspended || job->suspended)) {
2603 DEBUG1(JOB, "Restarting stopped job pid %d.\n",
2604 job->pid);
2605 if (job->suspended) {
2606 (void)printf("*** [%s] Continued\n",
2607 job->node->name);
2608 (void)fflush(stdout);
2609 }
2610 job->suspended = FALSE;
2611 if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
2612 debug_printf("Failed to send SIGCONT to %d\n",
2613 job->pid);
2614 }
2615 }
2616 if (job->status == JOB_ST_FINISHED) {
2617 /*
2618 * Job exit deferred after calling waitpid() in a
2619 * signal handler
2620 */
2621 JobFinish(job, job->exit_status);
2622 }
2623 }
2624 make_suspended = FALSE;
2625 }
2626
2627 static void
2628 watchfd(Job *job)
2629 {
2630 if (job->inPollfd != NULL)
2631 Punt("Watching watched job");
2632
2633 fds[nJobs].fd = job->inPipe;
2634 fds[nJobs].events = POLLIN;
2635 allJobs[nJobs] = job;
2636 job->inPollfd = &fds[nJobs];
2637 nJobs++;
2638 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2639 if (useMeta) {
2640 fds[nJobs].fd = meta_job_fd(job);
2641 fds[nJobs].events = fds[nJobs].fd == -1 ? 0 : POLLIN;
2642 allJobs[nJobs] = job;
2643 nJobs++;
2644 }
2645 #endif
2646 }
2647
2648 static void
2649 clearfd(Job *job)
2650 {
2651 size_t i;
2652 if (job->inPollfd == NULL)
2653 Punt("Unwatching unwatched job");
2654 i = (size_t)(job->inPollfd - fds);
2655 nJobs--;
2656 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2657 if (useMeta) {
2658 /*
2659 * Sanity check: there should be two fds per job, so the job's
2660 * pollfd number should be even.
2661 */
2662 assert(nfds_per_job() == 2);
2663 if (i % 2)
2664 Punt("odd-numbered fd with meta");
2665 nJobs--;
2666 }
2667 #endif
2668 /*
2669 * Move last job in table into hole made by dead job.
2670 */
2671 if (nJobs != i) {
2672 fds[i] = fds[nJobs];
2673 allJobs[i] = allJobs[nJobs];
2674 allJobs[i]->inPollfd = &fds[i];
2675 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2676 if (useMeta) {
2677 fds[i + 1] = fds[nJobs + 1];
2678 allJobs[i + 1] = allJobs[nJobs + 1];
2679 }
2680 #endif
2681 }
2682 job->inPollfd = NULL;
2683 }
2684
2685 static int
2686 readyfd(Job *job)
2687 {
2688 if (job->inPollfd == NULL)
2689 Punt("Polling unwatched job");
2690 return (job->inPollfd->revents & POLLIN) != 0;
2691 }
2692
2693 /* Put a token (back) into the job pipe.
2694 * This allows a make process to start a build job. */
2695 static void
2696 JobTokenAdd(void)
2697 {
2698 char tok = JOB_TOKENS[aborting], tok1;
2699
2700 /* If we are depositing an error token flush everything else */
2701 while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2702 continue;
2703
2704 DEBUG3(JOB, "(%d) aborting %d, deposit token %c\n",
2705 getpid(), aborting, JOB_TOKENS[aborting]);
2706 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2707 continue;
2708 }
2709
2710 /* Prep the job token pipe in the root make process. */
2711 void
2712 Job_ServerStart(int max_tokens, int jp_0, int jp_1)
2713 {
2714 int i;
2715 char jobarg[64];
2716
2717 if (jp_0 >= 0 && jp_1 >= 0) {
2718 /* Pipe passed in from parent */
2719 tokenWaitJob.inPipe = jp_0;
2720 tokenWaitJob.outPipe = jp_1;
2721 (void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
2722 (void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
2723 return;
2724 }
2725
2726 JobCreatePipe(&tokenWaitJob, 15);
2727
2728 snprintf(jobarg, sizeof jobarg, "%d,%d",
2729 tokenWaitJob.inPipe, tokenWaitJob.outPipe);
2730
2731 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
2732 Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
2733
2734 /*
2735 * Preload the job pipe with one token per job, save the one
2736 * "extra" token for the primary job.
2737 *
2738 * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
2739 * larger than the write buffer size of the pipe, we will
2740 * deadlock here.
2741 */
2742 for (i = 1; i < max_tokens; i++)
2743 JobTokenAdd();
2744 }
2745
2746 /* Return a withdrawn token to the pool. */
2747 void
2748 Job_TokenReturn(void)
2749 {
2750 jobTokensRunning--;
2751 if (jobTokensRunning < 0)
2752 Punt("token botch");
2753 if (jobTokensRunning || JOB_TOKENS[aborting] != '+')
2754 JobTokenAdd();
2755 }
2756
2757 /*
2758 * Attempt to withdraw a token from the pool.
2759 *
2760 * If pool is empty, set wantToken so that we wake up when a token is
2761 * released.
2762 *
2763 * Returns TRUE if a token was withdrawn, and FALSE if the pool is currently
2764 * empty.
2765 */
2766 Boolean
2767 Job_TokenWithdraw(void)
2768 {
2769 char tok, tok1;
2770 ssize_t count;
2771
2772 wantToken = 0;
2773 DEBUG3(JOB, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
2774 getpid(), aborting, jobTokensRunning);
2775
2776 if (aborting != ABORT_NONE || (jobTokensRunning >= opts.maxJobs))
2777 return FALSE;
2778
2779 count = read(tokenWaitJob.inPipe, &tok, 1);
2780 if (count == 0)
2781 Fatal("eof on job pipe!");
2782 if (count < 0 && jobTokensRunning != 0) {
2783 if (errno != EAGAIN) {
2784 Fatal("job pipe read: %s", strerror(errno));
2785 }
2786 DEBUG1(JOB, "(%d) blocked for token\n", getpid());
2787 return FALSE;
2788 }
2789
2790 if (count == 1 && tok != '+') {
2791 /* make being aborted - remove any other job tokens */
2792 DEBUG2(JOB, "(%d) aborted by token %c\n", getpid(), tok);
2793 while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2794 continue;
2795 /* And put the stopper back */
2796 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
2797 errno == EAGAIN)
2798 continue;
2799 if (shouldDieQuietly(NULL, 1))
2800 exit(2);
2801 Fatal("A failure has been detected "
2802 "in another branch of the parallel make");
2803 }
2804
2805 if (count == 1 && jobTokensRunning == 0)
2806 /* We didn't want the token really */
2807 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
2808 errno == EAGAIN)
2809 continue;
2810
2811 jobTokensRunning++;
2812 DEBUG1(JOB, "(%d) withdrew token\n", getpid());
2813 return TRUE;
2814 }
2815
2816 /*
2817 * Run the named target if found. If a filename is specified, then set that
2818 * to the sources.
2819 *
2820 * Exits if the target fails.
2821 */
2822 Boolean
2823 Job_RunTarget(const char *target, const char *fname)
2824 {
2825 GNode *gn = Targ_FindNode(target);
2826 if (gn == NULL)
2827 return FALSE;
2828
2829 if (fname != NULL)
2830 Var_Set(ALLSRC, fname, gn);
2831
2832 JobRun(gn);
2833 /* XXX: Replace with GNode_IsError(gn) */
2834 if (gn->made == ERROR) {
2835 PrintOnError(gn, "\n\nStop.");
2836 exit(1);
2837 }
2838 return TRUE;
2839 }
2840
2841 #ifdef USE_SELECT
2842 int
2843 emul_poll(struct pollfd *fd, int nfd, int timeout)
2844 {
2845 fd_set rfds, wfds;
2846 int i, maxfd, nselect, npoll;
2847 struct timeval tv, *tvp;
2848 long usecs;
2849
2850 FD_ZERO(&rfds);
2851 FD_ZERO(&wfds);
2852
2853 maxfd = -1;
2854 for (i = 0; i < nfd; i++) {
2855 fd[i].revents = 0;
2856
2857 if (fd[i].events & POLLIN)
2858 FD_SET(fd[i].fd, &rfds);
2859
2860 if (fd[i].events & POLLOUT)
2861 FD_SET(fd[i].fd, &wfds);
2862
2863 if (fd[i].fd > maxfd)
2864 maxfd = fd[i].fd;
2865 }
2866
2867 if (maxfd >= FD_SETSIZE) {
2868 Punt("Ran out of fd_set slots; "
2869 "recompile with a larger FD_SETSIZE.");
2870 }
2871
2872 if (timeout < 0) {
2873 tvp = NULL;
2874 } else {
2875 usecs = timeout * 1000;
2876 tv.tv_sec = usecs / 1000000;
2877 tv.tv_usec = usecs % 1000000;
2878 tvp = &tv;
2879 }
2880
2881 nselect = select(maxfd + 1, &rfds, &wfds, NULL, tvp);
2882
2883 if (nselect <= 0)
2884 return nselect;
2885
2886 npoll = 0;
2887 for (i = 0; i < nfd; i++) {
2888 if (FD_ISSET(fd[i].fd, &rfds))
2889 fd[i].revents |= POLLIN;
2890
2891 if (FD_ISSET(fd[i].fd, &wfds))
2892 fd[i].revents |= POLLOUT;
2893
2894 if (fd[i].revents)
2895 npoll++;
2896 }
2897
2898 return npoll;
2899 }
2900 #endif /* USE_SELECT */
2901