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