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