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