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