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