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