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