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