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