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