job.c revision 1.438 1 /* $NetBSD: job.c,v 1.438 2021/11/28 17:20:39 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.438 2021/11/28 17:20:39 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 if (wr->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 StringListNode *ln;
1067
1068 if (!DEBUG(ERROR))
1069 return;
1070
1071 debug_printf("\n");
1072 debug_printf("*** Failed target: %s\n", job->node->name);
1073 debug_printf("*** Failed commands:\n");
1074 for (ln = job->node->commands.first; ln != NULL; ln = ln->next) {
1075 const char *unexpanded = (const char *)ln->datum;
1076 debug_printf("\t%s\n", unexpanded);
1077
1078 if (strchr(unexpanded, '$') != NULL) {
1079 char *expanded;
1080 (void)Var_Subst((const char *)ln->datum, job->node,
1081 VARE_WANTRES, &expanded);
1082 debug_printf("\t=> %s\n", expanded);
1083 free(expanded);
1084 }
1085 }
1086 }
1087
1088 static void
1089 JobFinishDoneExitedError(Job *job, int *inout_status)
1090 {
1091 SwitchOutputTo(job->node);
1092 #ifdef USE_META
1093 if (useMeta) {
1094 meta_job_error(job, job->node,
1095 job->ignerr, WEXITSTATUS(*inout_status));
1096 }
1097 #endif
1098 if (!shouldDieQuietly(job->node, -1)) {
1099 DebugFailedJob(job);
1100 (void)printf("*** [%s] Error code %d%s\n",
1101 job->node->name, WEXITSTATUS(*inout_status),
1102 job->ignerr ? " (ignored)" : "");
1103 }
1104
1105 if (job->ignerr)
1106 *inout_status = 0;
1107 else {
1108 if (deleteOnError)
1109 JobDeleteTarget(job->node);
1110 PrintOnError(job->node, NULL);
1111 }
1112 }
1113
1114 static void
1115 JobFinishDoneExited(Job *job, int *inout_status)
1116 {
1117 DEBUG2(JOB, "Process %d [%s] exited.\n", job->pid, job->node->name);
1118
1119 if (WEXITSTATUS(*inout_status) != 0)
1120 JobFinishDoneExitedError(job, inout_status);
1121 else if (DEBUG(JOB)) {
1122 SwitchOutputTo(job->node);
1123 (void)printf("*** [%s] Completed successfully\n",
1124 job->node->name);
1125 }
1126 }
1127
1128 static void
1129 JobFinishDoneSignaled(Job *job, int status)
1130 {
1131 SwitchOutputTo(job->node);
1132 DebugFailedJob(job);
1133 (void)printf("*** [%s] Signal %d\n", job->node->name, WTERMSIG(status));
1134 if (deleteOnError)
1135 JobDeleteTarget(job->node);
1136 }
1137
1138 static void
1139 JobFinishDone(Job *job, int *inout_status)
1140 {
1141 if (WIFEXITED(*inout_status))
1142 JobFinishDoneExited(job, inout_status);
1143 else
1144 JobFinishDoneSignaled(job, *inout_status);
1145
1146 (void)fflush(stdout);
1147 }
1148
1149 /*
1150 * Do final processing for the given job including updating parent nodes and
1151 * starting new jobs as available/necessary.
1152 *
1153 * Deferred commands for the job are placed on the .END node.
1154 *
1155 * If there was a serious error (job_errors != 0; not an ignored one), no more
1156 * jobs will be started.
1157 *
1158 * Input:
1159 * job job to finish
1160 * status sub-why job went away
1161 */
1162 static void
1163 JobFinish(Job *job, int status)
1164 {
1165 bool done, return_job_token;
1166
1167 DEBUG3(JOB, "JobFinish: %d [%s], status %d\n",
1168 job->pid, job->node->name, status);
1169
1170 if ((WIFEXITED(status) &&
1171 ((WEXITSTATUS(status) != 0 && !job->ignerr))) ||
1172 WIFSIGNALED(status)) {
1173 /* Finished because of an error. */
1174
1175 JobClosePipes(job);
1176 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1177 if (fclose(job->cmdFILE) != 0)
1178 Punt("Cannot write shell script for '%s': %s",
1179 job->node->name, strerror(errno));
1180 job->cmdFILE = NULL;
1181 }
1182 done = true;
1183
1184 } else if (WIFEXITED(status)) {
1185 /*
1186 * Deal with ignored errors in -B mode. We need to print a
1187 * message telling of the ignored error as well as to run
1188 * the next command.
1189 */
1190 done = WEXITSTATUS(status) != 0;
1191
1192 JobClosePipes(job);
1193
1194 } else {
1195 /* No need to close things down or anything. */
1196 done = false;
1197 }
1198
1199 if (done)
1200 JobFinishDone(job, &status);
1201
1202 #ifdef USE_META
1203 if (useMeta) {
1204 int meta_status = meta_job_finish(job);
1205 if (meta_status != 0 && status == 0)
1206 status = meta_status;
1207 }
1208 #endif
1209
1210 return_job_token = false;
1211
1212 Trace_Log(JOBEND, job);
1213 if (!job->special) {
1214 if (status != 0 ||
1215 (aborting == ABORT_ERROR) || aborting == ABORT_INTERRUPT)
1216 return_job_token = true;
1217 }
1218
1219 if (aborting != ABORT_ERROR && aborting != ABORT_INTERRUPT &&
1220 (status == 0)) {
1221 /*
1222 * As long as we aren't aborting and the job didn't return a
1223 * non-zero status that we shouldn't ignore, we call
1224 * Make_Update to update the parents.
1225 */
1226 JobSaveCommands(job);
1227 job->node->made = MADE;
1228 if (!job->special)
1229 return_job_token = true;
1230 Make_Update(job->node);
1231 job->status = JOB_ST_FREE;
1232 } else if (status != 0) {
1233 job_errors++;
1234 job->status = JOB_ST_FREE;
1235 }
1236
1237 if (job_errors > 0 && !opts.keepgoing && aborting != ABORT_INTERRUPT) {
1238 /* Prevent more jobs from getting started. */
1239 aborting = ABORT_ERROR;
1240 }
1241
1242 if (return_job_token)
1243 Job_TokenReturn();
1244
1245 if (aborting == ABORT_ERROR && jobTokensRunning == 0)
1246 Finish(job_errors);
1247 }
1248
1249 static void
1250 TouchRegular(GNode *gn)
1251 {
1252 const char *file = GNode_Path(gn);
1253 struct utimbuf times;
1254 int fd;
1255 char c;
1256
1257 times.actime = now;
1258 times.modtime = now;
1259 if (utime(file, ×) >= 0)
1260 return;
1261
1262 fd = open(file, O_RDWR | O_CREAT, 0666);
1263 if (fd < 0) {
1264 (void)fprintf(stderr, "*** couldn't touch %s: %s\n",
1265 file, strerror(errno));
1266 (void)fflush(stderr);
1267 return; /* XXX: What about propagating the error? */
1268 }
1269
1270 /* Last resort: update the file's time stamps in the traditional way.
1271 * XXX: This doesn't work for empty files, which are sometimes used
1272 * as marker files. */
1273 if (read(fd, &c, 1) == 1) {
1274 (void)lseek(fd, 0, SEEK_SET);
1275 while (write(fd, &c, 1) == -1 && errno == EAGAIN)
1276 continue;
1277 }
1278 (void)close(fd); /* XXX: What about propagating the error? */
1279 }
1280
1281 /*
1282 * Touch the given target. Called by JobStart when the -t flag was given.
1283 *
1284 * The modification date of the file is changed.
1285 * If the file did not exist, it is created.
1286 */
1287 void
1288 Job_Touch(GNode *gn, bool echo)
1289 {
1290 if (gn->type &
1291 (OP_JOIN | OP_USE | OP_USEBEFORE | OP_EXEC | OP_OPTIONAL |
1292 OP_SPECIAL | OP_PHONY)) {
1293 /*
1294 * These are "virtual" targets and should not really be
1295 * created.
1296 */
1297 return;
1298 }
1299
1300 if (echo || !GNode_ShouldExecute(gn)) {
1301 (void)fprintf(stdout, "touch %s\n", gn->name);
1302 (void)fflush(stdout);
1303 }
1304
1305 if (!GNode_ShouldExecute(gn))
1306 return;
1307
1308 if (gn->type & OP_ARCHV)
1309 Arch_Touch(gn);
1310 else if (gn->type & OP_LIB)
1311 Arch_TouchLib(gn);
1312 else
1313 TouchRegular(gn);
1314 }
1315
1316 /*
1317 * Make sure the given node has all the commands it needs.
1318 *
1319 * The node will have commands from the .DEFAULT rule added to it if it
1320 * needs them.
1321 *
1322 * Input:
1323 * gn The target whose commands need verifying
1324 * abortProc Function to abort with message
1325 *
1326 * Results:
1327 * true if the commands list is/was ok.
1328 */
1329 bool
1330 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1331 {
1332 if (GNode_IsTarget(gn))
1333 return true;
1334 if (!Lst_IsEmpty(&gn->commands))
1335 return true;
1336 if ((gn->type & OP_LIB) && !Lst_IsEmpty(&gn->children))
1337 return true;
1338
1339 /*
1340 * No commands. Look for .DEFAULT rule from which we might infer
1341 * commands.
1342 */
1343 if (defaultNode != NULL && !Lst_IsEmpty(&defaultNode->commands) &&
1344 !(gn->type & OP_SPECIAL)) {
1345 /*
1346 * The traditional Make only looks for a .DEFAULT if the node
1347 * was never the target of an operator, so that's what we do
1348 * too.
1349 *
1350 * The .DEFAULT node acts like a transformation rule, in that
1351 * gn also inherits any attributes or sources attached to
1352 * .DEFAULT itself.
1353 */
1354 Make_HandleUse(defaultNode, gn);
1355 Var_Set(gn, IMPSRC, GNode_VarTarget(gn));
1356 return true;
1357 }
1358
1359 Dir_UpdateMTime(gn, false);
1360 if (gn->mtime != 0 || (gn->type & OP_SPECIAL))
1361 return true;
1362
1363 /*
1364 * The node wasn't the target of an operator. We have no .DEFAULT
1365 * rule to go on and the target doesn't already exist. There's
1366 * nothing more we can do for this branch. If the -k flag wasn't
1367 * given, we stop in our tracks, otherwise we just don't update
1368 * this node's parents so they never get examined.
1369 */
1370
1371 if (gn->flags & FROM_DEPEND) {
1372 if (!Job_RunTarget(".STALE", gn->fname))
1373 fprintf(stdout,
1374 "%s: %s, %d: ignoring stale %s for %s\n",
1375 progname, gn->fname, gn->lineno, makeDependfile,
1376 gn->name);
1377 return true;
1378 }
1379
1380 if (gn->type & OP_OPTIONAL) {
1381 (void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
1382 progname, gn->name, "ignored");
1383 (void)fflush(stdout);
1384 return true;
1385 }
1386
1387 if (opts.keepgoing) {
1388 (void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
1389 progname, gn->name, "continuing");
1390 (void)fflush(stdout);
1391 return false;
1392 }
1393
1394 abortProc("%s: don't know how to make %s. Stop", progname, gn->name);
1395 return false;
1396 }
1397
1398 /*
1399 * Execute the shell for the given job.
1400 *
1401 * See Job_CatchOutput for handling the output of the shell.
1402 */
1403 static void
1404 JobExec(Job *job, char **argv)
1405 {
1406 int cpid; /* ID of new child */
1407 sigset_t mask;
1408
1409 if (DEBUG(JOB)) {
1410 int i;
1411
1412 debug_printf("Running %s\n", job->node->name);
1413 debug_printf("\tCommand: ");
1414 for (i = 0; argv[i] != NULL; i++) {
1415 debug_printf("%s ", argv[i]);
1416 }
1417 debug_printf("\n");
1418 }
1419
1420 /*
1421 * Some jobs produce no output and it's disconcerting to have
1422 * no feedback of their running (since they produce no output, the
1423 * banner with their name in it never appears). This is an attempt to
1424 * provide that feedback, even if nothing follows it.
1425 */
1426 if (job->echo)
1427 SwitchOutputTo(job->node);
1428
1429 /* No interruptions until this job is on the `jobs' list */
1430 JobSigLock(&mask);
1431
1432 /* Pre-emptively mark job running, pid still zero though */
1433 job->status = JOB_ST_RUNNING;
1434
1435 Var_ReexportVars();
1436
1437 cpid = vfork();
1438 if (cpid == -1)
1439 Punt("Cannot vfork: %s", strerror(errno));
1440
1441 if (cpid == 0) {
1442 /* Child */
1443 sigset_t tmask;
1444
1445 #ifdef USE_META
1446 if (useMeta) {
1447 meta_job_child(job);
1448 }
1449 #endif
1450 /*
1451 * Reset all signal handlers; this is necessary because we
1452 * also need to unblock signals before we exec(2).
1453 */
1454 JobSigReset();
1455
1456 /* Now unblock signals */
1457 sigemptyset(&tmask);
1458 JobSigUnlock(&tmask);
1459
1460 /*
1461 * Must duplicate the input stream down to the child's input
1462 * and reset it to the beginning (again). Since the stream
1463 * was marked close-on-exec, we must clear that bit in the
1464 * new input.
1465 */
1466 if (dup2(fileno(job->cmdFILE), 0) == -1)
1467 execDie("dup2", "job->cmdFILE");
1468 if (fcntl(0, F_SETFD, 0) == -1)
1469 execDie("fcntl clear close-on-exec", "stdin");
1470 if (lseek(0, 0, SEEK_SET) == -1)
1471 execDie("lseek to 0", "stdin");
1472
1473 if (job->node->type & (OP_MAKE | OP_SUBMAKE)) {
1474 /*
1475 * Pass job token pipe to submakes.
1476 */
1477 if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1)
1478 execDie("clear close-on-exec",
1479 "tokenWaitJob.inPipe");
1480 if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1)
1481 execDie("clear close-on-exec",
1482 "tokenWaitJob.outPipe");
1483 }
1484
1485 /*
1486 * Set up the child's output to be routed through the pipe
1487 * we've created for it.
1488 */
1489 if (dup2(job->outPipe, 1) == -1)
1490 execDie("dup2", "job->outPipe");
1491
1492 /*
1493 * The output channels are marked close on exec. This bit
1494 * was duplicated by the dup2(on some systems), so we have
1495 * to clear it before routing the shell's error output to
1496 * the same place as its standard output.
1497 */
1498 if (fcntl(1, F_SETFD, 0) == -1)
1499 execDie("clear close-on-exec", "stdout");
1500 if (dup2(1, 2) == -1)
1501 execDie("dup2", "1, 2");
1502
1503 /*
1504 * We want to switch the child into a different process
1505 * family so we can kill it and all its descendants in
1506 * one fell swoop, by killing its process family, but not
1507 * commit suicide.
1508 */
1509 #if defined(MAKE_NATIVE) || defined(HAVE_SETPGID)
1510 # if defined(SYSV)
1511 /* XXX: dsl - I'm sure this should be setpgrp()... */
1512 (void)setsid();
1513 # else
1514 (void)setpgid(0, getpid());
1515 # endif
1516 #endif
1517
1518 (void)execv(shellPath, argv);
1519 execDie("exec", shellPath);
1520 }
1521
1522 /* Parent, continuing after the child exec */
1523 job->pid = cpid;
1524
1525 Trace_Log(JOBSTART, job);
1526
1527 #ifdef USE_META
1528 if (useMeta) {
1529 meta_job_parent(job, cpid);
1530 }
1531 #endif
1532
1533 /*
1534 * Set the current position in the buffer to the beginning
1535 * and mark another stream to watch in the outputs mask
1536 */
1537 job->curPos = 0;
1538
1539 watchfd(job);
1540
1541 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1542 if (fclose(job->cmdFILE) != 0)
1543 Punt("Cannot write shell script for '%s': %s",
1544 job->node->name, strerror(errno));
1545 job->cmdFILE = NULL;
1546 }
1547
1548 /* Now that the job is actually running, add it to the table. */
1549 if (DEBUG(JOB)) {
1550 debug_printf("JobExec(%s): pid %d added to jobs table\n",
1551 job->node->name, job->pid);
1552 DumpJobs("job started");
1553 }
1554 JobSigUnlock(&mask);
1555 }
1556
1557 /* Create the argv needed to execute the shell for a given job. */
1558 static void
1559 JobMakeArgv(Job *job, char **argv)
1560 {
1561 int argc;
1562 static char args[10]; /* For merged arguments */
1563
1564 argv[0] = UNCONST(shellName);
1565 argc = 1;
1566
1567 if ((shell->errFlag != NULL && shell->errFlag[0] != '-') ||
1568 (shell->echoFlag != NULL && shell->echoFlag[0] != '-')) {
1569 /*
1570 * At least one of the flags doesn't have a minus before it,
1571 * so merge them together. Have to do this because the Bourne
1572 * shell thinks its second argument is a file to source.
1573 * Grrrr. Note the ten-character limitation on the combined
1574 * arguments.
1575 *
1576 * TODO: Research until when the above comments were
1577 * practically relevant.
1578 */
1579 (void)snprintf(args, sizeof args, "-%s%s",
1580 (job->ignerr ? "" :
1581 (shell->errFlag != NULL ? shell->errFlag : "")),
1582 (!job->echo ? "" :
1583 (shell->echoFlag != NULL ? shell->echoFlag : "")));
1584
1585 if (args[1] != '\0') {
1586 argv[argc] = args;
1587 argc++;
1588 }
1589 } else {
1590 if (!job->ignerr && shell->errFlag != NULL) {
1591 argv[argc] = UNCONST(shell->errFlag);
1592 argc++;
1593 }
1594 if (job->echo && shell->echoFlag != NULL) {
1595 argv[argc] = UNCONST(shell->echoFlag);
1596 argc++;
1597 }
1598 }
1599 argv[argc] = NULL;
1600 }
1601
1602 static void
1603 JobWriteShellCommands(Job *job, GNode *gn, bool *out_run)
1604 {
1605 /*
1606 * tfile is the name of a file into which all shell commands
1607 * are put. It is removed before the child shell is executed,
1608 * unless DEBUG(SCRIPT) is set.
1609 */
1610 char tfile[MAXPATHLEN];
1611 int tfd; /* File descriptor to the temp file */
1612
1613 tfd = Job_TempFile(TMPPAT, tfile, sizeof tfile);
1614
1615 job->cmdFILE = fdopen(tfd, "w+");
1616 if (job->cmdFILE == NULL)
1617 Punt("Could not fdopen %s", tfile);
1618
1619 (void)fcntl(fileno(job->cmdFILE), F_SETFD, FD_CLOEXEC);
1620
1621 #ifdef USE_META
1622 if (useMeta) {
1623 meta_job_start(job, gn);
1624 if (gn->type & OP_SILENT) /* might have changed */
1625 job->echo = false;
1626 }
1627 #endif
1628
1629 *out_run = JobWriteCommands(job);
1630 }
1631
1632 /*
1633 * Start a target-creation process going for the target described by gn.
1634 *
1635 * Results:
1636 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1637 * if there isn't actually anything left to do for the job and
1638 * JOB_RUNNING if the job has been started.
1639 *
1640 * Details:
1641 * A new Job node is created and added to the list of running
1642 * jobs. PMake is forked and a child shell created.
1643 *
1644 * NB: The return value is ignored by everyone.
1645 */
1646 static JobStartResult
1647 JobStart(GNode *gn, bool special)
1648 {
1649 Job *job; /* new job descriptor */
1650 char *argv[10]; /* Argument vector to shell */
1651 bool cmdsOK; /* true if the nodes commands were all right */
1652 bool run;
1653
1654 for (job = job_table; job < job_table_end; job++) {
1655 if (job->status == JOB_ST_FREE)
1656 break;
1657 }
1658 if (job >= job_table_end)
1659 Punt("JobStart no job slots vacant");
1660
1661 memset(job, 0, sizeof *job);
1662 job->node = gn;
1663 job->tailCmds = NULL;
1664 job->status = JOB_ST_SET_UP;
1665
1666 job->special = special || gn->type & OP_SPECIAL;
1667 job->ignerr = opts.ignoreErrors || gn->type & OP_IGNORE;
1668 job->echo = !(opts.beSilent || gn->type & OP_SILENT);
1669
1670 /*
1671 * Check the commands now so any attributes from .DEFAULT have a
1672 * chance to migrate to the node.
1673 */
1674 cmdsOK = Job_CheckCommands(gn, Error);
1675
1676 job->inPollfd = NULL;
1677
1678 if (Lst_IsEmpty(&gn->commands)) {
1679 job->cmdFILE = stdout;
1680 run = false;
1681
1682 /*
1683 * We're serious here, but if the commands were bogus, we're
1684 * also dead...
1685 */
1686 if (!cmdsOK) {
1687 PrintOnError(gn, NULL); /* provide some clue */
1688 DieHorribly();
1689 }
1690 } else if (((gn->type & OP_MAKE) && !opts.noRecursiveExecute) ||
1691 (!opts.noExecute && !opts.touchFlag)) {
1692 /*
1693 * The above condition looks very similar to
1694 * GNode_ShouldExecute but is subtly different. It prevents
1695 * that .MAKE targets are touched since these are usually
1696 * virtual targets.
1697 */
1698
1699 /*
1700 * We're serious here, but if the commands were bogus, we're
1701 * also dead...
1702 */
1703 if (!cmdsOK) {
1704 PrintOnError(gn, NULL); /* provide some clue */
1705 DieHorribly();
1706 }
1707
1708 JobWriteShellCommands(job, gn, &run);
1709 (void)fflush(job->cmdFILE);
1710 } else if (!GNode_ShouldExecute(gn)) {
1711 /*
1712 * Just write all the commands to stdout in one fell swoop.
1713 * This still sets up job->tailCmds correctly.
1714 */
1715 SwitchOutputTo(gn);
1716 job->cmdFILE = stdout;
1717 if (cmdsOK)
1718 JobWriteCommands(job);
1719 run = false;
1720 (void)fflush(job->cmdFILE);
1721 } else {
1722 Job_Touch(gn, job->echo);
1723 run = false;
1724 }
1725
1726 /* If we're not supposed to execute a shell, don't. */
1727 if (!run) {
1728 if (!job->special)
1729 Job_TokenReturn();
1730 /* Unlink and close the command file if we opened one */
1731 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1732 (void)fclose(job->cmdFILE);
1733 job->cmdFILE = NULL;
1734 }
1735
1736 /*
1737 * We only want to work our way up the graph if we aren't
1738 * here because the commands for the job were no good.
1739 */
1740 if (cmdsOK && aborting == ABORT_NONE) {
1741 JobSaveCommands(job);
1742 job->node->made = MADE;
1743 Make_Update(job->node);
1744 }
1745 job->status = JOB_ST_FREE;
1746 return cmdsOK ? JOB_FINISHED : JOB_ERROR;
1747 }
1748
1749 /*
1750 * Set up the control arguments to the shell. This is based on the
1751 * flags set earlier for this job.
1752 */
1753 JobMakeArgv(job, argv);
1754
1755 /* Create the pipe by which we'll get the shell's output. */
1756 JobCreatePipe(job, 3);
1757
1758 JobExec(job, argv);
1759 return JOB_RUNNING;
1760 }
1761
1762 /*
1763 * If the shell has an output filter (which only csh and ksh have by default),
1764 * print the output of the child process, skipping the noPrint text of the
1765 * shell.
1766 *
1767 * Return the part of the output that the calling function needs to output by
1768 * itself.
1769 */
1770 static char *
1771 PrintFilteredOutput(char *cp, char *endp) /* XXX: should all be const */
1772 {
1773 char *ecp; /* XXX: should be const */
1774
1775 if (shell->noPrint == NULL || shell->noPrint[0] == '\0')
1776 return cp;
1777
1778 /*
1779 * XXX: What happens if shell->noPrint occurs on the boundary of
1780 * the buffer? To work correctly in all cases, this should rather
1781 * be a proper stream filter instead of doing string matching on
1782 * selected chunks of the output.
1783 */
1784 while ((ecp = strstr(cp, shell->noPrint)) != NULL) {
1785 if (ecp != cp) {
1786 *ecp = '\0'; /* XXX: avoid writing to the buffer */
1787 /*
1788 * The only way there wouldn't be a newline after
1789 * this line is if it were the last in the buffer.
1790 * however, since the noPrint output comes after it,
1791 * there must be a newline, so we don't print one.
1792 */
1793 /* XXX: What about null bytes in the output? */
1794 (void)fprintf(stdout, "%s", cp);
1795 (void)fflush(stdout);
1796 }
1797 cp = ecp + shell->noPrintLen;
1798 if (cp == endp)
1799 break;
1800 cp++; /* skip over the (XXX: assumed) newline */
1801 pp_skip_whitespace(&cp);
1802 }
1803 return cp;
1804 }
1805
1806 /*
1807 * This function is called whenever there is something to read on the pipe.
1808 * We collect more output from the given job and store it in the job's
1809 * outBuf. If this makes up a line, we print it tagged by the job's
1810 * identifier, as necessary.
1811 *
1812 * In the output of the shell, the 'noPrint' lines are removed. If the
1813 * command is not alone on the line (the character after it is not \0 or
1814 * \n), we do print whatever follows it.
1815 *
1816 * Input:
1817 * job the job whose output needs printing
1818 * finish true if this is the last time we'll be called
1819 * for this job
1820 */
1821 static void
1822 CollectOutput(Job *job, bool finish)
1823 {
1824 bool gotNL; /* true if got a newline */
1825 bool fbuf; /* true if our buffer filled up */
1826 size_t nr; /* number of bytes read */
1827 size_t i; /* auxiliary index into outBuf */
1828 size_t max; /* limit for i (end of current data) */
1829 ssize_t nRead; /* (Temporary) number of bytes read */
1830
1831 /* Read as many bytes as will fit in the buffer. */
1832 again:
1833 gotNL = false;
1834 fbuf = false;
1835
1836 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1837 JOB_BUFSIZE - job->curPos);
1838 if (nRead < 0) {
1839 if (errno == EAGAIN)
1840 return;
1841 if (DEBUG(JOB)) {
1842 perror("CollectOutput(piperead)");
1843 }
1844 nr = 0;
1845 } else {
1846 nr = (size_t)nRead;
1847 }
1848
1849 /*
1850 * If we hit the end-of-file (the job is dead), we must flush its
1851 * remaining output, so pretend we read a newline if there's any
1852 * output remaining in the buffer.
1853 * Also clear the 'finish' flag so we stop looping.
1854 */
1855 if (nr == 0 && job->curPos != 0) {
1856 job->outBuf[job->curPos] = '\n';
1857 nr = 1;
1858 finish = false;
1859 } else if (nr == 0) {
1860 finish = false;
1861 }
1862
1863 /*
1864 * Look for the last newline in the bytes we just got. If there is
1865 * one, break out of the loop with 'i' as its index and gotNL set
1866 * true.
1867 */
1868 max = job->curPos + nr;
1869 for (i = job->curPos + nr - 1;
1870 i >= job->curPos && i != (size_t)-1; i--) {
1871 if (job->outBuf[i] == '\n') {
1872 gotNL = true;
1873 break;
1874 } else if (job->outBuf[i] == '\0') {
1875 /*
1876 * FIXME: The null characters are only replaced with
1877 * space _after_ the last '\n'. Everywhere else they
1878 * hide the rest of the command output.
1879 */
1880 job->outBuf[i] = ' ';
1881 }
1882 }
1883
1884 if (!gotNL) {
1885 job->curPos += nr;
1886 if (job->curPos == JOB_BUFSIZE) {
1887 /*
1888 * If we've run out of buffer space, we have no choice
1889 * but to print the stuff. sigh.
1890 */
1891 fbuf = true;
1892 i = job->curPos;
1893 }
1894 }
1895 if (gotNL || fbuf) {
1896 /*
1897 * Need to send the output to the screen. Null terminate it
1898 * first, overwriting the newline character if there was one.
1899 * So long as the line isn't one we should filter (according
1900 * to the shell description), we print the line, preceded
1901 * by a target banner if this target isn't the same as the
1902 * one for which we last printed something.
1903 * The rest of the data in the buffer are then shifted down
1904 * to the start of the buffer and curPos is set accordingly.
1905 */
1906 job->outBuf[i] = '\0';
1907 if (i >= job->curPos) {
1908 char *cp;
1909
1910 /*
1911 * FIXME: SwitchOutputTo should be here, according to
1912 * the comment above. But since PrintOutput does not
1913 * do anything in the default shell, this bug has gone
1914 * unnoticed until now.
1915 */
1916 cp = PrintFilteredOutput(job->outBuf, &job->outBuf[i]);
1917
1918 /*
1919 * There's still more in the output buffer. This time,
1920 * though, we know there's no newline at the end, so
1921 * we add one of our own free will.
1922 */
1923 if (*cp != '\0') {
1924 if (!opts.beSilent)
1925 SwitchOutputTo(job->node);
1926 #ifdef USE_META
1927 if (useMeta) {
1928 meta_job_output(job, cp,
1929 gotNL ? "\n" : "");
1930 }
1931 #endif
1932 (void)fprintf(stdout, "%s%s", cp,
1933 gotNL ? "\n" : "");
1934 (void)fflush(stdout);
1935 }
1936 }
1937 /*
1938 * max is the last offset still in the buffer. Move any
1939 * remaining characters to the start of the buffer and
1940 * update the end marker curPos.
1941 */
1942 if (i < max) {
1943 (void)memmove(job->outBuf, &job->outBuf[i + 1],
1944 max - (i + 1));
1945 job->curPos = max - (i + 1);
1946 } else {
1947 assert(i == max);
1948 job->curPos = 0;
1949 }
1950 }
1951 if (finish) {
1952 /*
1953 * If the finish flag is true, we must loop until we hit
1954 * end-of-file on the pipe. This is guaranteed to happen
1955 * eventually since the other end of the pipe is now closed
1956 * (we closed it explicitly and the child has exited). When
1957 * we do get an EOF, finish will be set false and we'll fall
1958 * through and out.
1959 */
1960 goto again;
1961 }
1962 }
1963
1964 static void
1965 JobRun(GNode *targ)
1966 {
1967 #if 0
1968 /*
1969 * Unfortunately it is too complicated to run .BEGIN, .END, and
1970 * .INTERRUPT job in the parallel job module. As of 2020-09-25,
1971 * unit-tests/deptgt-end-jobs.mk hangs in an endless loop.
1972 *
1973 * Running these jobs in compat mode also guarantees that these
1974 * jobs do not overlap with other unrelated jobs.
1975 */
1976 GNodeList lst = LST_INIT;
1977 Lst_Append(&lst, targ);
1978 (void)Make_Run(&lst);
1979 Lst_Done(&lst);
1980 JobStart(targ, true);
1981 while (jobTokensRunning != 0) {
1982 Job_CatchOutput();
1983 }
1984 #else
1985 Compat_Make(targ, targ);
1986 /* XXX: Replace with GNode_IsError(gn) */
1987 if (targ->made == ERROR) {
1988 PrintOnError(targ, "\n\nStop.");
1989 exit(1);
1990 }
1991 #endif
1992 }
1993
1994 /*
1995 * Handle the exit of a child. Called from Make_Make.
1996 *
1997 * The job descriptor is removed from the list of children.
1998 *
1999 * Notes:
2000 * We do waits, blocking or not, according to the wisdom of our
2001 * caller, until there are no more children to report. For each
2002 * job, call JobFinish to finish things off.
2003 */
2004 void
2005 Job_CatchChildren(void)
2006 {
2007 int pid; /* pid of dead child */
2008 int status; /* Exit/termination status */
2009
2010 /* Don't even bother if we know there's no one around. */
2011 if (jobTokensRunning == 0)
2012 return;
2013
2014 /* Have we received SIGCHLD since last call? */
2015 if (caught_sigchld == 0)
2016 return;
2017 caught_sigchld = 0;
2018
2019 while ((pid = waitpid((pid_t)-1, &status, WNOHANG | WUNTRACED)) > 0) {
2020 DEBUG2(JOB, "Process %d exited/stopped status %x.\n",
2021 pid, status);
2022 JobReapChild(pid, status, true);
2023 }
2024 }
2025
2026 /*
2027 * It is possible that wait[pid]() was called from elsewhere,
2028 * this lets us reap jobs regardless.
2029 */
2030 void
2031 JobReapChild(pid_t pid, int status, bool isJobs)
2032 {
2033 Job *job; /* job descriptor for dead child */
2034
2035 /* Don't even bother if we know there's no one around. */
2036 if (jobTokensRunning == 0)
2037 return;
2038
2039 job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
2040 if (job == NULL) {
2041 if (isJobs) {
2042 if (!lurking_children)
2043 Error("Child (%d) status %x not in table?",
2044 pid, status);
2045 }
2046 return; /* not ours */
2047 }
2048 if (WIFSTOPPED(status)) {
2049 DEBUG2(JOB, "Process %d (%s) stopped.\n",
2050 job->pid, job->node->name);
2051 if (!make_suspended) {
2052 switch (WSTOPSIG(status)) {
2053 case SIGTSTP:
2054 (void)printf("*** [%s] Suspended\n",
2055 job->node->name);
2056 break;
2057 case SIGSTOP:
2058 (void)printf("*** [%s] Stopped\n",
2059 job->node->name);
2060 break;
2061 default:
2062 (void)printf("*** [%s] Stopped -- signal %d\n",
2063 job->node->name, WSTOPSIG(status));
2064 }
2065 job->suspended = true;
2066 }
2067 (void)fflush(stdout);
2068 return;
2069 }
2070
2071 job->status = JOB_ST_FINISHED;
2072 job->exit_status = status;
2073
2074 JobFinish(job, status);
2075 }
2076
2077 /*
2078 * Catch the output from our children, if we're using pipes do so. Otherwise
2079 * just block time until we get a signal(most likely a SIGCHLD) since there's
2080 * no point in just spinning when there's nothing to do and the reaping of a
2081 * child can wait for a while.
2082 */
2083 void
2084 Job_CatchOutput(void)
2085 {
2086 int nready;
2087 Job *job;
2088 unsigned int i;
2089
2090 (void)fflush(stdout);
2091
2092 /* The first fd in the list is the job token pipe */
2093 do {
2094 nready = poll(fds + 1 - wantToken, fdsLen - 1 + wantToken,
2095 POLL_MSEC);
2096 } while (nready < 0 && errno == EINTR);
2097
2098 if (nready < 0)
2099 Punt("poll: %s", strerror(errno));
2100
2101 if (nready > 0 && readyfd(&childExitJob)) {
2102 char token = 0;
2103 ssize_t count;
2104 count = read(childExitJob.inPipe, &token, 1);
2105 if (count == 1) {
2106 if (token == DO_JOB_RESUME[0])
2107 /*
2108 * Complete relay requested from our SIGCONT
2109 * handler
2110 */
2111 JobRestartJobs();
2112 } else if (count == 0)
2113 Punt("unexpected eof on token pipe");
2114 else
2115 Punt("token pipe read: %s", strerror(errno));
2116 nready--;
2117 }
2118
2119 Job_CatchChildren();
2120 if (nready == 0)
2121 return;
2122
2123 for (i = npseudojobs * nfds_per_job(); i < fdsLen; i++) {
2124 if (fds[i].revents == 0)
2125 continue;
2126 job = jobByFdIndex[i];
2127 if (job->status == JOB_ST_RUNNING)
2128 CollectOutput(job, false);
2129 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2130 /*
2131 * With meta mode, we may have activity on the job's filemon
2132 * descriptor too, which at the moment is any pollfd other
2133 * than job->inPollfd.
2134 */
2135 if (useMeta && job->inPollfd != &fds[i]) {
2136 if (meta_job_event(job) <= 0) {
2137 fds[i].events = 0; /* never mind */
2138 }
2139 }
2140 #endif
2141 if (--nready == 0)
2142 return;
2143 }
2144 }
2145
2146 /*
2147 * Start the creation of a target. Basically a front-end for JobStart used by
2148 * the Make module.
2149 */
2150 void
2151 Job_Make(GNode *gn)
2152 {
2153 (void)JobStart(gn, false);
2154 }
2155
2156 static void
2157 InitShellNameAndPath(void)
2158 {
2159 shellName = shell->name;
2160
2161 #ifdef DEFSHELL_CUSTOM
2162 if (shellName[0] == '/') {
2163 shellPath = shellName;
2164 shellName = str_basename(shellPath);
2165 return;
2166 }
2167 #endif
2168
2169 shellPath = str_concat3(_PATH_DEFSHELLDIR, "/", shellName);
2170 }
2171
2172 void
2173 Shell_Init(void)
2174 {
2175 if (shellPath == NULL)
2176 InitShellNameAndPath();
2177
2178 Var_SetWithFlags(SCOPE_CMDLINE, ".SHELL", shellPath, VAR_SET_READONLY);
2179 if (shell->errFlag == NULL)
2180 shell->errFlag = "";
2181 if (shell->echoFlag == NULL)
2182 shell->echoFlag = "";
2183 if (shell->hasErrCtl && shell->errFlag[0] != '\0') {
2184 if (shellErrFlag != NULL &&
2185 strcmp(shell->errFlag, &shellErrFlag[1]) != 0) {
2186 free(shellErrFlag);
2187 shellErrFlag = NULL;
2188 }
2189 if (shellErrFlag == NULL) {
2190 size_t n = strlen(shell->errFlag) + 2;
2191
2192 shellErrFlag = bmake_malloc(n);
2193 if (shellErrFlag != NULL)
2194 snprintf(shellErrFlag, n, "-%s",
2195 shell->errFlag);
2196 }
2197 } else if (shellErrFlag != NULL) {
2198 free(shellErrFlag);
2199 shellErrFlag = NULL;
2200 }
2201 }
2202
2203 /*
2204 * Return the string literal that is used in the current command shell
2205 * to produce a newline character.
2206 */
2207 const char *
2208 Shell_GetNewline(void)
2209 {
2210 return shell->newline;
2211 }
2212
2213 void
2214 Job_SetPrefix(void)
2215 {
2216 if (targPrefix != NULL) {
2217 free(targPrefix);
2218 } else if (!Var_Exists(SCOPE_GLOBAL, MAKE_JOB_PREFIX)) {
2219 Global_Set(MAKE_JOB_PREFIX, "---");
2220 }
2221
2222 (void)Var_Subst("${" MAKE_JOB_PREFIX "}",
2223 SCOPE_GLOBAL, VARE_WANTRES, &targPrefix);
2224 /* TODO: handle errors */
2225 }
2226
2227 static void
2228 AddSig(int sig, SignalProc handler)
2229 {
2230 if (bmake_signal(sig, SIG_IGN) != SIG_IGN) {
2231 sigaddset(&caught_signals, sig);
2232 (void)bmake_signal(sig, handler);
2233 }
2234 }
2235
2236 /* Initialize the process module. */
2237 void
2238 Job_Init(void)
2239 {
2240 Job_SetPrefix();
2241 /* Allocate space for all the job info */
2242 job_table = bmake_malloc((size_t)opts.maxJobs * sizeof *job_table);
2243 memset(job_table, 0, (size_t)opts.maxJobs * sizeof *job_table);
2244 job_table_end = job_table + opts.maxJobs;
2245 wantToken = 0;
2246 caught_sigchld = 0;
2247
2248 aborting = ABORT_NONE;
2249 job_errors = 0;
2250
2251 /*
2252 * There is a non-zero chance that we already have children.
2253 * eg after 'make -f- <<EOF'
2254 * Since their termination causes a 'Child (pid) not in table'
2255 * message, Collect the status of any that are already dead, and
2256 * suppress the error message if there are any undead ones.
2257 */
2258 for (;;) {
2259 int rval, status;
2260 rval = waitpid((pid_t)-1, &status, WNOHANG);
2261 if (rval > 0)
2262 continue;
2263 if (rval == 0)
2264 lurking_children = true;
2265 break;
2266 }
2267
2268 Shell_Init();
2269
2270 JobCreatePipe(&childExitJob, 3);
2271
2272 {
2273 /* Preallocate enough for the maximum number of jobs. */
2274 size_t nfds = (npseudojobs + (size_t)opts.maxJobs) *
2275 nfds_per_job();
2276 fds = bmake_malloc(sizeof *fds * nfds);
2277 jobByFdIndex = bmake_malloc(sizeof *jobByFdIndex * nfds);
2278 }
2279
2280 /* These are permanent entries and take slots 0 and 1 */
2281 watchfd(&tokenWaitJob);
2282 watchfd(&childExitJob);
2283
2284 sigemptyset(&caught_signals);
2285 /*
2286 * Install a SIGCHLD handler.
2287 */
2288 (void)bmake_signal(SIGCHLD, JobChildSig);
2289 sigaddset(&caught_signals, SIGCHLD);
2290
2291 /*
2292 * Catch the four signals that POSIX specifies if they aren't ignored.
2293 * JobPassSig will take care of calling JobInterrupt if appropriate.
2294 */
2295 AddSig(SIGINT, JobPassSig_int);
2296 AddSig(SIGHUP, JobPassSig_term);
2297 AddSig(SIGTERM, JobPassSig_term);
2298 AddSig(SIGQUIT, JobPassSig_term);
2299
2300 /*
2301 * There are additional signals that need to be caught and passed if
2302 * either the export system wants to be told directly of signals or if
2303 * we're giving each job its own process group (since then it won't get
2304 * signals from the terminal driver as we own the terminal)
2305 */
2306 AddSig(SIGTSTP, JobPassSig_suspend);
2307 AddSig(SIGTTOU, JobPassSig_suspend);
2308 AddSig(SIGTTIN, JobPassSig_suspend);
2309 AddSig(SIGWINCH, JobCondPassSig);
2310 AddSig(SIGCONT, JobContinueSig);
2311
2312 (void)Job_RunTarget(".BEGIN", NULL);
2313 /* Create the .END node now, even though no code in the unit tests
2314 * depends on it. See also Targ_GetEndNode in Compat_Run. */
2315 (void)Targ_GetEndNode();
2316 }
2317
2318 static void
2319 DelSig(int sig)
2320 {
2321 if (sigismember(&caught_signals, sig) != 0)
2322 (void)bmake_signal(sig, SIG_DFL);
2323 }
2324
2325 static void
2326 JobSigReset(void)
2327 {
2328 DelSig(SIGINT);
2329 DelSig(SIGHUP);
2330 DelSig(SIGQUIT);
2331 DelSig(SIGTERM);
2332 DelSig(SIGTSTP);
2333 DelSig(SIGTTOU);
2334 DelSig(SIGTTIN);
2335 DelSig(SIGWINCH);
2336 DelSig(SIGCONT);
2337 (void)bmake_signal(SIGCHLD, SIG_DFL);
2338 }
2339
2340 /* Find a shell in 'shells' given its name, or return NULL. */
2341 static Shell *
2342 FindShellByName(const char *name)
2343 {
2344 Shell *sh = shells;
2345 const Shell *shellsEnd = sh + sizeof shells / sizeof shells[0];
2346
2347 for (sh = shells; sh < shellsEnd; sh++) {
2348 if (strcmp(name, sh->name) == 0)
2349 return sh;
2350 }
2351 return NULL;
2352 }
2353
2354 /*
2355 * Parse a shell specification and set up 'shell', shellPath and
2356 * shellName appropriately.
2357 *
2358 * Input:
2359 * line The shell spec
2360 *
2361 * Results:
2362 * false if the specification was incorrect.
2363 *
2364 * Side Effects:
2365 * 'shell' points to a Shell structure (either predefined or
2366 * created from the shell spec), shellPath is the full path of the
2367 * shell described by 'shell', while shellName is just the
2368 * final component of shellPath.
2369 *
2370 * Notes:
2371 * A shell specification consists of a .SHELL target, with dependency
2372 * operator, followed by a series of blank-separated words. Double
2373 * quotes can be used to use blanks in words. A backslash escapes
2374 * anything (most notably a double-quote and a space) and
2375 * provides the functionality it does in C. Each word consists of
2376 * keyword and value separated by an equal sign. There should be no
2377 * unnecessary spaces in the word. The keywords are as follows:
2378 * name Name of shell.
2379 * path Location of shell.
2380 * quiet Command to turn off echoing.
2381 * echo Command to turn echoing on
2382 * filter Result of turning off echoing that shouldn't be
2383 * printed.
2384 * echoFlag Flag to turn echoing on at the start
2385 * errFlag Flag to turn error checking on at the start
2386 * hasErrCtl True if shell has error checking control
2387 * newline String literal to represent a newline char
2388 * check Command to turn on error checking if hasErrCtl
2389 * is true or template of command to echo a command
2390 * for which error checking is off if hasErrCtl is
2391 * false.
2392 * ignore Command to turn off error checking if hasErrCtl
2393 * is true or template of command to execute a
2394 * command so as to ignore any errors it returns if
2395 * hasErrCtl is false.
2396 */
2397 bool
2398 Job_ParseShell(char *line)
2399 {
2400 Words wordsList;
2401 char **words;
2402 char **argv;
2403 size_t argc;
2404 char *path;
2405 Shell newShell;
2406 bool fullSpec = false;
2407 Shell *sh;
2408
2409 /* XXX: don't use line as an iterator variable */
2410 pp_skip_whitespace(&line);
2411
2412 free(shell_freeIt);
2413
2414 memset(&newShell, 0, sizeof newShell);
2415
2416 /*
2417 * Parse the specification by keyword
2418 */
2419 wordsList = Str_Words(line, true);
2420 words = wordsList.words;
2421 argc = wordsList.len;
2422 path = wordsList.freeIt;
2423 if (words == NULL) {
2424 Error("Unterminated quoted string [%s]", line);
2425 return false;
2426 }
2427 shell_freeIt = path;
2428
2429 for (path = NULL, argv = words; argc != 0; argc--, argv++) {
2430 char *arg = *argv;
2431 if (strncmp(arg, "path=", 5) == 0) {
2432 path = arg + 5;
2433 } else if (strncmp(arg, "name=", 5) == 0) {
2434 newShell.name = arg + 5;
2435 } else {
2436 if (strncmp(arg, "quiet=", 6) == 0) {
2437 newShell.echoOff = arg + 6;
2438 } else if (strncmp(arg, "echo=", 5) == 0) {
2439 newShell.echoOn = arg + 5;
2440 } else if (strncmp(arg, "filter=", 7) == 0) {
2441 newShell.noPrint = arg + 7;
2442 newShell.noPrintLen = strlen(newShell.noPrint);
2443 } else if (strncmp(arg, "echoFlag=", 9) == 0) {
2444 newShell.echoFlag = arg + 9;
2445 } else if (strncmp(arg, "errFlag=", 8) == 0) {
2446 newShell.errFlag = arg + 8;
2447 } else if (strncmp(arg, "hasErrCtl=", 10) == 0) {
2448 char c = arg[10];
2449 newShell.hasErrCtl = c == 'Y' || c == 'y' ||
2450 c == 'T' || c == 't';
2451 } else if (strncmp(arg, "newline=", 8) == 0) {
2452 newShell.newline = arg + 8;
2453 } else if (strncmp(arg, "check=", 6) == 0) {
2454 /* Before 2020-12-10, these two variables
2455 * had been a single variable. */
2456 newShell.errOn = arg + 6;
2457 newShell.echoTmpl = arg + 6;
2458 } else if (strncmp(arg, "ignore=", 7) == 0) {
2459 /* Before 2020-12-10, these two variables
2460 * had been a single variable. */
2461 newShell.errOff = arg + 7;
2462 newShell.runIgnTmpl = arg + 7;
2463 } else if (strncmp(arg, "errout=", 7) == 0) {
2464 newShell.runChkTmpl = arg + 7;
2465 } else if (strncmp(arg, "comment=", 8) == 0) {
2466 newShell.commentChar = arg[8];
2467 } else {
2468 Parse_Error(PARSE_FATAL,
2469 "Unknown keyword \"%s\"", arg);
2470 free(words);
2471 return false;
2472 }
2473 fullSpec = true;
2474 }
2475 }
2476
2477 if (path == NULL) {
2478 /*
2479 * If no path was given, the user wants one of the
2480 * pre-defined shells, yes? So we find the one s/he wants
2481 * with the help of FindShellByName and set things up the
2482 * right way. shellPath will be set up by Shell_Init.
2483 */
2484 if (newShell.name == NULL) {
2485 Parse_Error(PARSE_FATAL,
2486 "Neither path nor name specified");
2487 free(words);
2488 return false;
2489 } else {
2490 if ((sh = FindShellByName(newShell.name)) == NULL) {
2491 Parse_Error(PARSE_WARNING,
2492 "%s: No matching shell", newShell.name);
2493 free(words);
2494 return false;
2495 }
2496 shell = sh;
2497 shellName = newShell.name;
2498 if (shellPath != NULL) {
2499 /*
2500 * Shell_Init has already been called!
2501 * Do it again.
2502 */
2503 free(UNCONST(shellPath));
2504 shellPath = NULL;
2505 Shell_Init();
2506 }
2507 }
2508 } else {
2509 /*
2510 * The user provided a path. If s/he gave nothing else
2511 * (fullSpec is false), try and find a matching shell in the
2512 * ones we know of. Else we just take the specification at
2513 * its word and copy it to a new location. In either case,
2514 * we need to record the path the user gave for the shell.
2515 */
2516 shellPath = path;
2517 path = strrchr(path, '/');
2518 if (path == NULL) {
2519 path = UNCONST(shellPath);
2520 } else {
2521 path++;
2522 }
2523 if (newShell.name != NULL) {
2524 shellName = newShell.name;
2525 } else {
2526 shellName = path;
2527 }
2528 if (!fullSpec) {
2529 if ((sh = FindShellByName(shellName)) == NULL) {
2530 Parse_Error(PARSE_WARNING,
2531 "%s: No matching shell", shellName);
2532 free(words);
2533 return false;
2534 }
2535 shell = sh;
2536 } else {
2537 shell = bmake_malloc(sizeof *shell);
2538 *shell = newShell;
2539 }
2540 /* this will take care of shellErrFlag */
2541 Shell_Init();
2542 }
2543
2544 if (shell->echoOn != NULL && shell->echoOff != NULL)
2545 shell->hasEchoCtl = true;
2546
2547 if (!shell->hasErrCtl) {
2548 if (shell->echoTmpl == NULL)
2549 shell->echoTmpl = "";
2550 if (shell->runIgnTmpl == NULL)
2551 shell->runIgnTmpl = "%s\n";
2552 }
2553
2554 /*
2555 * Do not free up the words themselves, since they might be in use
2556 * by the shell specification.
2557 */
2558 free(words);
2559 return true;
2560 }
2561
2562 /*
2563 * Handle the receipt of an interrupt.
2564 *
2565 * All children are killed. Another job will be started if the .INTERRUPT
2566 * target is defined.
2567 *
2568 * Input:
2569 * runINTERRUPT Non-zero if commands for the .INTERRUPT target
2570 * should be executed
2571 * signo signal received
2572 */
2573 static void
2574 JobInterrupt(bool runINTERRUPT, int signo)
2575 {
2576 Job *job; /* job descriptor in that element */
2577 GNode *interrupt; /* the node describing the .INTERRUPT target */
2578 sigset_t mask;
2579 GNode *gn;
2580
2581 aborting = ABORT_INTERRUPT;
2582
2583 JobSigLock(&mask);
2584
2585 for (job = job_table; job < job_table_end; job++) {
2586 if (job->status != JOB_ST_RUNNING)
2587 continue;
2588
2589 gn = job->node;
2590
2591 JobDeleteTarget(gn);
2592 if (job->pid != 0) {
2593 DEBUG2(JOB,
2594 "JobInterrupt passing signal %d to child %d.\n",
2595 signo, job->pid);
2596 KILLPG(job->pid, signo);
2597 }
2598 }
2599
2600 JobSigUnlock(&mask);
2601
2602 if (runINTERRUPT && !opts.touchFlag) {
2603 interrupt = Targ_FindNode(".INTERRUPT");
2604 if (interrupt != NULL) {
2605 opts.ignoreErrors = false;
2606 JobRun(interrupt);
2607 }
2608 }
2609 Trace_Log(MAKEINTR, NULL);
2610 exit(signo); /* XXX: why signo? */
2611 }
2612
2613 /*
2614 * Do the final processing, i.e. run the commands attached to the .END target.
2615 *
2616 * Return the number of errors reported.
2617 */
2618 int
2619 Job_Finish(void)
2620 {
2621 GNode *endNode = Targ_GetEndNode();
2622 if (!Lst_IsEmpty(&endNode->commands) ||
2623 !Lst_IsEmpty(&endNode->children)) {
2624 if (job_errors != 0) {
2625 Error("Errors reported so .END ignored");
2626 } else {
2627 JobRun(endNode);
2628 }
2629 }
2630 return job_errors;
2631 }
2632
2633 /* Clean up any memory used by the jobs module. */
2634 void
2635 Job_End(void)
2636 {
2637 #ifdef CLEANUP
2638 free(shell_freeIt);
2639 #endif
2640 }
2641
2642 /*
2643 * Waits for all running jobs to finish and returns.
2644 * Sets 'aborting' to ABORT_WAIT to prevent other jobs from starting.
2645 */
2646 void
2647 Job_Wait(void)
2648 {
2649 aborting = ABORT_WAIT;
2650 while (jobTokensRunning != 0) {
2651 Job_CatchOutput();
2652 }
2653 aborting = ABORT_NONE;
2654 }
2655
2656 /*
2657 * Abort all currently running jobs without handling output or anything.
2658 * This function is to be called only in the event of a major error.
2659 * Most definitely NOT to be called from JobInterrupt.
2660 *
2661 * All children are killed, not just the firstborn.
2662 */
2663 void
2664 Job_AbortAll(void)
2665 {
2666 Job *job; /* the job descriptor in that element */
2667 int foo;
2668
2669 aborting = ABORT_ERROR;
2670
2671 if (jobTokensRunning != 0) {
2672 for (job = job_table; job < job_table_end; job++) {
2673 if (job->status != JOB_ST_RUNNING)
2674 continue;
2675 /*
2676 * kill the child process with increasingly drastic
2677 * signals to make darn sure it's dead.
2678 */
2679 KILLPG(job->pid, SIGINT);
2680 KILLPG(job->pid, SIGKILL);
2681 }
2682 }
2683
2684 /*
2685 * Catch as many children as want to report in at first, then give up
2686 */
2687 while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
2688 continue;
2689 }
2690
2691 /*
2692 * Tries to restart stopped jobs if there are slots available.
2693 * Called in process context in response to a SIGCONT.
2694 */
2695 static void
2696 JobRestartJobs(void)
2697 {
2698 Job *job;
2699
2700 for (job = job_table; job < job_table_end; job++) {
2701 if (job->status == JOB_ST_RUNNING &&
2702 (make_suspended || job->suspended)) {
2703 DEBUG1(JOB, "Restarting stopped job pid %d.\n",
2704 job->pid);
2705 if (job->suspended) {
2706 (void)printf("*** [%s] Continued\n",
2707 job->node->name);
2708 (void)fflush(stdout);
2709 }
2710 job->suspended = false;
2711 if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
2712 debug_printf("Failed to send SIGCONT to %d\n",
2713 job->pid);
2714 }
2715 }
2716 if (job->status == JOB_ST_FINISHED) {
2717 /*
2718 * Job exit deferred after calling waitpid() in a
2719 * signal handler
2720 */
2721 JobFinish(job, job->exit_status);
2722 }
2723 }
2724 make_suspended = false;
2725 }
2726
2727 static void
2728 watchfd(Job *job)
2729 {
2730 if (job->inPollfd != NULL)
2731 Punt("Watching watched job");
2732
2733 fds[fdsLen].fd = job->inPipe;
2734 fds[fdsLen].events = POLLIN;
2735 jobByFdIndex[fdsLen] = job;
2736 job->inPollfd = &fds[fdsLen];
2737 fdsLen++;
2738 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2739 if (useMeta) {
2740 fds[fdsLen].fd = meta_job_fd(job);
2741 fds[fdsLen].events = fds[fdsLen].fd == -1 ? 0 : POLLIN;
2742 jobByFdIndex[fdsLen] = job;
2743 fdsLen++;
2744 }
2745 #endif
2746 }
2747
2748 static void
2749 clearfd(Job *job)
2750 {
2751 size_t i;
2752 if (job->inPollfd == NULL)
2753 Punt("Unwatching unwatched job");
2754 i = (size_t)(job->inPollfd - fds);
2755 fdsLen--;
2756 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2757 if (useMeta) {
2758 /*
2759 * Sanity check: there should be two fds per job, so the job's
2760 * pollfd number should be even.
2761 */
2762 assert(nfds_per_job() == 2);
2763 if (i % 2 != 0)
2764 Punt("odd-numbered fd with meta");
2765 fdsLen--;
2766 }
2767 #endif
2768 /*
2769 * Move last job in table into hole made by dead job.
2770 */
2771 if (fdsLen != i) {
2772 fds[i] = fds[fdsLen];
2773 jobByFdIndex[i] = jobByFdIndex[fdsLen];
2774 jobByFdIndex[i]->inPollfd = &fds[i];
2775 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2776 if (useMeta) {
2777 fds[i + 1] = fds[fdsLen + 1];
2778 jobByFdIndex[i + 1] = jobByFdIndex[fdsLen + 1];
2779 }
2780 #endif
2781 }
2782 job->inPollfd = NULL;
2783 }
2784
2785 static bool
2786 readyfd(Job *job)
2787 {
2788 if (job->inPollfd == NULL)
2789 Punt("Polling unwatched job");
2790 return (job->inPollfd->revents & POLLIN) != 0;
2791 }
2792
2793 /*
2794 * Put a token (back) into the job pipe.
2795 * This allows a make process to start a build job.
2796 */
2797 static void
2798 JobTokenAdd(void)
2799 {
2800 char tok = JOB_TOKENS[aborting], tok1;
2801
2802 /* If we are depositing an error token flush everything else */
2803 while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2804 continue;
2805
2806 DEBUG3(JOB, "(%d) aborting %d, deposit token %c\n",
2807 getpid(), aborting, JOB_TOKENS[aborting]);
2808 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2809 continue;
2810 }
2811
2812 /* Get a temp file */
2813 int
2814 Job_TempFile(const char *pattern, char *tfile, size_t tfile_sz)
2815 {
2816 int fd;
2817 sigset_t mask;
2818
2819 JobSigLock(&mask);
2820 fd = mkTempFile(pattern, tfile, tfile_sz);
2821 if (tfile != NULL && !DEBUG(SCRIPT))
2822 unlink(tfile);
2823 JobSigUnlock(&mask);
2824
2825 return fd;
2826 }
2827
2828 /* Prep the job token pipe in the root make process. */
2829 void
2830 Job_ServerStart(int max_tokens, int jp_0, int jp_1)
2831 {
2832 int i;
2833 char jobarg[64];
2834
2835 if (jp_0 >= 0 && jp_1 >= 0) {
2836 /* Pipe passed in from parent */
2837 tokenWaitJob.inPipe = jp_0;
2838 tokenWaitJob.outPipe = jp_1;
2839 (void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
2840 (void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
2841 return;
2842 }
2843
2844 JobCreatePipe(&tokenWaitJob, 15);
2845
2846 snprintf(jobarg, sizeof jobarg, "%d,%d",
2847 tokenWaitJob.inPipe, tokenWaitJob.outPipe);
2848
2849 Global_Append(MAKEFLAGS, "-J");
2850 Global_Append(MAKEFLAGS, jobarg);
2851
2852 /*
2853 * Preload the job pipe with one token per job, save the one
2854 * "extra" token for the primary job.
2855 *
2856 * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
2857 * larger than the write buffer size of the pipe, we will
2858 * deadlock here.
2859 */
2860 for (i = 1; i < max_tokens; i++)
2861 JobTokenAdd();
2862 }
2863
2864 /* Return a withdrawn token to the pool. */
2865 void
2866 Job_TokenReturn(void)
2867 {
2868 jobTokensRunning--;
2869 if (jobTokensRunning < 0)
2870 Punt("token botch");
2871 if (jobTokensRunning != 0 || JOB_TOKENS[aborting] != '+')
2872 JobTokenAdd();
2873 }
2874
2875 /*
2876 * Attempt to withdraw a token from the pool.
2877 *
2878 * If pool is empty, set wantToken so that we wake up when a token is
2879 * released.
2880 *
2881 * Returns true if a token was withdrawn, and false if the pool is currently
2882 * empty.
2883 */
2884 bool
2885 Job_TokenWithdraw(void)
2886 {
2887 char tok, tok1;
2888 ssize_t count;
2889
2890 wantToken = 0;
2891 DEBUG3(JOB, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
2892 getpid(), aborting, jobTokensRunning);
2893
2894 if (aborting != ABORT_NONE || (jobTokensRunning >= opts.maxJobs))
2895 return false;
2896
2897 count = read(tokenWaitJob.inPipe, &tok, 1);
2898 if (count == 0)
2899 Fatal("eof on job pipe!");
2900 if (count < 0 && jobTokensRunning != 0) {
2901 if (errno != EAGAIN) {
2902 Fatal("job pipe read: %s", strerror(errno));
2903 }
2904 DEBUG1(JOB, "(%d) blocked for token\n", getpid());
2905 wantToken = 1;
2906 return false;
2907 }
2908
2909 if (count == 1 && tok != '+') {
2910 /* make being aborted - remove any other job tokens */
2911 DEBUG2(JOB, "(%d) aborted by token %c\n", getpid(), tok);
2912 while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2913 continue;
2914 /* And put the stopper back */
2915 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
2916 errno == EAGAIN)
2917 continue;
2918 if (shouldDieQuietly(NULL, 1))
2919 exit(6); /* we aborted */
2920 Fatal("A failure has been detected "
2921 "in another branch of the parallel make");
2922 }
2923
2924 if (count == 1 && jobTokensRunning == 0)
2925 /* We didn't want the token really */
2926 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
2927 errno == EAGAIN)
2928 continue;
2929
2930 jobTokensRunning++;
2931 DEBUG1(JOB, "(%d) withdrew token\n", getpid());
2932 return true;
2933 }
2934
2935 /*
2936 * Run the named target if found. If a filename is specified, then set that
2937 * to the sources.
2938 *
2939 * Exits if the target fails.
2940 */
2941 bool
2942 Job_RunTarget(const char *target, const char *fname)
2943 {
2944 GNode *gn = Targ_FindNode(target);
2945 if (gn == NULL)
2946 return false;
2947
2948 if (fname != NULL)
2949 Var_Set(gn, ALLSRC, fname);
2950
2951 JobRun(gn);
2952 /* XXX: Replace with GNode_IsError(gn) */
2953 if (gn->made == ERROR) {
2954 PrintOnError(gn, "\n\nStop.");
2955 exit(1);
2956 }
2957 return true;
2958 }
2959
2960 #ifdef USE_SELECT
2961 int
2962 emul_poll(struct pollfd *fd, int nfd, int timeout)
2963 {
2964 fd_set rfds, wfds;
2965 int i, maxfd, nselect, npoll;
2966 struct timeval tv, *tvp;
2967 long usecs;
2968
2969 FD_ZERO(&rfds);
2970 FD_ZERO(&wfds);
2971
2972 maxfd = -1;
2973 for (i = 0; i < nfd; i++) {
2974 fd[i].revents = 0;
2975
2976 if (fd[i].events & POLLIN)
2977 FD_SET(fd[i].fd, &rfds);
2978
2979 if (fd[i].events & POLLOUT)
2980 FD_SET(fd[i].fd, &wfds);
2981
2982 if (fd[i].fd > maxfd)
2983 maxfd = fd[i].fd;
2984 }
2985
2986 if (maxfd >= FD_SETSIZE) {
2987 Punt("Ran out of fd_set slots; "
2988 "recompile with a larger FD_SETSIZE.");
2989 }
2990
2991 if (timeout < 0) {
2992 tvp = NULL;
2993 } else {
2994 usecs = timeout * 1000;
2995 tv.tv_sec = usecs / 1000000;
2996 tv.tv_usec = usecs % 1000000;
2997 tvp = &tv;
2998 }
2999
3000 nselect = select(maxfd + 1, &rfds, &wfds, NULL, tvp);
3001
3002 if (nselect <= 0)
3003 return nselect;
3004
3005 npoll = 0;
3006 for (i = 0; i < nfd; i++) {
3007 if (FD_ISSET(fd[i].fd, &rfds))
3008 fd[i].revents |= POLLIN;
3009
3010 if (FD_ISSET(fd[i].fd, &wfds))
3011 fd[i].revents |= POLLOUT;
3012
3013 if (fd[i].revents)
3014 npoll++;
3015 }
3016
3017 return npoll;
3018 }
3019 #endif /* USE_SELECT */
3020