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