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