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