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