job.c revision 1.361 1 /* $NetBSD: job.c,v 1.361 2020/12/10 23:03:00 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.361 2020/12/10 23:03:00 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 static void
1503 JobOpenTmpFile(Job *job, GNode *gn, Boolean cmdsOK, Boolean *out_run)
1504 {
1505 /*
1506 * tfile is the name of a file into which all shell commands
1507 * are put. It is removed before the child shell is executed,
1508 * unless DEBUG(SCRIPT) is set.
1509 */
1510 char *tfile;
1511 sigset_t mask;
1512 int tfd; /* File descriptor to the temp file */
1513
1514 /*
1515 * We're serious here, but if the commands were bogus, we're
1516 * also dead...
1517 */
1518 if (!cmdsOK) {
1519 PrintOnError(gn, NULL); /* provide some clue */
1520 DieHorribly();
1521 }
1522
1523 JobSigLock(&mask);
1524 tfd = mkTempFile(TMPPAT, &tfile);
1525 if (!DEBUG(SCRIPT))
1526 (void)eunlink(tfile);
1527 JobSigUnlock(&mask);
1528
1529 job->cmdFILE = fdopen(tfd, "w+");
1530 if (job->cmdFILE == NULL)
1531 Punt("Could not fdopen %s", tfile);
1532
1533 (void)fcntl(fileno(job->cmdFILE), F_SETFD, FD_CLOEXEC);
1534 /*
1535 * Send the commands to the command file, flush all its
1536 * buffers then rewind and remove the thing.
1537 */
1538 *out_run = TRUE;
1539
1540 #ifdef USE_META
1541 if (useMeta) {
1542 meta_job_start(job, gn);
1543 if (Targ_Silent(gn)) /* might have changed */
1544 job->echo = FALSE;
1545 }
1546 #endif
1547 /* We can do all the commands at once. hooray for sanity */
1548 numCommands = 0;
1549 JobPrintCommands(job);
1550
1551 /*
1552 * If we didn't print out any commands to the shell script,
1553 * there's no point in executing the shell.
1554 */
1555 if (numCommands == 0)
1556 *out_run = FALSE;
1557
1558 free(tfile);
1559 }
1560
1561 /*
1562 * Start a target-creation process going for the target described by the
1563 * graph node gn.
1564 *
1565 * Input:
1566 * gn target to create
1567 * flags flags for the job to override normal ones.
1568 * previous The previous Job structure for this node, if any.
1569 *
1570 * Results:
1571 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1572 * if there isn't actually anything left to do for the job and
1573 * JOB_RUNNING if the job has been started.
1574 *
1575 * Side Effects:
1576 * A new Job node is created and added to the list of running
1577 * jobs. PMake is forked and a child shell created.
1578 *
1579 * NB: The return value is ignored by everyone.
1580 */
1581 static JobStartResult
1582 JobStart(GNode *gn, Boolean special)
1583 {
1584 Job *job; /* new job descriptor */
1585 char *argv[10]; /* Argument vector to shell */
1586 Boolean cmdsOK; /* true if the nodes commands were all right */
1587 Boolean run;
1588
1589 for (job = job_table; job < job_table_end; job++) {
1590 if (job->status == JOB_ST_FREE)
1591 break;
1592 }
1593 if (job >= job_table_end)
1594 Punt("JobStart no job slots vacant");
1595
1596 memset(job, 0, sizeof *job);
1597 job->node = gn;
1598 job->tailCmds = NULL;
1599 job->status = JOB_ST_SET_UP;
1600
1601 job->special = special || (gn->type & OP_SPECIAL);
1602 job->ignerr = Targ_Ignore(gn);
1603 job->echo = !Targ_Silent(gn);
1604 job->xtraced = FALSE;
1605
1606 /*
1607 * Check the commands now so any attributes from .DEFAULT have a
1608 * chance to migrate to the node.
1609 */
1610 cmdsOK = Job_CheckCommands(gn, Error);
1611
1612 job->inPollfd = NULL;
1613 /*
1614 * If the -n flag wasn't given, we open up OUR (not the child's)
1615 * temporary file to stuff commands in it. The thing is rd/wr so
1616 * we don't need to reopen it to feed it to the shell. If the -n
1617 * flag *was* given, we just set the file to be stdout. Cute, huh?
1618 */
1619 if (((gn->type & OP_MAKE) && !opts.noRecursiveExecute) ||
1620 (!opts.noExecute && !opts.touchFlag)) {
1621 JobOpenTmpFile(job, gn, cmdsOK, &run);
1622 } else if (!GNode_ShouldExecute(gn)) {
1623 /*
1624 * Not executing anything -- just print all the commands to
1625 * stdout in one fell swoop. This will still set up
1626 * job->tailCmds correctly.
1627 */
1628 SwitchOutputTo(gn);
1629 job->cmdFILE = stdout;
1630 /*
1631 * Only print the commands if they're ok, but don't die if
1632 * they're not -- just let the user know they're bad and
1633 * keep going. It doesn't do any harm in this case and may
1634 * do some good.
1635 */
1636 if (cmdsOK)
1637 JobPrintCommands(job);
1638 /* Don't execute the shell, thank you. */
1639 run = FALSE;
1640 } else {
1641 /*
1642 * Just touch the target and note that no shell should be
1643 * executed. Set cmdFILE to stdout to make life easier.
1644 * Check the commands, too, but don't die if they're no
1645 * good -- it does no harm to keep working up the graph.
1646 */
1647 job->cmdFILE = stdout;
1648 Job_Touch(gn, job->echo);
1649 run = FALSE;
1650 }
1651 /* Just in case it isn't already... */
1652 (void)fflush(job->cmdFILE);
1653
1654 /* If we're not supposed to execute a shell, don't. */
1655 if (!run) {
1656 if (!job->special)
1657 Job_TokenReturn();
1658 /* Unlink and close the command file if we opened one */
1659 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1660 (void)fclose(job->cmdFILE);
1661 job->cmdFILE = NULL;
1662 }
1663
1664 /*
1665 * We only want to work our way up the graph if we aren't
1666 * here because the commands for the job were no good.
1667 */
1668 if (cmdsOK && aborting == ABORT_NONE) {
1669 JobSaveCommands(job);
1670 job->node->made = MADE;
1671 Make_Update(job->node);
1672 }
1673 job->status = JOB_ST_FREE;
1674 return cmdsOK ? JOB_FINISHED : JOB_ERROR;
1675 }
1676
1677 /*
1678 * Set up the control arguments to the shell. This is based on the
1679 * flags set earlier for this job.
1680 */
1681 JobMakeArgv(job, argv);
1682
1683 /* Create the pipe by which we'll get the shell's output. */
1684 JobCreatePipe(job, 3);
1685
1686 JobExec(job, argv);
1687 return JOB_RUNNING;
1688 }
1689
1690 /*
1691 * Print the output of the shell command, skipping the noPrint command of
1692 * the shell, if any.
1693 */
1694 static char *
1695 JobOutput(char *cp, char *endp)
1696 {
1697 char *ecp;
1698
1699 if (shell->noPrint == NULL || shell->noPrint[0] == '\0')
1700 return cp;
1701
1702 while ((ecp = strstr(cp, shell->noPrint)) != NULL) {
1703 if (ecp != cp) {
1704 *ecp = '\0';
1705 /*
1706 * The only way there wouldn't be a newline after
1707 * this line is if it were the last in the buffer.
1708 * however, since the non-printable comes after it,
1709 * there must be a newline, so we don't print one.
1710 */
1711 (void)fprintf(stdout, "%s", cp);
1712 (void)fflush(stdout);
1713 }
1714 cp = ecp + shell->noPrintLen;
1715 if (cp != endp) {
1716 /*
1717 * Still more to print, look again after skipping
1718 * the whitespace following the non-printable
1719 * command.
1720 */
1721 cp++;
1722 pp_skip_whitespace(&cp);
1723 } else {
1724 return cp;
1725 }
1726 }
1727 return cp;
1728 }
1729
1730 /*
1731 * This function is called whenever there is something to read on the pipe.
1732 * We collect more output from the given job and store it in the job's
1733 * outBuf. If this makes up a line, we print it tagged by the job's
1734 * identifier, as necessary.
1735 *
1736 * In the output of the shell, the 'noPrint' lines are removed. If the
1737 * command is not alone on the line (the character after it is not \0 or
1738 * \n), we do print whatever follows it.
1739 *
1740 * Input:
1741 * job the job whose output needs printing
1742 * finish TRUE if this is the last time we'll be called
1743 * for this job
1744 */
1745 static void
1746 JobDoOutput(Job *job, Boolean finish)
1747 {
1748 Boolean gotNL; /* true if got a newline */
1749 Boolean fbuf; /* true if our buffer filled up */
1750 size_t nr; /* number of bytes read */
1751 size_t i; /* auxiliary index into outBuf */
1752 size_t max; /* limit for i (end of current data) */
1753 ssize_t nRead; /* (Temporary) number of bytes read */
1754
1755 /* Read as many bytes as will fit in the buffer. */
1756 again:
1757 gotNL = FALSE;
1758 fbuf = FALSE;
1759
1760 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1761 JOB_BUFSIZE - job->curPos);
1762 if (nRead < 0) {
1763 if (errno == EAGAIN)
1764 return;
1765 if (DEBUG(JOB)) {
1766 perror("JobDoOutput(piperead)");
1767 }
1768 nr = 0;
1769 } else {
1770 nr = (size_t)nRead;
1771 }
1772
1773 /*
1774 * If we hit the end-of-file (the job is dead), we must flush its
1775 * remaining output, so pretend we read a newline if there's any
1776 * output remaining in the buffer.
1777 * Also clear the 'finish' flag so we stop looping.
1778 */
1779 if (nr == 0 && job->curPos != 0) {
1780 job->outBuf[job->curPos] = '\n';
1781 nr = 1;
1782 finish = FALSE;
1783 } else if (nr == 0) {
1784 finish = FALSE;
1785 }
1786
1787 /*
1788 * Look for the last newline in the bytes we just got. If there is
1789 * one, break out of the loop with 'i' as its index and gotNL set
1790 * TRUE.
1791 */
1792 max = job->curPos + nr;
1793 for (i = job->curPos + nr - 1;
1794 i >= job->curPos && i != (size_t)-1; i--) {
1795 if (job->outBuf[i] == '\n') {
1796 gotNL = TRUE;
1797 break;
1798 } else if (job->outBuf[i] == '\0') {
1799 /*
1800 * Why?
1801 */
1802 job->outBuf[i] = ' ';
1803 }
1804 }
1805
1806 if (!gotNL) {
1807 job->curPos += nr;
1808 if (job->curPos == JOB_BUFSIZE) {
1809 /*
1810 * If we've run out of buffer space, we have no choice
1811 * but to print the stuff. sigh.
1812 */
1813 fbuf = TRUE;
1814 i = job->curPos;
1815 }
1816 }
1817 if (gotNL || fbuf) {
1818 /*
1819 * Need to send the output to the screen. Null terminate it
1820 * first, overwriting the newline character if there was one.
1821 * So long as the line isn't one we should filter (according
1822 * to the shell description), we print the line, preceded
1823 * by a target banner if this target isn't the same as the
1824 * one for which we last printed something.
1825 * The rest of the data in the buffer are then shifted down
1826 * to the start of the buffer and curPos is set accordingly.
1827 */
1828 job->outBuf[i] = '\0';
1829 if (i >= job->curPos) {
1830 char *cp;
1831
1832 cp = JobOutput(job->outBuf, &job->outBuf[i]);
1833
1834 /*
1835 * There's still more in that thar buffer. This time,
1836 * though, we know there's no newline at the end, so
1837 * we add one of our own free will.
1838 */
1839 if (*cp != '\0') {
1840 if (!opts.beSilent)
1841 SwitchOutputTo(job->node);
1842 #ifdef USE_META
1843 if (useMeta) {
1844 meta_job_output(job, cp,
1845 gotNL ? "\n" : "");
1846 }
1847 #endif
1848 (void)fprintf(stdout, "%s%s", cp,
1849 gotNL ? "\n" : "");
1850 (void)fflush(stdout);
1851 }
1852 }
1853 /*
1854 * max is the last offset still in the buffer. Move any
1855 * remaining characters to the start of the buffer and
1856 * update the end marker curPos.
1857 */
1858 if (i < max) {
1859 (void)memmove(job->outBuf, &job->outBuf[i + 1],
1860 max - (i + 1));
1861 job->curPos = max - (i + 1);
1862 } else {
1863 assert(i == max);
1864 job->curPos = 0;
1865 }
1866 }
1867 if (finish) {
1868 /*
1869 * If the finish flag is true, we must loop until we hit
1870 * end-of-file on the pipe. This is guaranteed to happen
1871 * eventually since the other end of the pipe is now closed
1872 * (we closed it explicitly and the child has exited). When
1873 * we do get an EOF, finish will be set FALSE and we'll fall
1874 * through and out.
1875 */
1876 goto again;
1877 }
1878 }
1879
1880 static void
1881 JobRun(GNode *targ)
1882 {
1883 #if 0
1884 /*
1885 * Unfortunately it is too complicated to run .BEGIN, .END, and
1886 * .INTERRUPT job in the parallel job module. As of 2020-09-25,
1887 * unit-tests/deptgt-end-jobs.mk hangs in an endless loop.
1888 *
1889 * Running these jobs in compat mode also guarantees that these
1890 * jobs do not overlap with other unrelated jobs.
1891 */
1892 List *lst = Lst_New();
1893 Lst_Append(lst, targ);
1894 (void)Make_Run(lst);
1895 Lst_Destroy(lst, NULL);
1896 JobStart(targ, JOB_SPECIAL);
1897 while (jobTokensRunning != 0) {
1898 Job_CatchOutput();
1899 }
1900 #else
1901 Compat_Make(targ, targ);
1902 /* XXX: Replace with GNode_IsError(gn) */
1903 if (targ->made == ERROR) {
1904 PrintOnError(targ, "\n\nStop.");
1905 exit(1);
1906 }
1907 #endif
1908 }
1909
1910 /* Handle the exit of a child. Called from Make_Make.
1911 *
1912 * The job descriptor is removed from the list of children.
1913 *
1914 * Notes:
1915 * We do waits, blocking or not, according to the wisdom of our
1916 * caller, until there are no more children to report. For each
1917 * job, call JobFinish to finish things off.
1918 */
1919 void
1920 Job_CatchChildren(void)
1921 {
1922 int pid; /* pid of dead child */
1923 int status; /* Exit/termination status */
1924
1925 /* Don't even bother if we know there's no one around. */
1926 if (jobTokensRunning == 0)
1927 return;
1928
1929 while ((pid = waitpid((pid_t)-1, &status, WNOHANG | WUNTRACED)) > 0) {
1930 DEBUG2(JOB, "Process %d exited/stopped status %x.\n",
1931 pid, status);
1932 JobReapChild(pid, status, TRUE);
1933 }
1934 }
1935
1936 /*
1937 * It is possible that wait[pid]() was called from elsewhere,
1938 * this lets us reap jobs regardless.
1939 */
1940 void
1941 JobReapChild(pid_t pid, int status, Boolean isJobs)
1942 {
1943 Job *job; /* job descriptor for dead child */
1944
1945 /* Don't even bother if we know there's no one around. */
1946 if (jobTokensRunning == 0)
1947 return;
1948
1949 job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
1950 if (job == NULL) {
1951 if (isJobs) {
1952 if (!lurking_children)
1953 Error("Child (%d) status %x not in table?",
1954 pid, status);
1955 }
1956 return; /* not ours */
1957 }
1958 if (WIFSTOPPED(status)) {
1959 DEBUG2(JOB, "Process %d (%s) stopped.\n",
1960 job->pid, job->node->name);
1961 if (!make_suspended) {
1962 switch (WSTOPSIG(status)) {
1963 case SIGTSTP:
1964 (void)printf("*** [%s] Suspended\n",
1965 job->node->name);
1966 break;
1967 case SIGSTOP:
1968 (void)printf("*** [%s] Stopped\n",
1969 job->node->name);
1970 break;
1971 default:
1972 (void)printf("*** [%s] Stopped -- signal %d\n",
1973 job->node->name, WSTOPSIG(status));
1974 }
1975 job->suspended = TRUE;
1976 }
1977 (void)fflush(stdout);
1978 return;
1979 }
1980
1981 job->status = JOB_ST_FINISHED;
1982 job->exit_status = status;
1983
1984 JobFinish(job, status);
1985 }
1986
1987 /* Catch the output from our children, if we're using pipes do so. Otherwise
1988 * just block time until we get a signal(most likely a SIGCHLD) since there's
1989 * no point in just spinning when there's nothing to do and the reaping of a
1990 * child can wait for a while. */
1991 void
1992 Job_CatchOutput(void)
1993 {
1994 int nready;
1995 Job *job;
1996 unsigned int i;
1997
1998 (void)fflush(stdout);
1999
2000 /* The first fd in the list is the job token pipe */
2001 do {
2002 nready = poll(fds + 1 - wantToken, nJobs - 1 + wantToken,
2003 POLL_MSEC);
2004 } while (nready < 0 && errno == EINTR);
2005
2006 if (nready < 0)
2007 Punt("poll: %s", strerror(errno));
2008
2009 if (nready > 0 && readyfd(&childExitJob)) {
2010 char token = 0;
2011 ssize_t count;
2012 count = read(childExitJob.inPipe, &token, 1);
2013 switch (count) {
2014 case 0:
2015 Punt("unexpected eof on token pipe");
2016 case -1:
2017 Punt("token pipe read: %s", strerror(errno));
2018 case 1:
2019 if (token == DO_JOB_RESUME[0])
2020 /*
2021 * Complete relay requested from our SIGCONT
2022 * handler
2023 */
2024 JobRestartJobs();
2025 break;
2026 default:
2027 abort();
2028 }
2029 nready--;
2030 }
2031
2032 Job_CatchChildren();
2033 if (nready == 0)
2034 return;
2035
2036 for (i = npseudojobs * nfds_per_job(); i < nJobs; i++) {
2037 if (!fds[i].revents)
2038 continue;
2039 job = allJobs[i];
2040 if (job->status == JOB_ST_RUNNING)
2041 JobDoOutput(job, FALSE);
2042 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2043 /*
2044 * With meta mode, we may have activity on the job's filemon
2045 * descriptor too, which at the moment is any pollfd other
2046 * than job->inPollfd.
2047 */
2048 if (useMeta && job->inPollfd != &fds[i]) {
2049 if (meta_job_event(job) <= 0) {
2050 fds[i].events = 0; /* never mind */
2051 }
2052 }
2053 #endif
2054 if (--nready == 0)
2055 return;
2056 }
2057 }
2058
2059 /* Start the creation of a target. Basically a front-end for JobStart used by
2060 * the Make module. */
2061 void
2062 Job_Make(GNode *gn)
2063 {
2064 (void)JobStart(gn, FALSE);
2065 }
2066
2067 static void
2068 InitShellNameAndPath(void)
2069 {
2070 shellName = shell->name;
2071
2072 #ifdef DEFSHELL_CUSTOM
2073 if (shellName[0] == '/') {
2074 shellPath = shellName;
2075 shellName = strrchr(shellPath, '/') + 1;
2076 return;
2077 }
2078 #endif
2079
2080 shellPath = str_concat3(_PATH_DEFSHELLDIR, "/", shellName);
2081 }
2082
2083 void
2084 Shell_Init(void)
2085 {
2086 if (shellPath == NULL)
2087 InitShellNameAndPath();
2088
2089 Var_SetWithFlags(".SHELL", shellPath, VAR_CMDLINE, VAR_SET_READONLY);
2090 if (shell->exit == NULL)
2091 shell->exit = "";
2092 if (shell->echo == NULL)
2093 shell->echo = "";
2094 if (shell->hasErrCtl && shell->exit[0] != '\0') {
2095 if (shellErrFlag &&
2096 strcmp(shell->exit, &shellErrFlag[1]) != 0) {
2097 free(shellErrFlag);
2098 shellErrFlag = NULL;
2099 }
2100 if (shellErrFlag == NULL) {
2101 size_t n = strlen(shell->exit) + 2;
2102
2103 shellErrFlag = bmake_malloc(n);
2104 if (shellErrFlag != NULL)
2105 snprintf(shellErrFlag, n, "-%s", shell->exit);
2106 }
2107 } else if (shellErrFlag != NULL) {
2108 free(shellErrFlag);
2109 shellErrFlag = NULL;
2110 }
2111 }
2112
2113 /*
2114 * Return the string literal that is used in the current command shell
2115 * to produce a newline character.
2116 */
2117 const char *
2118 Shell_GetNewline(void)
2119 {
2120 return shell->newline;
2121 }
2122
2123 void
2124 Job_SetPrefix(void)
2125 {
2126 if (targPrefix != NULL) {
2127 free(targPrefix);
2128 } else if (!Var_Exists(MAKE_JOB_PREFIX, VAR_GLOBAL)) {
2129 Var_Set(MAKE_JOB_PREFIX, "---", VAR_GLOBAL);
2130 }
2131
2132 (void)Var_Subst("${" MAKE_JOB_PREFIX "}",
2133 VAR_GLOBAL, VARE_WANTRES, &targPrefix);
2134 /* TODO: handle errors */
2135 }
2136
2137 static void
2138 AddSig(int sig, SignalProc handler)
2139 {
2140 if (bmake_signal(sig, SIG_IGN) != SIG_IGN) {
2141 sigaddset(&caught_signals, sig);
2142 (void)bmake_signal(sig, handler);
2143 }
2144 }
2145
2146 /* Initialize the process module. */
2147 void
2148 Job_Init(void)
2149 {
2150 Job_SetPrefix();
2151 /* Allocate space for all the job info */
2152 job_table = bmake_malloc((size_t)opts.maxJobs * sizeof *job_table);
2153 memset(job_table, 0, (size_t)opts.maxJobs * sizeof *job_table);
2154 job_table_end = job_table + opts.maxJobs;
2155 wantToken = 0;
2156
2157 aborting = ABORT_NONE;
2158 job_errors = 0;
2159
2160 /*
2161 * There is a non-zero chance that we already have children.
2162 * eg after 'make -f- <<EOF'
2163 * Since their termination causes a 'Child (pid) not in table'
2164 * message, Collect the status of any that are already dead, and
2165 * suppress the error message if there are any undead ones.
2166 */
2167 for (;;) {
2168 int rval, status;
2169 rval = waitpid((pid_t)-1, &status, WNOHANG);
2170 if (rval > 0)
2171 continue;
2172 if (rval == 0)
2173 lurking_children = TRUE;
2174 break;
2175 }
2176
2177 Shell_Init();
2178
2179 JobCreatePipe(&childExitJob, 3);
2180
2181 /* Preallocate enough for the maximum number of jobs. */
2182 fds = bmake_malloc(sizeof *fds *
2183 (npseudojobs + (size_t)opts.maxJobs) *
2184 nfds_per_job());
2185 allJobs = bmake_malloc(sizeof *allJobs *
2186 (npseudojobs + (size_t)opts.maxJobs) *
2187 nfds_per_job());
2188
2189 /* These are permanent entries and take slots 0 and 1 */
2190 watchfd(&tokenWaitJob);
2191 watchfd(&childExitJob);
2192
2193 sigemptyset(&caught_signals);
2194 /*
2195 * Install a SIGCHLD handler.
2196 */
2197 (void)bmake_signal(SIGCHLD, JobChildSig);
2198 sigaddset(&caught_signals, SIGCHLD);
2199
2200 /*
2201 * Catch the four signals that POSIX specifies if they aren't ignored.
2202 * JobPassSig will take care of calling JobInterrupt if appropriate.
2203 */
2204 AddSig(SIGINT, JobPassSig_int);
2205 AddSig(SIGHUP, JobPassSig_term);
2206 AddSig(SIGTERM, JobPassSig_term);
2207 AddSig(SIGQUIT, JobPassSig_term);
2208
2209 /*
2210 * There are additional signals that need to be caught and passed if
2211 * either the export system wants to be told directly of signals or if
2212 * we're giving each job its own process group (since then it won't get
2213 * signals from the terminal driver as we own the terminal)
2214 */
2215 AddSig(SIGTSTP, JobPassSig_suspend);
2216 AddSig(SIGTTOU, JobPassSig_suspend);
2217 AddSig(SIGTTIN, JobPassSig_suspend);
2218 AddSig(SIGWINCH, JobCondPassSig);
2219 AddSig(SIGCONT, JobContinueSig);
2220
2221 (void)Job_RunTarget(".BEGIN", NULL);
2222 /* Create the .END node now, even though no code in the unit tests
2223 * depends on it. See also Targ_GetEndNode in Compat_Run. */
2224 (void)Targ_GetEndNode();
2225 }
2226
2227 static void
2228 DelSig(int sig)
2229 {
2230 if (sigismember(&caught_signals, sig))
2231 (void)bmake_signal(sig, SIG_DFL);
2232 }
2233
2234 static void JobSigReset(void)
2235 {
2236 DelSig(SIGINT);
2237 DelSig(SIGHUP);
2238 DelSig(SIGQUIT);
2239 DelSig(SIGTERM);
2240 DelSig(SIGTSTP);
2241 DelSig(SIGTTOU);
2242 DelSig(SIGTTIN);
2243 DelSig(SIGWINCH);
2244 DelSig(SIGCONT);
2245 (void)bmake_signal(SIGCHLD, SIG_DFL);
2246 }
2247
2248 /* Find a shell in 'shells' given its name, or return NULL. */
2249 static Shell *
2250 FindShellByName(const char *name)
2251 {
2252 Shell *sh = shells;
2253 const Shell *shellsEnd = sh + sizeof shells / sizeof shells[0];
2254
2255 for (sh = shells; sh < shellsEnd; sh++) {
2256 if (strcmp(name, sh->name) == 0)
2257 return sh;
2258 }
2259 return NULL;
2260 }
2261
2262 /*
2263 * Parse a shell specification and set up 'shell', shellPath and
2264 * shellName appropriately.
2265 *
2266 * Input:
2267 * line The shell spec
2268 *
2269 * Results:
2270 * FALSE if the specification was incorrect.
2271 *
2272 * Side Effects:
2273 * 'shell' points to a Shell structure (either predefined or
2274 * created from the shell spec), shellPath is the full path of the
2275 * shell described by 'shell', while shellName is just the
2276 * final component of shellPath.
2277 *
2278 * Notes:
2279 * A shell specification consists of a .SHELL target, with dependency
2280 * operator, followed by a series of blank-separated words. Double
2281 * quotes can be used to use blanks in words. A backslash escapes
2282 * anything (most notably a double-quote and a space) and
2283 * provides the functionality it does in C. Each word consists of
2284 * keyword and value separated by an equal sign. There should be no
2285 * unnecessary spaces in the word. The keywords are as follows:
2286 * name Name of shell.
2287 * path Location of shell.
2288 * quiet Command to turn off echoing.
2289 * echo Command to turn echoing on
2290 * filter Result of turning off echoing that shouldn't be
2291 * printed.
2292 * echoFlag Flag to turn echoing on at the start
2293 * errFlag Flag to turn error checking on at the start
2294 * hasErrCtl True if shell has error checking control
2295 * newline String literal to represent a newline char
2296 * check Command to turn on error checking if hasErrCtl
2297 * is TRUE or template of command to echo a command
2298 * for which error checking is off if hasErrCtl is
2299 * FALSE.
2300 * ignore Command to turn off error checking if hasErrCtl
2301 * is TRUE or template of command to execute a
2302 * command so as to ignore any errors it returns if
2303 * hasErrCtl is FALSE.
2304 */
2305 Boolean
2306 Job_ParseShell(char *line)
2307 {
2308 Words wordsList;
2309 char **words;
2310 char **argv;
2311 size_t argc;
2312 char *path;
2313 Shell newShell;
2314 Boolean fullSpec = FALSE;
2315 Shell *sh;
2316
2317 pp_skip_whitespace(&line);
2318
2319 free(shellArgv);
2320
2321 memset(&newShell, 0, sizeof newShell);
2322
2323 /*
2324 * Parse the specification by keyword
2325 */
2326 wordsList = Str_Words(line, TRUE);
2327 words = wordsList.words;
2328 argc = wordsList.len;
2329 path = wordsList.freeIt;
2330 if (words == NULL) {
2331 Error("Unterminated quoted string [%s]", line);
2332 return FALSE;
2333 }
2334 shellArgv = path;
2335
2336 for (path = NULL, argv = words; argc != 0; argc--, argv++) {
2337 char *arg = *argv;
2338 if (strncmp(arg, "path=", 5) == 0) {
2339 path = arg + 5;
2340 } else if (strncmp(arg, "name=", 5) == 0) {
2341 newShell.name = arg + 5;
2342 } else {
2343 if (strncmp(arg, "quiet=", 6) == 0) {
2344 newShell.echoOff = arg + 6;
2345 } else if (strncmp(arg, "echo=", 5) == 0) {
2346 newShell.echoOn = arg + 5;
2347 } else if (strncmp(arg, "filter=", 7) == 0) {
2348 newShell.noPrint = arg + 7;
2349 newShell.noPrintLen = strlen(newShell.noPrint);
2350 } else if (strncmp(arg, "echoFlag=", 9) == 0) {
2351 newShell.echo = arg + 9;
2352 } else if (strncmp(arg, "errFlag=", 8) == 0) {
2353 newShell.exit = arg + 8;
2354 } else if (strncmp(arg, "hasErrCtl=", 10) == 0) {
2355 char c = arg[10];
2356 newShell.hasErrCtl = c == 'Y' || c == 'y' ||
2357 c == 'T' || c == 't';
2358 } else if (strncmp(arg, "newline=", 8) == 0) {
2359 newShell.newline = arg + 8;
2360 } else if (strncmp(arg, "check=", 6) == 0) {
2361 /* Before 2020-12-10, these two variables
2362 * had been a single variable. */
2363 newShell.errOn = arg + 6;
2364 newShell.echoCmd = arg + 6;
2365 } else if (strncmp(arg, "ignore=", 7) == 0) {
2366 /* Before 2020-12-10, these two variables
2367 * had been a single variable. */
2368 newShell.errOff = arg + 7;
2369 newShell.execIgnore = arg + 7;
2370 } else if (strncmp(arg, "errout=", 7) == 0) {
2371 newShell.errExit = arg + 7;
2372 } else if (strncmp(arg, "comment=", 8) == 0) {
2373 newShell.commentChar = arg[8];
2374 } else {
2375 Parse_Error(PARSE_FATAL,
2376 "Unknown keyword \"%s\"", arg);
2377 free(words);
2378 return FALSE;
2379 }
2380 fullSpec = TRUE;
2381 }
2382 }
2383
2384 if (path == NULL) {
2385 /*
2386 * If no path was given, the user wants one of the
2387 * pre-defined shells, yes? So we find the one s/he wants
2388 * with the help of FindShellByName and set things up the
2389 * right way. shellPath will be set up by Shell_Init.
2390 */
2391 if (newShell.name == NULL) {
2392 Parse_Error(PARSE_FATAL,
2393 "Neither path nor name specified");
2394 free(words);
2395 return FALSE;
2396 } else {
2397 if ((sh = FindShellByName(newShell.name)) == NULL) {
2398 Parse_Error(PARSE_WARNING,
2399 "%s: No matching shell", newShell.name);
2400 free(words);
2401 return FALSE;
2402 }
2403 shell = sh;
2404 shellName = newShell.name;
2405 if (shellPath != NULL) {
2406 /*
2407 * Shell_Init has already been called!
2408 * Do it again.
2409 */
2410 free(UNCONST(shellPath));
2411 shellPath = NULL;
2412 Shell_Init();
2413 }
2414 }
2415 } else {
2416 /*
2417 * The user provided a path. If s/he gave nothing else
2418 * (fullSpec is FALSE), try and find a matching shell in the
2419 * ones we know of. Else we just take the specification at
2420 * its word and copy it to a new location. In either case,
2421 * we need to record the path the user gave for the shell.
2422 */
2423 shellPath = path;
2424 path = strrchr(path, '/');
2425 if (path == NULL) {
2426 path = UNCONST(shellPath);
2427 } else {
2428 path++;
2429 }
2430 if (newShell.name != NULL) {
2431 shellName = newShell.name;
2432 } else {
2433 shellName = path;
2434 }
2435 if (!fullSpec) {
2436 if ((sh = FindShellByName(shellName)) == NULL) {
2437 Parse_Error(PARSE_WARNING,
2438 "%s: No matching shell", shellName);
2439 free(words);
2440 return FALSE;
2441 }
2442 shell = sh;
2443 } else {
2444 shell = bmake_malloc(sizeof *shell);
2445 *shell = newShell;
2446 }
2447 /* this will take care of shellErrFlag */
2448 Shell_Init();
2449 }
2450
2451 if (shell->echoOn && shell->echoOff)
2452 shell->hasEchoCtl = TRUE;
2453
2454 if (!shell->hasErrCtl) {
2455 if (shell->echoCmd == NULL)
2456 shell->echoCmd = "";
2457 if (shell->execIgnore == NULL)
2458 shell->execIgnore = "%s\n";
2459 }
2460
2461 /*
2462 * Do not free up the words themselves, since they might be in use
2463 * by the shell specification.
2464 */
2465 free(words);
2466 return TRUE;
2467 }
2468
2469 /*
2470 * Handle the receipt of an interrupt.
2471 *
2472 * All children are killed. Another job will be started if the .INTERRUPT
2473 * target is defined.
2474 *
2475 * Input:
2476 * runINTERRUPT Non-zero if commands for the .INTERRUPT target
2477 * should be executed
2478 * signo signal received
2479 */
2480 static void
2481 JobInterrupt(int runINTERRUPT, int signo)
2482 {
2483 Job *job; /* job descriptor in that element */
2484 GNode *interrupt; /* the node describing the .INTERRUPT target */
2485 sigset_t mask;
2486 GNode *gn;
2487
2488 aborting = ABORT_INTERRUPT;
2489
2490 JobSigLock(&mask);
2491
2492 for (job = job_table; job < job_table_end; job++) {
2493 if (job->status != JOB_ST_RUNNING)
2494 continue;
2495
2496 gn = job->node;
2497
2498 JobDeleteTarget(gn);
2499 if (job->pid) {
2500 DEBUG2(JOB,
2501 "JobInterrupt passing signal %d to child %d.\n",
2502 signo, job->pid);
2503 KILLPG(job->pid, signo);
2504 }
2505 }
2506
2507 JobSigUnlock(&mask);
2508
2509 if (runINTERRUPT && !opts.touchFlag) {
2510 interrupt = Targ_FindNode(".INTERRUPT");
2511 if (interrupt != NULL) {
2512 opts.ignoreErrors = FALSE;
2513 JobRun(interrupt);
2514 }
2515 }
2516 Trace_Log(MAKEINTR, NULL);
2517 exit(signo);
2518 }
2519
2520 /*
2521 * Do the final processing, i.e. run the commands attached to the .END target.
2522 *
2523 * Return the number of errors reported.
2524 */
2525 int
2526 Job_Finish(void)
2527 {
2528 GNode *endNode = Targ_GetEndNode();
2529 if (!Lst_IsEmpty(&endNode->commands) ||
2530 !Lst_IsEmpty(&endNode->children)) {
2531 if (job_errors != 0) {
2532 Error("Errors reported so .END ignored");
2533 } else {
2534 JobRun(endNode);
2535 }
2536 }
2537 return job_errors;
2538 }
2539
2540 /* Clean up any memory used by the jobs module. */
2541 void
2542 Job_End(void)
2543 {
2544 #ifdef CLEANUP
2545 free(shellArgv);
2546 #endif
2547 }
2548
2549 /*
2550 * Waits for all running jobs to finish and returns.
2551 * Sets 'aborting' to ABORT_WAIT to prevent other jobs from starting.
2552 */
2553 void
2554 Job_Wait(void)
2555 {
2556 aborting = ABORT_WAIT;
2557 while (jobTokensRunning != 0) {
2558 Job_CatchOutput();
2559 }
2560 aborting = ABORT_NONE;
2561 }
2562
2563 /*
2564 * Abort all currently running jobs without handling output or anything.
2565 * This function is to be called only in the event of a major error.
2566 * Most definitely NOT to be called from JobInterrupt.
2567 *
2568 * All children are killed, not just the firstborn.
2569 */
2570 void
2571 Job_AbortAll(void)
2572 {
2573 Job *job; /* the job descriptor in that element */
2574 int foo;
2575
2576 aborting = ABORT_ERROR;
2577
2578 if (jobTokensRunning != 0) {
2579 for (job = job_table; job < job_table_end; job++) {
2580 if (job->status != JOB_ST_RUNNING)
2581 continue;
2582 /*
2583 * kill the child process with increasingly drastic
2584 * signals to make darn sure it's dead.
2585 */
2586 KILLPG(job->pid, SIGINT);
2587 KILLPG(job->pid, SIGKILL);
2588 }
2589 }
2590
2591 /*
2592 * Catch as many children as want to report in at first, then give up
2593 */
2594 while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2595 continue;
2596 }
2597
2598 /*
2599 * Tries to restart stopped jobs if there are slots available.
2600 * Called in process context in response to a SIGCONT.
2601 */
2602 static void
2603 JobRestartJobs(void)
2604 {
2605 Job *job;
2606
2607 for (job = job_table; job < job_table_end; job++) {
2608 if (job->status == JOB_ST_RUNNING &&
2609 (make_suspended || job->suspended)) {
2610 DEBUG1(JOB, "Restarting stopped job pid %d.\n",
2611 job->pid);
2612 if (job->suspended) {
2613 (void)printf("*** [%s] Continued\n",
2614 job->node->name);
2615 (void)fflush(stdout);
2616 }
2617 job->suspended = FALSE;
2618 if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
2619 debug_printf("Failed to send SIGCONT to %d\n",
2620 job->pid);
2621 }
2622 }
2623 if (job->status == JOB_ST_FINISHED) {
2624 /*
2625 * Job exit deferred after calling waitpid() in a
2626 * signal handler
2627 */
2628 JobFinish(job, job->exit_status);
2629 }
2630 }
2631 make_suspended = FALSE;
2632 }
2633
2634 static void
2635 watchfd(Job *job)
2636 {
2637 if (job->inPollfd != NULL)
2638 Punt("Watching watched job");
2639
2640 fds[nJobs].fd = job->inPipe;
2641 fds[nJobs].events = POLLIN;
2642 allJobs[nJobs] = job;
2643 job->inPollfd = &fds[nJobs];
2644 nJobs++;
2645 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2646 if (useMeta) {
2647 fds[nJobs].fd = meta_job_fd(job);
2648 fds[nJobs].events = fds[nJobs].fd == -1 ? 0 : POLLIN;
2649 allJobs[nJobs] = job;
2650 nJobs++;
2651 }
2652 #endif
2653 }
2654
2655 static void
2656 clearfd(Job *job)
2657 {
2658 size_t i;
2659 if (job->inPollfd == NULL)
2660 Punt("Unwatching unwatched job");
2661 i = (size_t)(job->inPollfd - fds);
2662 nJobs--;
2663 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2664 if (useMeta) {
2665 /*
2666 * Sanity check: there should be two fds per job, so the job's
2667 * pollfd number should be even.
2668 */
2669 assert(nfds_per_job() == 2);
2670 if (i % 2)
2671 Punt("odd-numbered fd with meta");
2672 nJobs--;
2673 }
2674 #endif
2675 /*
2676 * Move last job in table into hole made by dead job.
2677 */
2678 if (nJobs != i) {
2679 fds[i] = fds[nJobs];
2680 allJobs[i] = allJobs[nJobs];
2681 allJobs[i]->inPollfd = &fds[i];
2682 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2683 if (useMeta) {
2684 fds[i + 1] = fds[nJobs + 1];
2685 allJobs[i + 1] = allJobs[nJobs + 1];
2686 }
2687 #endif
2688 }
2689 job->inPollfd = NULL;
2690 }
2691
2692 static int
2693 readyfd(Job *job)
2694 {
2695 if (job->inPollfd == NULL)
2696 Punt("Polling unwatched job");
2697 return (job->inPollfd->revents & POLLIN) != 0;
2698 }
2699
2700 /* Put a token (back) into the job pipe.
2701 * This allows a make process to start a build job. */
2702 static void
2703 JobTokenAdd(void)
2704 {
2705 char tok = JOB_TOKENS[aborting], tok1;
2706
2707 /* If we are depositing an error token flush everything else */
2708 while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2709 continue;
2710
2711 DEBUG3(JOB, "(%d) aborting %d, deposit token %c\n",
2712 getpid(), aborting, JOB_TOKENS[aborting]);
2713 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2714 continue;
2715 }
2716
2717 /* Prep the job token pipe in the root make process. */
2718 void
2719 Job_ServerStart(int max_tokens, int jp_0, int jp_1)
2720 {
2721 int i;
2722 char jobarg[64];
2723
2724 if (jp_0 >= 0 && jp_1 >= 0) {
2725 /* Pipe passed in from parent */
2726 tokenWaitJob.inPipe = jp_0;
2727 tokenWaitJob.outPipe = jp_1;
2728 (void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
2729 (void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
2730 return;
2731 }
2732
2733 JobCreatePipe(&tokenWaitJob, 15);
2734
2735 snprintf(jobarg, sizeof jobarg, "%d,%d",
2736 tokenWaitJob.inPipe, tokenWaitJob.outPipe);
2737
2738 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
2739 Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
2740
2741 /*
2742 * Preload the job pipe with one token per job, save the one
2743 * "extra" token for the primary job.
2744 *
2745 * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
2746 * larger than the write buffer size of the pipe, we will
2747 * deadlock here.
2748 */
2749 for (i = 1; i < max_tokens; i++)
2750 JobTokenAdd();
2751 }
2752
2753 /* Return a withdrawn token to the pool. */
2754 void
2755 Job_TokenReturn(void)
2756 {
2757 jobTokensRunning--;
2758 if (jobTokensRunning < 0)
2759 Punt("token botch");
2760 if (jobTokensRunning || JOB_TOKENS[aborting] != '+')
2761 JobTokenAdd();
2762 }
2763
2764 /*
2765 * Attempt to withdraw a token from the pool.
2766 *
2767 * If pool is empty, set wantToken so that we wake up when a token is
2768 * released.
2769 *
2770 * Returns TRUE if a token was withdrawn, and FALSE if the pool is currently
2771 * empty.
2772 */
2773 Boolean
2774 Job_TokenWithdraw(void)
2775 {
2776 char tok, tok1;
2777 ssize_t count;
2778
2779 wantToken = 0;
2780 DEBUG3(JOB, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
2781 getpid(), aborting, jobTokensRunning);
2782
2783 if (aborting != ABORT_NONE || (jobTokensRunning >= opts.maxJobs))
2784 return FALSE;
2785
2786 count = read(tokenWaitJob.inPipe, &tok, 1);
2787 if (count == 0)
2788 Fatal("eof on job pipe!");
2789 if (count < 0 && jobTokensRunning != 0) {
2790 if (errno != EAGAIN) {
2791 Fatal("job pipe read: %s", strerror(errno));
2792 }
2793 DEBUG1(JOB, "(%d) blocked for token\n", getpid());
2794 return FALSE;
2795 }
2796
2797 if (count == 1 && tok != '+') {
2798 /* make being aborted - remove any other job tokens */
2799 DEBUG2(JOB, "(%d) aborted by token %c\n", getpid(), tok);
2800 while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2801 continue;
2802 /* And put the stopper back */
2803 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
2804 errno == EAGAIN)
2805 continue;
2806 if (shouldDieQuietly(NULL, 1))
2807 exit(2);
2808 Fatal("A failure has been detected "
2809 "in another branch of the parallel make");
2810 }
2811
2812 if (count == 1 && jobTokensRunning == 0)
2813 /* We didn't want the token really */
2814 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
2815 errno == EAGAIN)
2816 continue;
2817
2818 jobTokensRunning++;
2819 DEBUG1(JOB, "(%d) withdrew token\n", getpid());
2820 return TRUE;
2821 }
2822
2823 /*
2824 * Run the named target if found. If a filename is specified, then set that
2825 * to the sources.
2826 *
2827 * Exits if the target fails.
2828 */
2829 Boolean
2830 Job_RunTarget(const char *target, const char *fname)
2831 {
2832 GNode *gn = Targ_FindNode(target);
2833 if (gn == NULL)
2834 return FALSE;
2835
2836 if (fname != NULL)
2837 Var_Set(ALLSRC, fname, gn);
2838
2839 JobRun(gn);
2840 /* XXX: Replace with GNode_IsError(gn) */
2841 if (gn->made == ERROR) {
2842 PrintOnError(gn, "\n\nStop.");
2843 exit(1);
2844 }
2845 return TRUE;
2846 }
2847
2848 #ifdef USE_SELECT
2849 int
2850 emul_poll(struct pollfd *fd, int nfd, int timeout)
2851 {
2852 fd_set rfds, wfds;
2853 int i, maxfd, nselect, npoll;
2854 struct timeval tv, *tvp;
2855 long usecs;
2856
2857 FD_ZERO(&rfds);
2858 FD_ZERO(&wfds);
2859
2860 maxfd = -1;
2861 for (i = 0; i < nfd; i++) {
2862 fd[i].revents = 0;
2863
2864 if (fd[i].events & POLLIN)
2865 FD_SET(fd[i].fd, &rfds);
2866
2867 if (fd[i].events & POLLOUT)
2868 FD_SET(fd[i].fd, &wfds);
2869
2870 if (fd[i].fd > maxfd)
2871 maxfd = fd[i].fd;
2872 }
2873
2874 if (maxfd >= FD_SETSIZE) {
2875 Punt("Ran out of fd_set slots; "
2876 "recompile with a larger FD_SETSIZE.");
2877 }
2878
2879 if (timeout < 0) {
2880 tvp = NULL;
2881 } else {
2882 usecs = timeout * 1000;
2883 tv.tv_sec = usecs / 1000000;
2884 tv.tv_usec = usecs % 1000000;
2885 tvp = &tv;
2886 }
2887
2888 nselect = select(maxfd + 1, &rfds, &wfds, NULL, tvp);
2889
2890 if (nselect <= 0)
2891 return nselect;
2892
2893 npoll = 0;
2894 for (i = 0; i < nfd; i++) {
2895 if (FD_ISSET(fd[i].fd, &rfds))
2896 fd[i].revents |= POLLIN;
2897
2898 if (FD_ISSET(fd[i].fd, &wfds))
2899 fd[i].revents |= POLLOUT;
2900
2901 if (fd[i].revents)
2902 npoll++;
2903 }
2904
2905 return npoll;
2906 }
2907 #endif /* USE_SELECT */
2908