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