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