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