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