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