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