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