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