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