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