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