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