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