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