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