job.c revision 1.43 1 /* $NetBSD: job.c,v 1.43 2000/12/30 15:58:34 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.43 2000/12/30 15:58:34 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.43 2000/12/30 15:58:34 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 && !(job->flags & JOB_SPECIAL)) {
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 if (!(job->flags & JOB_SPECIAL))
1039 Job_TokenReturn();
1040 Make_Update(job->node);
1041 free((Address)job);
1042 } else if (*status != 0) {
1043 errors += 1;
1044 free((Address)job);
1045 }
1046 JobRestartJobs();
1047
1048 /*
1049 * Set aborting if any error.
1050 */
1051 if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
1052 /*
1053 * If we found any errors in this batch of children and the -k flag
1054 * wasn't given, we set the aborting flag so no more jobs get
1055 * started.
1056 */
1057 aborting = ABORT_ERROR;
1058 }
1059
1060 if ((aborting == ABORT_ERROR) && Job_Empty()) {
1061 /*
1062 * If we are aborting and the job table is now empty, we finish.
1063 */
1064 Finish(errors);
1065 }
1066 }
1067
1068 /*-
1069 *-----------------------------------------------------------------------
1070 * Job_Touch --
1071 * Touch the given target. Called by JobStart when the -t flag was
1072 * given
1073 *
1074 * Results:
1075 * None
1076 *
1077 * Side Effects:
1078 * The data modification of the file is changed. In addition, if the
1079 * file did not exist, it is created.
1080 *-----------------------------------------------------------------------
1081 */
1082 void
1083 Job_Touch(gn, silent)
1084 GNode *gn; /* the node of the file to touch */
1085 Boolean silent; /* TRUE if should not print messages */
1086 {
1087 int streamID; /* ID of stream opened to do the touch */
1088 struct utimbuf times; /* Times for utime() call */
1089
1090 if (gn->type & (OP_JOIN|OP_USE|OP_EXEC|OP_OPTIONAL|OP_PHONY)) {
1091 /*
1092 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets
1093 * and, as such, shouldn't really be created.
1094 */
1095 return;
1096 }
1097
1098 if (!silent || (noExecute && !(gn->type & OP_MAKE))) {
1099 (void) fprintf(stdout, "touch %s\n", gn->name);
1100 (void) fflush(stdout);
1101 }
1102
1103 if (noExecute && !(gn->type & OP_MAKE)) {
1104 return;
1105 }
1106
1107 if (gn->type & OP_ARCHV) {
1108 Arch_Touch(gn);
1109 } else if (gn->type & OP_LIB) {
1110 Arch_TouchLib(gn);
1111 } else {
1112 char *file = gn->path ? gn->path : gn->name;
1113
1114 times.actime = times.modtime = now;
1115 if (utime(file, ×) < 0){
1116 streamID = open(file, O_RDWR | O_CREAT, 0666);
1117
1118 if (streamID >= 0) {
1119 char c;
1120
1121 /*
1122 * Read and write a byte to the file to change the
1123 * modification time, then close the file.
1124 */
1125 if (read(streamID, &c, 1) == 1) {
1126 (void) lseek(streamID, (off_t)0, SEEK_SET);
1127 (void) write(streamID, &c, 1);
1128 }
1129
1130 (void) close(streamID);
1131 } else {
1132 (void) fprintf(stdout, "*** couldn't touch %s: %s",
1133 file, strerror(errno));
1134 (void) fflush(stdout);
1135 }
1136 }
1137 }
1138 }
1139
1140 /*-
1141 *-----------------------------------------------------------------------
1142 * Job_CheckCommands --
1143 * Make sure the given node has all the commands it needs.
1144 *
1145 * Results:
1146 * TRUE if the commands list is/was ok.
1147 *
1148 * Side Effects:
1149 * The node will have commands from the .DEFAULT rule added to it
1150 * if it needs them.
1151 *-----------------------------------------------------------------------
1152 */
1153 Boolean
1154 Job_CheckCommands(gn, abortProc)
1155 GNode *gn; /* The target whose commands need
1156 * verifying */
1157 void (*abortProc) __P((char *, ...));
1158 /* Function to abort with message */
1159 {
1160 if (OP_NOP(gn->type) && Lst_IsEmpty(gn->commands) &&
1161 (gn->type & OP_LIB) == 0) {
1162 /*
1163 * No commands. Look for .DEFAULT rule from which we might infer
1164 * commands
1165 */
1166 if ((DEFAULT != NILGNODE) && !Lst_IsEmpty(DEFAULT->commands)) {
1167 char *p1;
1168 /*
1169 * Make only looks for a .DEFAULT if the node was never the
1170 * target of an operator, so that's what we do too. If
1171 * a .DEFAULT was given, we substitute its commands for gn's
1172 * commands and set the IMPSRC variable to be the target's name
1173 * The DEFAULT node acts like a transformation rule, in that
1174 * gn also inherits any attributes or sources attached to
1175 * .DEFAULT itself.
1176 */
1177 Make_HandleUse(DEFAULT, gn);
1178 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn);
1179 if (p1)
1180 free(p1);
1181 } else if (Dir_MTime(gn) == 0) {
1182 /*
1183 * The node wasn't the target of an operator we have no .DEFAULT
1184 * rule to go on and the target doesn't already exist. There's
1185 * nothing more we can do for this branch. If the -k flag wasn't
1186 * given, we stop in our tracks, otherwise we just don't update
1187 * this node's parents so they never get examined.
1188 */
1189 static const char msg[] = "make: don't know how to make";
1190
1191 if (gn->type & OP_OPTIONAL) {
1192 (void) fprintf(stdout, "%s %s(ignored)\n", msg, gn->name);
1193 (void) fflush(stdout);
1194 } else if (keepgoing) {
1195 (void) fprintf(stdout, "%s %s(continuing)\n", msg, gn->name);
1196 (void) fflush(stdout);
1197 return FALSE;
1198 } else {
1199 (*abortProc)("%s %s. Stop", msg, gn->name);
1200 return FALSE;
1201 }
1202 }
1203 }
1204 return TRUE;
1205 }
1206 #ifdef RMT_WILL_WATCH
1207 /*-
1208 *-----------------------------------------------------------------------
1209 * JobLocalInput --
1210 * Handle a pipe becoming readable. Callback function for Rmt_Watch
1211 *
1212 * Results:
1213 * None
1214 *
1215 * Side Effects:
1216 * JobDoOutput is called.
1217 *
1218 *-----------------------------------------------------------------------
1219 */
1220 /*ARGSUSED*/
1221 static void
1222 JobLocalInput(stream, job)
1223 int stream; /* Stream that's ready (ignored) */
1224 Job *job; /* Job to which the stream belongs */
1225 {
1226 JobDoOutput(job, FALSE);
1227 }
1228 #endif /* RMT_WILL_WATCH */
1229
1230 /*-
1231 *-----------------------------------------------------------------------
1232 * JobExec --
1233 * Execute the shell for the given job. Called from JobStart and
1234 * JobRestart.
1235 *
1236 * Results:
1237 * None.
1238 *
1239 * Side Effects:
1240 * A shell is executed, outputs is altered and the Job structure added
1241 * to the job table.
1242 *
1243 *-----------------------------------------------------------------------
1244 */
1245 static void
1246 JobExec(job, argv)
1247 Job *job; /* Job to execute */
1248 char **argv;
1249 {
1250 int cpid; /* ID of new child */
1251
1252 if (DEBUG(JOB)) {
1253 int i;
1254
1255 (void) fprintf(stdout, "Running %s %sly\n", job->node->name,
1256 job->flags&JOB_REMOTE?"remote":"local");
1257 (void) fprintf(stdout, "\tCommand: ");
1258 for (i = 0; argv[i] != NULL; i++) {
1259 (void) fprintf(stdout, "%s ", argv[i]);
1260 }
1261 (void) fprintf(stdout, "\n");
1262 (void) fflush(stdout);
1263 }
1264
1265 /*
1266 * Some jobs produce no output and it's disconcerting to have
1267 * no feedback of their running (since they produce no output, the
1268 * banner with their name in it never appears). This is an attempt to
1269 * provide that feedback, even if nothing follows it.
1270 */
1271 if ((lastNode != job->node) && (job->flags & JOB_FIRST) &&
1272 !(job->flags & JOB_SILENT)) {
1273 MESSAGE(stdout, job->node);
1274 lastNode = job->node;
1275 }
1276
1277 #ifdef RMT_NO_EXEC
1278 if (job->flags & JOB_REMOTE) {
1279 goto jobExecFinish;
1280 }
1281 #endif /* RMT_NO_EXEC */
1282
1283 if ((cpid = vfork()) == -1) {
1284 Punt("Cannot vfork");
1285 } else if (cpid == 0) {
1286
1287 /*
1288 * Must duplicate the input stream down to the child's input and
1289 * reset it to the beginning (again). Since the stream was marked
1290 * close-on-exec, we must clear that bit in the new input.
1291 */
1292 if (dup2(FILENO(job->cmdFILE), 0) == -1)
1293 Punt("Cannot dup2: %s", strerror(errno));
1294 (void) fcntl(0, F_SETFD, 0);
1295 (void) lseek(0, (off_t)0, SEEK_SET);
1296
1297 if (job->node->type & OP_MAKE) {
1298 /*
1299 * Pass job token pipe to submakes.
1300 */
1301 fcntl(job_pipe[0], F_SETFD, 0);
1302 fcntl(job_pipe[1], F_SETFD, 0);
1303 }
1304
1305 if (usePipes) {
1306 /*
1307 * Set up the child's output to be routed through the pipe
1308 * we've created for it.
1309 */
1310 if (dup2(job->outPipe, 1) == -1)
1311 Punt("Cannot dup2: %s", strerror(errno));
1312 } else {
1313 /*
1314 * We're capturing output in a file, so we duplicate the
1315 * descriptor to the temporary file into the standard
1316 * output.
1317 */
1318 if (dup2(job->outFd, 1) == -1)
1319 Punt("Cannot dup2: %s", strerror(errno));
1320 }
1321 /*
1322 * The output channels are marked close on exec. This bit was
1323 * duplicated by the dup2 (on some systems), so we have to clear
1324 * it before routing the shell's error output to the same place as
1325 * its standard output.
1326 */
1327 (void) fcntl(1, F_SETFD, 0);
1328 if (dup2(1, 2) == -1)
1329 Punt("Cannot dup2: %s", strerror(errno));
1330
1331 #ifdef USE_PGRP
1332 /*
1333 * We want to switch the child into a different process family so
1334 * we can kill it and all its descendants in one fell swoop,
1335 * by killing its process family, but not commit suicide.
1336 */
1337 # if defined(SYSV)
1338 (void) setsid();
1339 # else
1340 (void) setpgid(0, getpid());
1341 # endif
1342 #endif /* USE_PGRP */
1343
1344 #ifdef REMOTE
1345 if (job->flags & JOB_REMOTE) {
1346 Rmt_Exec(shellPath, argv, FALSE);
1347 } else
1348 #endif /* REMOTE */
1349 (void) execv(shellPath, argv);
1350
1351 (void) write(2, "Could not execute shell\n",
1352 sizeof("Could not execute shell"));
1353 _exit(1);
1354 } else {
1355 #ifdef REMOTE
1356 sigset_t nmask, omask;
1357 sigemptyset(&nmask);
1358 sigaddset(&nmask, SIGCHLD);
1359 sigprocmask(SIG_BLOCK, &nmask, &omask);
1360 #endif
1361 job->pid = cpid;
1362
1363 Trace_Log(JOBSTART, job);
1364
1365 if (usePipes && (job->flags & JOB_FIRST)) {
1366 /*
1367 * The first time a job is run for a node, we set the current
1368 * position in the buffer to the beginning and mark another
1369 * stream to watch in the outputs mask
1370 */
1371 job->curPos = 0;
1372
1373 #ifdef RMT_WILL_WATCH
1374 Rmt_Watch(job->inPipe, JobLocalInput, job);
1375 #else
1376 #ifdef USE_SELECT
1377 FD_SET(job->inPipe, &outputs);
1378 #else
1379 watchfd(job);
1380 #endif
1381 #endif /* RMT_WILL_WATCH */
1382 }
1383
1384 if (job->flags & JOB_REMOTE) {
1385 #ifndef REMOTE
1386 job->rmtID = 0;
1387 #else
1388 job->rmtID = Rmt_LastID(job->pid);
1389 #endif /* REMOTE */
1390 } else {
1391 nLocal += 1;
1392 /*
1393 * XXX: Used to not happen if REMOTE. Why?
1394 */
1395 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1396 (void) fclose(job->cmdFILE);
1397 job->cmdFILE = NULL;
1398 }
1399 }
1400 #ifdef REMOTE
1401 sigprocmask(SIG_SETMASK, &omask, NULL);
1402 #endif
1403 }
1404
1405 #ifdef RMT_NO_EXEC
1406 jobExecFinish:
1407 #endif
1408 /*
1409 * Now the job is actually running, add it to the table.
1410 */
1411 nJobs += 1;
1412 (void) Lst_AtEnd(jobs, (ClientData)job);
1413 }
1414
1415 /*-
1416 *-----------------------------------------------------------------------
1417 * JobMakeArgv --
1418 * Create the argv needed to execute the shell for a given job.
1419 *
1420 *
1421 * Results:
1422 *
1423 * Side Effects:
1424 *
1425 *-----------------------------------------------------------------------
1426 */
1427 static void
1428 JobMakeArgv(job, argv)
1429 Job *job;
1430 char **argv;
1431 {
1432 int argc;
1433 static char args[10]; /* For merged arguments */
1434
1435 argv[0] = shellName;
1436 argc = 1;
1437
1438 if ((commandShell->exit && (*commandShell->exit != '-')) ||
1439 (commandShell->echo && (*commandShell->echo != '-')))
1440 {
1441 /*
1442 * At least one of the flags doesn't have a minus before it, so
1443 * merge them together. Have to do this because the *(&(@*#*&#$#
1444 * Bourne shell thinks its second argument is a file to source.
1445 * Grrrr. Note the ten-character limitation on the combined arguments.
1446 */
1447 (void)snprintf(args, sizeof(args), "-%s%s",
1448 ((job->flags & JOB_IGNERR) ? "" :
1449 (commandShell->exit ? commandShell->exit : "")),
1450 ((job->flags & JOB_SILENT) ? "" :
1451 (commandShell->echo ? commandShell->echo : "")));
1452
1453 if (args[1]) {
1454 argv[argc] = args;
1455 argc++;
1456 }
1457 } else {
1458 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1459 argv[argc] = commandShell->exit;
1460 argc++;
1461 }
1462 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1463 argv[argc] = commandShell->echo;
1464 argc++;
1465 }
1466 }
1467 argv[argc] = NULL;
1468 }
1469
1470 /*-
1471 *-----------------------------------------------------------------------
1472 * JobRestart --
1473 * Restart a job that stopped for some reason.
1474 *
1475 * Results:
1476 * None.
1477 *
1478 *-----------------------------------------------------------------------
1479 */
1480 static void
1481 JobRestart(job)
1482 Job *job; /* Job to restart */
1483 {
1484 #ifdef REMOTE
1485 int host;
1486 #endif
1487
1488 if (job->flags & JOB_REMIGRATE) {
1489 if (
1490 #ifdef REMOTE
1491 verboseRemigrates ||
1492 #endif
1493 DEBUG(JOB)) {
1494 (void) fprintf(stdout, "*** remigrating %x(%s)\n",
1495 job->pid, job->node->name);
1496 (void) fflush(stdout);
1497 }
1498
1499 #ifdef REMOTE
1500 if (!Rmt_ReExport(job->pid, job->node, &host)) {
1501 if (verboseRemigrates || DEBUG(JOB)) {
1502 (void) fprintf(stdout, "*** couldn't migrate...\n");
1503 (void) fflush(stdout);
1504 }
1505 #endif
1506 if (nLocal != maxLocal) {
1507 /*
1508 * Job cannot be remigrated, but there's room on the local
1509 * machine, so resume the job and note that another
1510 * local job has started.
1511 */
1512 if (
1513 #ifdef REMOTE
1514 verboseRemigrates ||
1515 #endif
1516 DEBUG(JOB)) {
1517 (void) fprintf(stdout, "*** resuming on local machine\n");
1518 (void) fflush(stdout);
1519 }
1520 KILL(job->pid, SIGCONT);
1521 nLocal +=1;
1522 #ifdef REMOTE
1523 job->flags &= ~(JOB_REMIGRATE|JOB_RESUME|JOB_REMOTE);
1524 job->flags |= JOB_CONTINUING;
1525 #else
1526 job->flags &= ~(JOB_REMIGRATE|JOB_RESUME);
1527 #endif
1528 } else {
1529 /*
1530 * Job cannot be restarted. Mark the table as full and
1531 * place the job back on the list of stopped jobs.
1532 */
1533 if (
1534 #ifdef REMOTE
1535 verboseRemigrates ||
1536 #endif
1537 DEBUG(JOB)) {
1538 (void) fprintf(stdout, "*** holding\n");
1539 (void) fflush(stdout);
1540 }
1541 (void)Lst_AtFront(stoppedJobs, (ClientData)job);
1542 return;
1543 }
1544 #ifdef REMOTE
1545 } else {
1546 /*
1547 * Clear out the remigrate and resume flags. Set the continuing
1548 * flag so we know later on that the process isn't exiting just
1549 * because of a signal.
1550 */
1551 job->flags &= ~(JOB_REMIGRATE|JOB_RESUME);
1552 job->flags |= JOB_CONTINUING;
1553 job->rmtID = host;
1554 }
1555 #endif
1556
1557 (void)Lst_AtEnd(jobs, (ClientData)job);
1558 nJobs += 1;
1559 } else if (job->flags & JOB_RESTART) {
1560 /*
1561 * Set up the control arguments to the shell. This is based on the
1562 * flags set earlier for this job. If the JOB_IGNERR flag is clear,
1563 * the 'exit' flag of the commandShell is used to cause it to exit
1564 * upon receiving an error. If the JOB_SILENT flag is clear, the
1565 * 'echo' flag of the commandShell is used to get it to start echoing
1566 * as soon as it starts processing commands.
1567 */
1568 char *argv[10];
1569
1570 JobMakeArgv(job, argv);
1571
1572 if (DEBUG(JOB)) {
1573 (void) fprintf(stdout, "Restarting %s...", job->node->name);
1574 (void) fflush(stdout);
1575 }
1576 #ifdef REMOTE
1577 if ((job->node->type&OP_NOEXPORT) ||
1578 (nLocal < maxLocal && runLocalFirst)
1579 # ifdef RMT_NO_EXEC
1580 || !Rmt_Export(shellPath, argv, job)
1581 # else
1582 || !Rmt_Begin(shellPath, argv, job->node)
1583 # endif
1584 #endif
1585 {
1586 if (((nLocal >= maxLocal) && !(job->flags & JOB_SPECIAL))) {
1587 /*
1588 * Can't be exported and not allowed to run locally -- put it
1589 * back on the hold queue and mark the table full
1590 */
1591 if (DEBUG(JOB)) {
1592 (void) fprintf(stdout, "holding\n");
1593 (void) fflush(stdout);
1594 }
1595 (void)Lst_AtFront(stoppedJobs, (ClientData)job);
1596 return;
1597 } else {
1598 /*
1599 * Job may be run locally.
1600 */
1601 if (DEBUG(JOB)) {
1602 (void) fprintf(stdout, "running locally\n");
1603 (void) fflush(stdout);
1604 }
1605 job->flags &= ~JOB_REMOTE;
1606 }
1607 }
1608 #ifdef REMOTE
1609 else {
1610 /*
1611 * Can be exported. Hooray!
1612 */
1613 if (DEBUG(JOB)) {
1614 (void) fprintf(stdout, "exporting\n");
1615 (void) fflush(stdout);
1616 }
1617 job->flags |= JOB_REMOTE;
1618 }
1619 #endif
1620 JobExec(job, argv);
1621 } else {
1622 /*
1623 * The job has stopped and needs to be restarted. Why it stopped,
1624 * we don't know...
1625 */
1626 if (DEBUG(JOB)) {
1627 (void) fprintf(stdout, "Resuming %s...", job->node->name);
1628 (void) fflush(stdout);
1629 }
1630 if (((job->flags & JOB_REMOTE) ||
1631 (nLocal < maxLocal) ||
1632 #ifdef REMOTE
1633 (((job->flags & JOB_SPECIAL) &&
1634 (job->node->type & OP_NOEXPORT)) &&
1635 (maxLocal == 0))) &&
1636 #else
1637 ((job->flags & JOB_SPECIAL) &&
1638 (maxLocal == 0))) &&
1639 #endif
1640 (nJobs != maxJobs))
1641 {
1642 /*
1643 * If the job is remote, it's ok to resume it as long as the
1644 * maximum concurrency won't be exceeded. If it's local and
1645 * we haven't reached the local concurrency limit already (or the
1646 * job must be run locally and maxLocal is 0), it's also ok to
1647 * resume it.
1648 */
1649 Boolean error;
1650 int status;
1651
1652 #ifdef RMT_WANTS_SIGNALS
1653 if (job->flags & JOB_REMOTE) {
1654 error = !Rmt_Signal(job, SIGCONT);
1655 } else
1656 #endif /* RMT_WANTS_SIGNALS */
1657 error = (KILL(job->pid, SIGCONT) != 0);
1658
1659 if (!error) {
1660 /*
1661 * Make sure the user knows we've continued the beast and
1662 * actually put the thing in the job table.
1663 */
1664 job->flags |= JOB_CONTINUING;
1665 status = W_STOPCODE(SIGCONT);
1666 JobFinish(job, &status);
1667
1668 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1669 if (DEBUG(JOB)) {
1670 (void) fprintf(stdout, "done\n");
1671 (void) fflush(stdout);
1672 }
1673 } else {
1674 Error("couldn't resume %s: %s",
1675 job->node->name, strerror(errno));
1676 status = W_EXITCODE(1, 0);
1677 JobFinish(job, &status);
1678 }
1679 } else {
1680 /*
1681 * Job cannot be restarted. Mark the table as full and
1682 * place the job back on the list of stopped jobs.
1683 */
1684 if (DEBUG(JOB)) {
1685 (void) fprintf(stdout, "table full\n");
1686 (void) fflush(stdout);
1687 }
1688 (void) Lst_AtFront(stoppedJobs, (ClientData)job);
1689 }
1690 }
1691 }
1692
1693 /*-
1694 *-----------------------------------------------------------------------
1695 * JobStart --
1696 * Start a target-creation process going for the target described
1697 * by the graph node gn.
1698 *
1699 * Results:
1700 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1701 * if there isn't actually anything left to do for the job and
1702 * JOB_RUNNING if the job has been started.
1703 *
1704 * Side Effects:
1705 * A new Job node is created and added to the list of running
1706 * jobs. PMake is forked and a child shell created.
1707 *-----------------------------------------------------------------------
1708 */
1709 static int
1710 JobStart(gn, flags, previous)
1711 GNode *gn; /* target to create */
1712 int flags; /* flags for the job to override normal ones.
1713 * e.g. JOB_SPECIAL or JOB_IGNDOTS */
1714 Job *previous; /* The previous Job structure for this node,
1715 * if any. */
1716 {
1717 register Job *job; /* new job descriptor */
1718 char *argv[10]; /* Argument vector to shell */
1719 Boolean cmdsOK; /* true if the nodes commands were all right */
1720 Boolean local; /* Set true if the job was run locally */
1721 Boolean noExec; /* Set true if we decide not to run the job */
1722 int tfd; /* File descriptor to the temp file */
1723
1724 if (previous != NULL) {
1725 previous->flags &= ~(JOB_FIRST|JOB_IGNERR|JOB_SILENT|JOB_REMOTE);
1726 job = previous;
1727 } else {
1728 job = (Job *) emalloc(sizeof(Job));
1729 if (job == NULL) {
1730 Punt("JobStart out of memory");
1731 }
1732 flags |= JOB_FIRST;
1733 }
1734
1735 job->node = gn;
1736 job->tailCmds = NILLNODE;
1737
1738 /*
1739 * Set the initial value of the flags for this job based on the global
1740 * ones and the node's attributes... Any flags supplied by the caller
1741 * are also added to the field.
1742 */
1743 job->flags = 0;
1744 if (Targ_Ignore(gn)) {
1745 job->flags |= JOB_IGNERR;
1746 }
1747 if (Targ_Silent(gn)) {
1748 job->flags |= JOB_SILENT;
1749 }
1750 job->flags |= flags;
1751
1752 /*
1753 * Check the commands now so any attributes from .DEFAULT have a chance
1754 * to migrate to the node
1755 */
1756 if (!compatMake && job->flags & JOB_FIRST) {
1757 cmdsOK = Job_CheckCommands(gn, Error);
1758 } else {
1759 cmdsOK = TRUE;
1760 }
1761
1762 #ifndef RMT_WILL_WATCH
1763 #ifndef USE_SELECT
1764 job->inPollfd = NULL;
1765 #endif
1766 #endif
1767 /*
1768 * If the -n flag wasn't given, we open up OUR (not the child's)
1769 * temporary file to stuff commands in it. The thing is rd/wr so we don't
1770 * need to reopen it to feed it to the shell. If the -n flag *was* given,
1771 * we just set the file to be stdout. Cute, huh?
1772 */
1773 if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1774 /*
1775 * tfile is the name of a file into which all shell commands are
1776 * put. It is used over by removing it before the child shell is
1777 * executed. The XXXXXX in the string are replaced by the pid of
1778 * the make process in a 6-character field with leading zeroes.
1779 */
1780 char tfile[sizeof(TMPPAT)];
1781 /*
1782 * We're serious here, but if the commands were bogus, we're
1783 * also dead...
1784 */
1785 if (!cmdsOK) {
1786 DieHorribly();
1787 }
1788
1789 (void)strcpy(tfile, TMPPAT);
1790 if ((tfd = mkstemp(tfile)) == -1)
1791 Punt("Could not create temporary file %s", strerror(errno));
1792 (void) eunlink(tfile);
1793
1794 job->cmdFILE = fdopen(tfd, "w+");
1795 if (job->cmdFILE == NULL) {
1796 Punt("Could not fdopen %s", tfile);
1797 }
1798 (void) fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1799 /*
1800 * Send the commands to the command file, flush all its buffers then
1801 * rewind and remove the thing.
1802 */
1803 noExec = FALSE;
1804
1805 /*
1806 * used to be backwards; replace when start doing multiple commands
1807 * per shell.
1808 */
1809 if (compatMake) {
1810 /*
1811 * Be compatible: If this is the first time for this node,
1812 * verify its commands are ok and open the commands list for
1813 * sequential access by later invocations of JobStart.
1814 * Once that is done, we take the next command off the list
1815 * and print it to the command file. If the command was an
1816 * ellipsis, note that there's nothing more to execute.
1817 */
1818 if ((job->flags&JOB_FIRST) && (Lst_Open(gn->commands) != SUCCESS)){
1819 cmdsOK = FALSE;
1820 } else {
1821 LstNode ln = Lst_Next(gn->commands);
1822
1823 if ((ln == NILLNODE) ||
1824 JobPrintCommand((ClientData) Lst_Datum(ln),
1825 (ClientData) job))
1826 {
1827 noExec = TRUE;
1828 Lst_Close(gn->commands);
1829 }
1830 if (noExec && !(job->flags & JOB_FIRST)) {
1831 /*
1832 * If we're not going to execute anything, the job
1833 * is done and we need to close down the various
1834 * file descriptors we've opened for output, then
1835 * call JobDoOutput to catch the final characters or
1836 * send the file to the screen... Note that the i/o streams
1837 * are only open if this isn't the first job.
1838 * Note also that this could not be done in
1839 * Job_CatchChildren b/c it wasn't clear if there were
1840 * more commands to execute or not...
1841 */
1842 JobClose(job);
1843 }
1844 }
1845 } else {
1846 /*
1847 * We can do all the commands at once. hooray for sanity
1848 */
1849 numCommands = 0;
1850 Lst_ForEach(gn->commands, JobPrintCommand, (ClientData)job);
1851
1852 /*
1853 * If we didn't print out any commands to the shell script,
1854 * there's not much point in executing the shell, is there?
1855 */
1856 if (numCommands == 0) {
1857 noExec = TRUE;
1858 }
1859 }
1860 } else if (noExecute) {
1861 /*
1862 * Not executing anything -- just print all the commands to stdout
1863 * in one fell swoop. This will still set up job->tailCmds correctly.
1864 */
1865 if (lastNode != gn) {
1866 MESSAGE(stdout, gn);
1867 lastNode = gn;
1868 }
1869 job->cmdFILE = stdout;
1870 /*
1871 * Only print the commands if they're ok, but don't die if they're
1872 * not -- just let the user know they're bad and keep going. It
1873 * doesn't do any harm in this case and may do some good.
1874 */
1875 if (cmdsOK) {
1876 Lst_ForEach(gn->commands, JobPrintCommand, (ClientData)job);
1877 }
1878 /*
1879 * Don't execute the shell, thank you.
1880 */
1881 noExec = TRUE;
1882 } else {
1883 /*
1884 * Just touch the target and note that no shell should be executed.
1885 * Set cmdFILE to stdout to make life easier. Check the commands, too,
1886 * but don't die if they're no good -- it does no harm to keep working
1887 * up the graph.
1888 */
1889 job->cmdFILE = stdout;
1890 Job_Touch(gn, job->flags&JOB_SILENT);
1891 noExec = TRUE;
1892 }
1893
1894 /*
1895 * If we're not supposed to execute a shell, don't.
1896 */
1897 if (noExec) {
1898 /*
1899 * Unlink and close the command file if we opened one
1900 */
1901 if (job->cmdFILE != stdout) {
1902 if (job->cmdFILE != NULL) {
1903 (void) fclose(job->cmdFILE);
1904 job->cmdFILE = NULL;
1905 }
1906 } else {
1907 (void) fflush(stdout);
1908 }
1909
1910 /*
1911 * We only want to work our way up the graph if we aren't here because
1912 * the commands for the job were no good.
1913 */
1914 if (cmdsOK) {
1915 if (aborting == 0) {
1916 if (job->tailCmds != NILLNODE) {
1917 Lst_ForEachFrom(job->node->commands, job->tailCmds,
1918 JobSaveCommand,
1919 (ClientData)job->node);
1920 }
1921 if (!(job->flags & JOB_SPECIAL))
1922 Job_TokenReturn();
1923 Make_Update(job->node);
1924 }
1925 free((Address)job);
1926 return(JOB_FINISHED);
1927 } else {
1928 free((Address)job);
1929 return(JOB_ERROR);
1930 }
1931 } else {
1932 (void) fflush(job->cmdFILE);
1933 }
1934
1935 /*
1936 * Set up the control arguments to the shell. This is based on the flags
1937 * set earlier for this job.
1938 */
1939 JobMakeArgv(job, argv);
1940
1941 /*
1942 * If we're using pipes to catch output, create the pipe by which we'll
1943 * get the shell's output. If we're using files, print out that we're
1944 * starting a job and then set up its temporary-file name.
1945 */
1946 if (!compatMake || (job->flags & JOB_FIRST)) {
1947 if (usePipes) {
1948 int fd[2];
1949 if (pipe(fd) == -1)
1950 Punt("Cannot create pipe: %s", strerror(errno));
1951 job->inPipe = fd[0];
1952 #ifdef USE_SELECT
1953 if (job->inPipe >= FD_SETSIZE)
1954 Punt("Ran out of fd_set slots; "
1955 "recompile with a larger FD_SETSIZE.");
1956 #endif
1957 job->outPipe = fd[1];
1958 (void) fcntl(job->inPipe, F_SETFD, 1);
1959 (void) fcntl(job->outPipe, F_SETFD, 1);
1960 } else {
1961 (void) fprintf(stdout, "Remaking `%s'\n", gn->name);
1962 (void) fflush(stdout);
1963 (void) strcpy(job->outFile, TMPPAT);
1964 job->outFd = mkstemp(job->outFile);
1965 (void) fcntl(job->outFd, F_SETFD, 1);
1966 }
1967 }
1968
1969 #ifdef REMOTE
1970 if (!(gn->type & OP_NOEXPORT) && !(runLocalFirst && nLocal < maxLocal)) {
1971 #ifdef RMT_NO_EXEC
1972 local = !Rmt_Export(shellPath, argv, job);
1973 #else
1974 local = !Rmt_Begin(shellPath, argv, job->node);
1975 #endif /* RMT_NO_EXEC */
1976 if (!local) {
1977 job->flags |= JOB_REMOTE;
1978 }
1979 } else
1980 #endif
1981 local = TRUE;
1982
1983 if (local && (((nLocal >= maxLocal) &&
1984 !(job->flags & JOB_SPECIAL) &&
1985 #ifdef REMOTE
1986 (!(gn->type & OP_NOEXPORT) || (maxLocal != 0))
1987 #else
1988 (maxLocal != 0)
1989 #endif
1990 )))
1991 {
1992 /*
1993 * The job can only be run locally, but we've hit the limit of
1994 * local concurrency, so put the job on hold until some other job
1995 * finishes. Note that the special jobs (.BEGIN, .INTERRUPT and .END)
1996 * may be run locally even when the local limit has been reached
1997 * (e.g. when maxLocal == 0), though they will be exported if at
1998 * all possible. In addition, any target marked with .NOEXPORT will
1999 * be run locally if maxLocal is 0.
2000 */
2001 job->flags |= JOB_RESTART;
2002 (void) Lst_AtEnd(stoppedJobs, (ClientData)job);
2003 } else {
2004 JobExec(job, argv);
2005 }
2006 return(JOB_RUNNING);
2007 }
2008
2009 static char *
2010 JobOutput(job, cp, endp, msg)
2011 register Job *job;
2012 register char *cp, *endp;
2013 int msg;
2014 {
2015 register char *ecp;
2016
2017 if (commandShell->noPrint) {
2018 ecp = Str_FindSubstring(cp, commandShell->noPrint);
2019 while (ecp != NULL) {
2020 if (cp != ecp) {
2021 *ecp = '\0';
2022 if (msg && job->node != lastNode) {
2023 MESSAGE(stdout, job->node);
2024 lastNode = job->node;
2025 }
2026 /*
2027 * The only way there wouldn't be a newline after
2028 * this line is if it were the last in the buffer.
2029 * however, since the non-printable comes after it,
2030 * there must be a newline, so we don't print one.
2031 */
2032 (void) fprintf(stdout, "%s", cp);
2033 (void) fflush(stdout);
2034 }
2035 cp = ecp + commandShell->noPLen;
2036 if (cp != endp) {
2037 /*
2038 * Still more to print, look again after skipping
2039 * the whitespace following the non-printable
2040 * command....
2041 */
2042 cp++;
2043 while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
2044 cp++;
2045 }
2046 ecp = Str_FindSubstring(cp, commandShell->noPrint);
2047 } else {
2048 return cp;
2049 }
2050 }
2051 }
2052 return cp;
2053 }
2054
2055 /*-
2056 *-----------------------------------------------------------------------
2057 * JobDoOutput --
2058 * This function is called at different times depending on
2059 * whether the user has specified that output is to be collected
2060 * via pipes or temporary files. In the former case, we are called
2061 * whenever there is something to read on the pipe. We collect more
2062 * output from the given job and store it in the job's outBuf. If
2063 * this makes up a line, we print it tagged by the job's identifier,
2064 * as necessary.
2065 * If output has been collected in a temporary file, we open the
2066 * file and read it line by line, transfering it to our own
2067 * output channel until the file is empty. At which point we
2068 * remove the temporary file.
2069 * In both cases, however, we keep our figurative eye out for the
2070 * 'noPrint' line for the shell from which the output came. If
2071 * we recognize a line, we don't print it. If the command is not
2072 * alone on the line (the character after it is not \0 or \n), we
2073 * do print whatever follows it.
2074 *
2075 * Results:
2076 * None
2077 *
2078 * Side Effects:
2079 * curPos may be shifted as may the contents of outBuf.
2080 *-----------------------------------------------------------------------
2081 */
2082 STATIC void
2083 JobDoOutput(job, finish)
2084 register Job *job; /* the job whose output needs printing */
2085 Boolean finish; /* TRUE if this is the last time we'll be
2086 * called for this job */
2087 {
2088 Boolean gotNL = FALSE; /* true if got a newline */
2089 Boolean fbuf; /* true if our buffer filled up */
2090 register int nr; /* number of bytes read */
2091 register int i; /* auxiliary index into outBuf */
2092 register int max; /* limit for i (end of current data) */
2093 int nRead; /* (Temporary) number of bytes read */
2094
2095 FILE *oFILE; /* Stream pointer to shell's output file */
2096 char inLine[132];
2097
2098
2099 if (usePipes) {
2100 /*
2101 * Read as many bytes as will fit in the buffer.
2102 */
2103 end_loop:
2104 gotNL = FALSE;
2105 fbuf = FALSE;
2106
2107 nRead = read(job->inPipe, &job->outBuf[job->curPos],
2108 JOB_BUFSIZE - job->curPos);
2109 if (nRead < 0) {
2110 if (DEBUG(JOB)) {
2111 perror("JobDoOutput(piperead)");
2112 }
2113 nr = 0;
2114 } else {
2115 nr = nRead;
2116 }
2117
2118 /*
2119 * If we hit the end-of-file (the job is dead), we must flush its
2120 * remaining output, so pretend we read a newline if there's any
2121 * output remaining in the buffer.
2122 * Also clear the 'finish' flag so we stop looping.
2123 */
2124 if ((nr == 0) && (job->curPos != 0)) {
2125 job->outBuf[job->curPos] = '\n';
2126 nr = 1;
2127 finish = FALSE;
2128 } else if (nr == 0) {
2129 finish = FALSE;
2130 }
2131
2132 /*
2133 * Look for the last newline in the bytes we just got. If there is
2134 * one, break out of the loop with 'i' as its index and gotNL set
2135 * TRUE.
2136 */
2137 max = job->curPos + nr;
2138 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
2139 if (job->outBuf[i] == '\n') {
2140 gotNL = TRUE;
2141 break;
2142 } else if (job->outBuf[i] == '\0') {
2143 /*
2144 * Why?
2145 */
2146 job->outBuf[i] = ' ';
2147 }
2148 }
2149
2150 if (!gotNL) {
2151 job->curPos += nr;
2152 if (job->curPos == JOB_BUFSIZE) {
2153 /*
2154 * If we've run out of buffer space, we have no choice
2155 * but to print the stuff. sigh.
2156 */
2157 fbuf = TRUE;
2158 i = job->curPos;
2159 }
2160 }
2161 if (gotNL || fbuf) {
2162 /*
2163 * Need to send the output to the screen. Null terminate it
2164 * first, overwriting the newline character if there was one.
2165 * So long as the line isn't one we should filter (according
2166 * to the shell description), we print the line, preceeded
2167 * by a target banner if this target isn't the same as the
2168 * one for which we last printed something.
2169 * The rest of the data in the buffer are then shifted down
2170 * to the start of the buffer and curPos is set accordingly.
2171 */
2172 job->outBuf[i] = '\0';
2173 if (i >= job->curPos) {
2174 char *cp;
2175
2176 cp = JobOutput(job, job->outBuf, &job->outBuf[i], FALSE);
2177
2178 /*
2179 * There's still more in that thar buffer. This time, though,
2180 * we know there's no newline at the end, so we add one of
2181 * our own free will.
2182 */
2183 if (*cp != '\0') {
2184 if (job->node != lastNode) {
2185 MESSAGE(stdout, job->node);
2186 lastNode = job->node;
2187 }
2188 (void) fprintf(stdout, "%s%s", cp, gotNL ? "\n" : "");
2189 (void) fflush(stdout);
2190 }
2191 }
2192 if (i < max - 1) {
2193 /* shift the remaining characters down */
2194 (void) memcpy(job->outBuf, &job->outBuf[i + 1], max - (i + 1));
2195 job->curPos = max - (i + 1);
2196
2197 } else {
2198 /*
2199 * We have written everything out, so we just start over
2200 * from the start of the buffer. No copying. No nothing.
2201 */
2202 job->curPos = 0;
2203 }
2204 }
2205 if (finish) {
2206 /*
2207 * If the finish flag is true, we must loop until we hit
2208 * end-of-file on the pipe. This is guaranteed to happen
2209 * eventually since the other end of the pipe is now closed
2210 * (we closed it explicitly and the child has exited). When
2211 * we do get an EOF, finish will be set FALSE and we'll fall
2212 * through and out.
2213 */
2214 goto end_loop;
2215 }
2216 } else {
2217 /*
2218 * We've been called to retrieve the output of the job from the
2219 * temporary file where it's been squirreled away. This consists of
2220 * opening the file, reading the output line by line, being sure not
2221 * to print the noPrint line for the shell we used, then close and
2222 * remove the temporary file. Very simple.
2223 *
2224 * Change to read in blocks and do FindSubString type things as for
2225 * pipes? That would allow for "@echo -n..."
2226 */
2227 oFILE = fopen(job->outFile, "r");
2228 if (oFILE != NULL) {
2229 (void) fprintf(stdout, "Results of making %s:\n", job->node->name);
2230 (void) fflush(stdout);
2231 while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2232 register char *cp, *endp, *oendp;
2233
2234 cp = inLine;
2235 oendp = endp = inLine + strlen(inLine);
2236 if (endp[-1] == '\n') {
2237 *--endp = '\0';
2238 }
2239 cp = JobOutput(job, inLine, endp, FALSE);
2240
2241 /*
2242 * There's still more in that thar buffer. This time, though,
2243 * we know there's no newline at the end, so we add one of
2244 * our own free will.
2245 */
2246 (void) fprintf(stdout, "%s", cp);
2247 (void) fflush(stdout);
2248 if (endp != oendp) {
2249 (void) fprintf(stdout, "\n");
2250 (void) fflush(stdout);
2251 }
2252 }
2253 (void) fclose(oFILE);
2254 (void) eunlink(job->outFile);
2255 } else {
2256 Punt("Cannot open `%s'", job->outFile);
2257 }
2258 }
2259 }
2260
2261 /*-
2262 *-----------------------------------------------------------------------
2263 * Job_CatchChildren --
2264 * Handle the exit of a child. Called from Make_Make.
2265 *
2266 * Results:
2267 * none.
2268 *
2269 * Side Effects:
2270 * The job descriptor is removed from the list of children.
2271 *
2272 * Notes:
2273 * We do waits, blocking or not, according to the wisdom of our
2274 * caller, until there are no more children to report. For each
2275 * job, call JobFinish to finish things off. This will take care of
2276 * putting jobs on the stoppedJobs queue.
2277 *
2278 *-----------------------------------------------------------------------
2279 */
2280 void
2281 Job_CatchChildren(block)
2282 Boolean block; /* TRUE if should block on the wait. */
2283 {
2284 int pid; /* pid of dead child */
2285 register Job *job; /* job descriptor for dead child */
2286 LstNode jnode; /* list element for finding job */
2287 int status; /* Exit/termination status */
2288
2289 /*
2290 * Don't even bother if we know there's no one around.
2291 */
2292 if (nLocal == 0) {
2293 return;
2294 }
2295
2296 while ((pid = waitpid((pid_t) -1, &status,
2297 (block?0:WNOHANG)|WUNTRACED)) > 0)
2298 {
2299 if (DEBUG(JOB)) {
2300 (void) fprintf(stdout, "Process %d exited or stopped %x.\n", pid,
2301 status);
2302 (void) fflush(stdout);
2303 }
2304
2305
2306 jnode = Lst_Find(jobs, (ClientData)&pid, JobCmpPid);
2307
2308 if (jnode == NILLNODE) {
2309 if (WIFSTOPPED(status) && (WSTOPSIG(status) == SIGCONT)) {
2310 jnode = Lst_Find(stoppedJobs, (ClientData) &pid, JobCmpPid);
2311 if (jnode == NILLNODE) {
2312 Error("Resumed child (%d) not in table", pid);
2313 continue;
2314 }
2315 job = (Job *)Lst_Datum(jnode);
2316 (void) Lst_Remove(stoppedJobs, jnode);
2317 } else {
2318 Error("Child (%d) not in table?", pid);
2319 continue;
2320 }
2321 } else {
2322 job = (Job *) Lst_Datum(jnode);
2323 (void) Lst_Remove(jobs, jnode);
2324 nJobs -= 1;
2325 #ifdef REMOTE
2326 if (!(job->flags & JOB_REMOTE)) {
2327 if (DEBUG(JOB)) {
2328 (void) fprintf(stdout,
2329 "Job queue has one fewer local process.\n");
2330 (void) fflush(stdout);
2331 }
2332 nLocal -= 1;
2333 }
2334 #else
2335 nLocal -= 1;
2336 #endif
2337 }
2338
2339 JobFinish(job, &status);
2340 }
2341 }
2342
2343 /*-
2344 *-----------------------------------------------------------------------
2345 * Job_CatchOutput --
2346 * Catch the output from our children, if we're using
2347 * pipes do so. Otherwise just block time until we get a
2348 * signal (most likely a SIGCHLD) since there's no point in
2349 * just spinning when there's nothing to do and the reaping
2350 * of a child can wait for a while.
2351 *
2352 * Results:
2353 * None
2354 *
2355 * Side Effects:
2356 * Output is read from pipes if we're piping.
2357 * -----------------------------------------------------------------------
2358 */
2359 void
2360 Job_CatchOutput()
2361 {
2362 int nready;
2363 register LstNode ln;
2364 register Job *job;
2365 #ifdef RMT_WILL_WATCH
2366 int pnJobs; /* Previous nJobs */
2367 #endif
2368
2369 (void) fflush(stdout);
2370 Job_TokenFlush();
2371 #ifdef RMT_WILL_WATCH
2372 pnJobs = nJobs;
2373
2374 /*
2375 * It is possible for us to be called with nJobs equal to 0. This happens
2376 * if all the jobs finish and a job that is stopped cannot be run
2377 * locally (eg if maxLocal is 0) and cannot be exported. The job will
2378 * be placed back on the stoppedJobs queue, Job_Empty() will return false,
2379 * Make_Run will call us again when there's nothing for which to wait.
2380 * nJobs never changes, so we loop forever. Hence the check. It could
2381 * be argued that we should sleep for a bit so as not to swamp the
2382 * exportation system with requests. Perhaps we should.
2383 *
2384 * NOTE: IT IS THE RESPONSIBILITY OF Rmt_Wait TO CALL Job_CatchChildren
2385 * IN A TIMELY FASHION TO CATCH ANY LOCALLY RUNNING JOBS THAT EXIT.
2386 * It may use the variable nLocal to determine if it needs to call
2387 * Job_CatchChildren (if nLocal is 0, there's nothing for which to
2388 * wait...)
2389 */
2390 while (nJobs != 0 && pnJobs == nJobs) {
2391 Rmt_Wait();
2392 }
2393 #else
2394 if (usePipes) {
2395 #ifdef USE_SELECT
2396 struct timeval timeout;
2397 fd_set readfds;
2398
2399 readfds = outputs;
2400 timeout.tv_sec = SEL_SEC;
2401 timeout.tv_usec = SEL_USEC;
2402
2403 if ((nready = select(FD_SETSIZE, &readfds, (fd_set *) 0,
2404 (fd_set *) 0, &timeout)) <= 0)
2405 return;
2406 #else
2407 if ((nready = poll((wantToken ? fds : (fds + 1)),
2408 (wantToken ? nfds : (nfds - 1)), POLL_MSEC)) <= 0)
2409 return;
2410 #endif
2411 else {
2412 if (Lst_Open(jobs) == FAILURE) {
2413 Punt("Cannot open job table");
2414 }
2415 while (nready && (ln = Lst_Next(jobs)) != NILLNODE) {
2416 job = (Job *) Lst_Datum(ln);
2417 #ifdef USE_SELECT
2418 if (FD_ISSET(job->inPipe, &readfds))
2419 #else
2420 if (readyfd(job))
2421 #endif
2422 {
2423 JobDoOutput(job, FALSE);
2424 nready -= 1;
2425 }
2426
2427 }
2428 Lst_Close(jobs);
2429 }
2430 }
2431 #endif /* RMT_WILL_WATCH */
2432 }
2433
2434 /*-
2435 *-----------------------------------------------------------------------
2436 * Job_Make --
2437 * Start the creation of a target. Basically a front-end for
2438 * JobStart used by the Make module.
2439 *
2440 * Results:
2441 * None.
2442 *
2443 * Side Effects:
2444 * Another job is started.
2445 *
2446 *-----------------------------------------------------------------------
2447 */
2448 void
2449 Job_Make(gn)
2450 GNode *gn;
2451 {
2452 (void) JobStart(gn, 0, NULL);
2453 }
2454
2455 /*-
2456 *-----------------------------------------------------------------------
2457 * Job_Init --
2458 * Initialize the process module
2459 *
2460 * Results:
2461 * none
2462 *
2463 * Side Effects:
2464 * lists and counters are initialized
2465 *-----------------------------------------------------------------------
2466 */
2467 void
2468 Job_Init(maxproc, maxlocal)
2469 int maxproc; /* the greatest number of jobs which may be
2470 * running at one time */
2471 int maxlocal; /* the greatest number of local jobs which may
2472 * be running at once. */
2473 {
2474 GNode *begin; /* node for commands to do at the very start */
2475
2476 jobs = Lst_Init(FALSE);
2477 stoppedJobs = Lst_Init(FALSE);
2478 maxJobs = maxproc;
2479 maxLocal = maxlocal;
2480 nJobs = 0;
2481 nLocal = 0;
2482 wantToken = FALSE;
2483
2484 aborting = 0;
2485 errors = 0;
2486
2487 lastNode = NILGNODE;
2488
2489 if (maxJobs == 1
2490 #ifdef REMOTE
2491 || noMessages
2492 #endif
2493 ) {
2494 /*
2495 * If only one job can run at a time, there's no need for a banner,
2496 * is there?
2497 */
2498 targFmt = "";
2499 } else {
2500 targFmt = TARG_FMT;
2501 }
2502
2503 if (shellPath == NULL) {
2504 /*
2505 * The user didn't specify a shell to use, so we are using the
2506 * default one... Both the absolute path and the last component
2507 * must be set. The last component is taken from the 'name' field
2508 * of the default shell description pointed-to by commandShell.
2509 * All default shells are located in _PATH_DEFSHELLDIR.
2510 */
2511 shellName = commandShell->name;
2512 shellPath = str_concat(_PATH_DEFSHELLDIR, shellName, STR_ADDSLASH);
2513 }
2514
2515 if (commandShell->exit == NULL) {
2516 commandShell->exit = "";
2517 }
2518 if (commandShell->echo == NULL) {
2519 commandShell->echo = "";
2520 }
2521
2522 /*
2523 * Catch the four signals that POSIX specifies if they aren't ignored.
2524 * JobPassSig will take care of calling JobInterrupt if appropriate.
2525 */
2526 if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2527 (void) signal(SIGINT, JobPassSig);
2528 }
2529 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2530 (void) signal(SIGHUP, JobPassSig);
2531 }
2532 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2533 (void) signal(SIGQUIT, JobPassSig);
2534 }
2535 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2536 (void) signal(SIGTERM, JobPassSig);
2537 }
2538 /*
2539 * Install a NOOP SIGCHLD handler so we are woken up if we're blocked.
2540 */
2541 signal(SIGCHLD, JobIgnoreSig);
2542
2543 /*
2544 * There are additional signals that need to be caught and passed if
2545 * either the export system wants to be told directly of signals or if
2546 * we're giving each job its own process group (since then it won't get
2547 * signals from the terminal driver as we own the terminal)
2548 */
2549 #if defined(RMT_WANTS_SIGNALS) || defined(USE_PGRP)
2550 if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2551 (void) signal(SIGTSTP, JobPassSig);
2552 }
2553 if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2554 (void) signal(SIGTTOU, JobPassSig);
2555 }
2556 if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2557 (void) signal(SIGTTIN, JobPassSig);
2558 }
2559 if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2560 (void) signal(SIGWINCH, JobPassSig);
2561 }
2562 #endif
2563
2564 begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2565
2566 if (begin != NILGNODE) {
2567 JobStart(begin, JOB_SPECIAL, (Job *)0);
2568 while (nJobs) {
2569 Job_CatchOutput();
2570 #ifndef RMT_WILL_WATCH
2571 Job_CatchChildren(!usePipes);
2572 #endif /* RMT_WILL_WATCH */
2573 }
2574 }
2575 postCommands = Targ_FindNode(".END", TARG_CREATE);
2576 }
2577
2578 /*-
2579 *-----------------------------------------------------------------------
2580 * Job_Empty --
2581 * See if the job table is empty. Because the local concurrency may
2582 * be set to 0, it is possible for the job table to become empty,
2583 * while the list of stoppedJobs remains non-empty. In such a case,
2584 * we want to restart as many jobs as we can.
2585 *
2586 * Results:
2587 * TRUE if it is. FALSE if it ain't.
2588 *
2589 * Side Effects:
2590 * None.
2591 *
2592 * -----------------------------------------------------------------------
2593 */
2594 Boolean
2595 Job_Empty()
2596 {
2597 if (nJobs == 0) {
2598 if (!Lst_IsEmpty(stoppedJobs) && !aborting) {
2599 /*
2600 * The job table is obviously not full if it has no jobs in
2601 * it...Try and restart the stopped jobs.
2602 */
2603 JobRestartJobs();
2604 return(FALSE);
2605 } else {
2606 return(TRUE);
2607 }
2608 } else {
2609 return(FALSE);
2610 }
2611 }
2612
2613 /*-
2614 *-----------------------------------------------------------------------
2615 * JobMatchShell --
2616 * Find a matching shell in 'shells' given its final component.
2617 *
2618 * Results:
2619 * A pointer to the Shell structure.
2620 *
2621 * Side Effects:
2622 * None.
2623 *
2624 *-----------------------------------------------------------------------
2625 */
2626 static Shell *
2627 JobMatchShell(name)
2628 char *name; /* Final component of shell path */
2629 {
2630 register Shell *sh; /* Pointer into shells table */
2631 Shell *match; /* Longest-matching shell */
2632 register char *cp1,
2633 *cp2;
2634 char *eoname;
2635
2636 eoname = name + strlen(name);
2637
2638 match = NULL;
2639
2640 for (sh = shells; sh->name != NULL; sh++) {
2641 for (cp1 = eoname - strlen(sh->name), cp2 = sh->name;
2642 *cp1 != '\0' && *cp1 == *cp2;
2643 cp1++, cp2++) {
2644 continue;
2645 }
2646 if (*cp1 != *cp2) {
2647 continue;
2648 } else if (match == NULL || strlen(match->name) < strlen(sh->name)) {
2649 match = sh;
2650 }
2651 }
2652 return(match == NULL ? sh : match);
2653 }
2654
2655 /*-
2656 *-----------------------------------------------------------------------
2657 * Job_ParseShell --
2658 * Parse a shell specification and set up commandShell, shellPath
2659 * and shellName appropriately.
2660 *
2661 * Results:
2662 * FAILURE if the specification was incorrect.
2663 *
2664 * Side Effects:
2665 * commandShell points to a Shell structure (either predefined or
2666 * created from the shell spec), shellPath is the full path of the
2667 * shell described by commandShell, while shellName is just the
2668 * final component of shellPath.
2669 *
2670 * Notes:
2671 * A shell specification consists of a .SHELL target, with dependency
2672 * operator, followed by a series of blank-separated words. Double
2673 * quotes can be used to use blanks in words. A backslash escapes
2674 * anything (most notably a double-quote and a space) and
2675 * provides the functionality it does in C. Each word consists of
2676 * keyword and value separated by an equal sign. There should be no
2677 * unnecessary spaces in the word. The keywords are as follows:
2678 * name Name of shell.
2679 * path Location of shell. Overrides "name" if given
2680 * quiet Command to turn off echoing.
2681 * echo Command to turn echoing on
2682 * filter Result of turning off echoing that shouldn't be
2683 * printed.
2684 * echoFlag Flag to turn echoing on at the start
2685 * errFlag Flag to turn error checking on at the start
2686 * hasErrCtl True if shell has error checking control
2687 * check Command to turn on error checking if hasErrCtl
2688 * is TRUE or template of command to echo a command
2689 * for which error checking is off if hasErrCtl is
2690 * FALSE.
2691 * ignore Command to turn off error checking if hasErrCtl
2692 * is TRUE or template of command to execute a
2693 * command so as to ignore any errors it returns if
2694 * hasErrCtl is FALSE.
2695 *
2696 *-----------------------------------------------------------------------
2697 */
2698 ReturnStatus
2699 Job_ParseShell(line)
2700 char *line; /* The shell spec */
2701 {
2702 char **words;
2703 int wordCount;
2704 register char **argv;
2705 register int argc;
2706 char *path;
2707 Shell newShell;
2708 Boolean fullSpec = FALSE;
2709
2710 while (isspace((unsigned char)*line)) {
2711 line++;
2712 }
2713
2714 if (shellArgv)
2715 free(shellArgv);
2716
2717 words = brk_string(line, &wordCount, TRUE, &shellArgv);
2718
2719 memset((Address)&newShell, 0, sizeof(newShell));
2720
2721 /*
2722 * Parse the specification by keyword
2723 */
2724 for (path = NULL, argc = wordCount - 1, argv = words;
2725 argc != 0;
2726 argc--, argv++) {
2727 if (strncmp(*argv, "path=", 5) == 0) {
2728 path = &argv[0][5];
2729 } else if (strncmp(*argv, "name=", 5) == 0) {
2730 newShell.name = &argv[0][5];
2731 } else {
2732 if (strncmp(*argv, "quiet=", 6) == 0) {
2733 newShell.echoOff = &argv[0][6];
2734 } else if (strncmp(*argv, "echo=", 5) == 0) {
2735 newShell.echoOn = &argv[0][5];
2736 } else if (strncmp(*argv, "filter=", 7) == 0) {
2737 newShell.noPrint = &argv[0][7];
2738 newShell.noPLen = strlen(newShell.noPrint);
2739 } else if (strncmp(*argv, "echoFlag=", 9) == 0) {
2740 newShell.echo = &argv[0][9];
2741 } else if (strncmp(*argv, "errFlag=", 8) == 0) {
2742 newShell.exit = &argv[0][8];
2743 } else if (strncmp(*argv, "hasErrCtl=", 10) == 0) {
2744 char c = argv[0][10];
2745 newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
2746 (c != 'T') && (c != 't'));
2747 } else if (strncmp(*argv, "check=", 6) == 0) {
2748 newShell.errCheck = &argv[0][6];
2749 } else if (strncmp(*argv, "ignore=", 7) == 0) {
2750 newShell.ignErr = &argv[0][7];
2751 } else {
2752 Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"",
2753 *argv);
2754 free(words);
2755 return(FAILURE);
2756 }
2757 fullSpec = TRUE;
2758 }
2759 }
2760
2761 if (path == NULL) {
2762 /*
2763 * If no path was given, the user wants one of the pre-defined shells,
2764 * yes? So we find the one s/he wants with the help of JobMatchShell
2765 * and set things up the right way. shellPath will be set up by
2766 * Job_Init.
2767 */
2768 if (newShell.name == NULL) {
2769 Parse_Error(PARSE_FATAL, "Neither path nor name specified");
2770 return(FAILURE);
2771 } else {
2772 commandShell = JobMatchShell(newShell.name);
2773 shellName = newShell.name;
2774 }
2775 } else {
2776 /*
2777 * The user provided a path. If s/he gave nothing else (fullSpec is
2778 * FALSE), try and find a matching shell in the ones we know of.
2779 * Else we just take the specification at its word and copy it
2780 * to a new location. In either case, we need to record the
2781 * path the user gave for the shell.
2782 */
2783 shellPath = path;
2784 path = strrchr(path, '/');
2785 if (path == NULL) {
2786 path = shellPath;
2787 } else {
2788 path += 1;
2789 }
2790 if (newShell.name != NULL) {
2791 shellName = newShell.name;
2792 } else {
2793 shellName = path;
2794 }
2795 if (!fullSpec) {
2796 commandShell = JobMatchShell(shellName);
2797 } else {
2798 commandShell = (Shell *) emalloc(sizeof(Shell));
2799 *commandShell = newShell;
2800 }
2801 }
2802
2803 if (commandShell->echoOn && commandShell->echoOff) {
2804 commandShell->hasEchoCtl = TRUE;
2805 }
2806
2807 if (!commandShell->hasErrCtl) {
2808 if (commandShell->errCheck == NULL) {
2809 commandShell->errCheck = "";
2810 }
2811 if (commandShell->ignErr == NULL) {
2812 commandShell->ignErr = "%s\n";
2813 }
2814 }
2815
2816 /*
2817 * Do not free up the words themselves, since they might be in use by the
2818 * shell specification.
2819 */
2820 free(words);
2821 return SUCCESS;
2822 }
2823
2824 /*-
2825 *-----------------------------------------------------------------------
2826 * JobInterrupt --
2827 * Handle the receipt of an interrupt.
2828 *
2829 * Results:
2830 * None
2831 *
2832 * Side Effects:
2833 * All children are killed. Another job will be started if the
2834 * .INTERRUPT target was given.
2835 *-----------------------------------------------------------------------
2836 */
2837 static void
2838 JobInterrupt(runINTERRUPT, signo)
2839 int runINTERRUPT; /* Non-zero if commands for the .INTERRUPT
2840 * target should be executed */
2841 int signo; /* signal received */
2842 {
2843 LstNode ln; /* element in job table */
2844 Job *job; /* job descriptor in that element */
2845 GNode *interrupt; /* the node describing the .INTERRUPT target */
2846
2847 aborting = ABORT_INTERRUPT;
2848
2849 (void) Lst_Open(jobs);
2850 while ((ln = Lst_Next(jobs)) != NILLNODE) {
2851 job = (Job *) Lst_Datum(ln);
2852
2853 if (!Targ_Precious(job->node)) {
2854 char *file = (job->node->path == NULL ?
2855 job->node->name :
2856 job->node->path);
2857 if (!noExecute && eunlink(file) != -1) {
2858 Error("*** %s removed", file);
2859 }
2860 }
2861 #ifdef RMT_WANTS_SIGNALS
2862 if (job->flags & JOB_REMOTE) {
2863 /*
2864 * If job is remote, let the Rmt module do the killing.
2865 */
2866 if (!Rmt_Signal(job, signo)) {
2867 /*
2868 * If couldn't kill the thing, finish it out now with an
2869 * error code, since no exit report will come in likely.
2870 */
2871 int status;
2872
2873 status.w_status = 0;
2874 status.w_retcode = 1;
2875 JobFinish(job, &status);
2876 }
2877 } else if (job->pid) {
2878 KILL(job->pid, signo);
2879 }
2880 #else
2881 if (job->pid) {
2882 if (DEBUG(JOB)) {
2883 (void) fprintf(stdout,
2884 "JobInterrupt passing signal to child %d.\n",
2885 job->pid);
2886 (void) fflush(stdout);
2887 }
2888 KILL(job->pid, signo);
2889 }
2890 #endif /* RMT_WANTS_SIGNALS */
2891 }
2892
2893 #ifdef REMOTE
2894 (void)Lst_Open(stoppedJobs);
2895 while ((ln = Lst_Next(stoppedJobs)) != NILLNODE) {
2896 job = (Job *) Lst_Datum(ln);
2897
2898 if (job->flags & JOB_RESTART) {
2899 if (DEBUG(JOB)) {
2900 (void) fprintf(stdout, "%s%s",
2901 "JobInterrupt skipping job on stopped queue",
2902 "-- it was waiting to be restarted.\n");
2903 (void) fflush(stdout);
2904 }
2905 continue;
2906 }
2907 if (!Targ_Precious(job->node)) {
2908 char *file = (job->node->path == NULL ?
2909 job->node->name :
2910 job->node->path);
2911 if (eunlink(file) == 0) {
2912 Error("*** %s removed", file);
2913 }
2914 }
2915 /*
2916 * Resume the thing so it will take the signal.
2917 */
2918 if (DEBUG(JOB)) {
2919 (void) fprintf(stdout,
2920 "JobInterrupt passing CONT to stopped child %d.\n",
2921 job->pid);
2922 (void) fflush(stdout);
2923 }
2924 KILL(job->pid, SIGCONT);
2925 #ifdef RMT_WANTS_SIGNALS
2926 if (job->flags & JOB_REMOTE) {
2927 /*
2928 * If job is remote, let the Rmt module do the killing.
2929 */
2930 if (!Rmt_Signal(job, SIGINT)) {
2931 /*
2932 * If couldn't kill the thing, finish it out now with an
2933 * error code, since no exit report will come in likely.
2934 */
2935 int status;
2936 status.w_status = 0;
2937 status.w_retcode = 1;
2938 JobFinish(job, &status);
2939 }
2940 } else if (job->pid) {
2941 if (DEBUG(JOB)) {
2942 (void) fprintf(stdout,
2943 "JobInterrupt passing interrupt to stopped child %d.\n",
2944 job->pid);
2945 (void) fflush(stdout);
2946 }
2947 KILL(job->pid, SIGINT);
2948 }
2949 #endif /* RMT_WANTS_SIGNALS */
2950 }
2951 #endif
2952 Lst_Close(stoppedJobs);
2953
2954 if (runINTERRUPT && !touchFlag) {
2955 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2956 if (interrupt != NILGNODE) {
2957 ignoreErrors = FALSE;
2958
2959 JobStart(interrupt, JOB_IGNDOTS, (Job *)0);
2960 while (nJobs) {
2961 Job_CatchOutput();
2962 #ifndef RMT_WILL_WATCH
2963 Job_CatchChildren(!usePipes);
2964 #endif /* RMT_WILL_WATCH */
2965 }
2966 }
2967 }
2968 Trace_Log(MAKEINTR, 0);
2969 exit(signo);
2970 }
2971
2972 /*
2973 *-----------------------------------------------------------------------
2974 * Job_Finish --
2975 * Do final processing such as the running of the commands
2976 * attached to the .END target.
2977 *
2978 * Results:
2979 * Number of errors reported.
2980 *
2981 * Side Effects:
2982 * None.
2983 *-----------------------------------------------------------------------
2984 */
2985 int
2986 Job_Finish()
2987 {
2988 if (postCommands != NILGNODE && !Lst_IsEmpty(postCommands->commands)) {
2989 if (errors) {
2990 Error("Errors reported so .END ignored");
2991 } else {
2992 JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
2993
2994 while (nJobs) {
2995 Job_CatchOutput();
2996 #ifndef RMT_WILL_WATCH
2997 Job_CatchChildren(!usePipes);
2998 #endif /* RMT_WILL_WATCH */
2999 }
3000 }
3001 }
3002 Job_TokenFlush();
3003 return(errors);
3004 }
3005
3006 /*-
3007 *-----------------------------------------------------------------------
3008 * Job_End --
3009 * Cleanup any memory used by the jobs module
3010 *
3011 * Results:
3012 * None.
3013 *
3014 * Side Effects:
3015 * Memory is freed
3016 *-----------------------------------------------------------------------
3017 */
3018 void
3019 Job_End()
3020 {
3021 #ifdef CLEANUP
3022 if (shellArgv)
3023 free(shellArgv);
3024 #endif
3025 }
3026
3027 /*-
3028 *-----------------------------------------------------------------------
3029 * Job_Wait --
3030 * Waits for all running jobs to finish and returns. Sets 'aborting'
3031 * to ABORT_WAIT to prevent other jobs from starting.
3032 *
3033 * Results:
3034 * None.
3035 *
3036 * Side Effects:
3037 * Currently running jobs finish.
3038 *
3039 *-----------------------------------------------------------------------
3040 */
3041 void
3042 Job_Wait()
3043 {
3044 aborting = ABORT_WAIT;
3045 while (nJobs != 0) {
3046 Job_CatchOutput();
3047 #ifndef RMT_WILL_WATCH
3048 Job_CatchChildren(!usePipes);
3049 #endif /* RMT_WILL_WATCH */
3050 }
3051 Job_TokenFlush();
3052 aborting = 0;
3053 }
3054
3055 /*-
3056 *-----------------------------------------------------------------------
3057 * Job_AbortAll --
3058 * Abort all currently running jobs without handling output or anything.
3059 * This function is to be called only in the event of a major
3060 * error. Most definitely NOT to be called from JobInterrupt.
3061 *
3062 * Results:
3063 * None
3064 *
3065 * Side Effects:
3066 * All children are killed, not just the firstborn
3067 *-----------------------------------------------------------------------
3068 */
3069 void
3070 Job_AbortAll()
3071 {
3072 LstNode ln; /* element in job table */
3073 Job *job; /* the job descriptor in that element */
3074 int foo;
3075
3076 aborting = ABORT_ERROR;
3077
3078 if (nJobs) {
3079
3080 (void) Lst_Open(jobs);
3081 while ((ln = Lst_Next(jobs)) != NILLNODE) {
3082 job = (Job *) Lst_Datum(ln);
3083
3084 /*
3085 * kill the child process with increasingly drastic signals to make
3086 * darn sure it's dead.
3087 */
3088 #ifdef RMT_WANTS_SIGNALS
3089 if (job->flags & JOB_REMOTE) {
3090 Rmt_Signal(job, SIGINT);
3091 Rmt_Signal(job, SIGKILL);
3092 } else {
3093 KILL(job->pid, SIGINT);
3094 KILL(job->pid, SIGKILL);
3095 }
3096 #else
3097 KILL(job->pid, SIGINT);
3098 KILL(job->pid, SIGKILL);
3099 #endif /* RMT_WANTS_SIGNALS */
3100 }
3101 }
3102
3103 /*
3104 * Catch as many children as want to report in at first, then give up
3105 */
3106 while (waitpid((pid_t) -1, &foo, WNOHANG) > 0)
3107 continue;
3108 }
3109
3110 #ifdef REMOTE
3111 /*-
3112 *-----------------------------------------------------------------------
3113 * JobFlagForMigration --
3114 * Handle the eviction of a child. Called from RmtStatusChange.
3115 * Flags the child as remigratable and then suspends it.
3116 *
3117 * Results:
3118 * none.
3119 *
3120 * Side Effects:
3121 * The job descriptor is flagged for remigration.
3122 *
3123 *-----------------------------------------------------------------------
3124 */
3125 void
3126 JobFlagForMigration(hostID)
3127 int hostID; /* ID of host we used, for matching children. */
3128 {
3129 register Job *job; /* job descriptor for dead child */
3130 LstNode jnode; /* list element for finding job */
3131
3132 if (DEBUG(JOB)) {
3133 (void) fprintf(stdout, "JobFlagForMigration(%d) called.\n", hostID);
3134 (void) fflush(stdout);
3135 }
3136 jnode = Lst_Find(jobs, (ClientData)hostID, JobCmpRmtID);
3137
3138 if (jnode == NILLNODE) {
3139 jnode = Lst_Find(stoppedJobs, (ClientData)hostID, JobCmpRmtID);
3140 if (jnode == NILLNODE) {
3141 if (DEBUG(JOB)) {
3142 Error("Evicting host(%d) not in table", hostID);
3143 }
3144 return;
3145 }
3146 }
3147 job = (Job *) Lst_Datum(jnode);
3148
3149 if (DEBUG(JOB)) {
3150 (void) fprintf(stdout,
3151 "JobFlagForMigration(%d) found job '%s'.\n", hostID,
3152 job->node->name);
3153 (void) fflush(stdout);
3154 }
3155
3156 KILL(job->pid, SIGSTOP);
3157
3158 job->flags |= JOB_REMIGRATE;
3159 }
3160
3161 #endif
3162
3163 /*-
3165 *-----------------------------------------------------------------------
3166 * JobRestartJobs --
3167 * Tries to restart stopped jobs if there are slots available.
3168 * Note that this tries to restart them regardless of pending errors.
3169 * It's not good to leave stopped jobs lying around!
3170 *
3171 * Results:
3172 * None.
3173 *
3174 * Side Effects:
3175 * Resumes(and possibly migrates) jobs.
3176 *
3177 *-----------------------------------------------------------------------
3178 */
3179 static void
3180 JobRestartJobs()
3181 {
3182 while (!Lst_IsEmpty(stoppedJobs)) {
3183 if (DEBUG(JOB)) {
3184 (void) fprintf(stdout, "Restarting a stopped job.\n");
3185 (void) fflush(stdout);
3186 }
3187 JobRestart((Job *)Lst_DeQueue(stoppedJobs));
3188 }
3189 }
3190
3191 #ifndef RMT_WILL_WATCH
3192 #ifndef USE_SELECT
3193 static void
3194 watchfd(job)
3195 Job *job;
3196 {
3197 int i;
3198 if (job->inPollfd != NULL)
3199 Punt("Watching watched job");
3200 if (fds == NULL) {
3201 maxfds = JBSTART;
3202 fds = emalloc(sizeof(struct pollfd) * maxfds);
3203 jobfds = emalloc(sizeof(Job **) * maxfds);
3204
3205 fds[0].fd = job_pipe[0];
3206 fds[0].events = POLLIN;
3207 jobfds[0] = &tokenWaitJob;
3208 tokenWaitJob.inPollfd = &fds[0];
3209 nfds++;
3210 } else if (nfds == maxfds) {
3211 maxfds *= JBFACTOR;
3212 fds = erealloc(fds, sizeof(struct pollfd) * maxfds);
3213 jobfds = erealloc(jobfds, sizeof(Job **) * maxfds);
3214 for (i = 0; i < nfds; i++)
3215 jobfds[i]->inPollfd = &fds[i];
3216 }
3217
3218 fds[nfds].fd = job->inPipe;
3219 fds[nfds].events = POLLIN;
3220 jobfds[nfds] = job;
3221 job->inPollfd = &fds[nfds];
3222 nfds++;
3223 }
3224
3225 static void
3226 clearfd(job)
3227 Job *job;
3228 {
3229 int i;
3230 if (job->inPollfd == NULL)
3231 Punt("Unwatching unwatched job");
3232 i = job->inPollfd - fds;
3233 nfds--;
3234 /*
3235 * Move last job in table into hole made by dead job.
3236 */
3237 if (nfds != i) {
3238 fds[i] = fds[nfds];
3239 jobfds[i] = jobfds[nfds];
3240 jobfds[i]->inPollfd = &fds[i];
3241 }
3242 job->inPollfd = NULL;
3243 }
3244
3245 static int
3246 readyfd(job)
3247 Job *job;
3248 {
3249 if (job->inPollfd == NULL)
3250 Punt("Polling unwatched job");
3251 return (job->inPollfd->revents & POLLIN) != 0;
3252 }
3253 #endif
3254 #endif
3255
3256 /*-
3257 *-----------------------------------------------------------------------
3258 * JobTokenAdd --
3259 * Put a token into the job pipe so that some make process can start
3260 * another job.
3261 *
3262 * Side Effects:
3263 * Allows more build jobs to be spawned somewhere.
3264 *
3265 *-----------------------------------------------------------------------
3266 */
3267
3268 static void
3269 JobTokenAdd()
3270 {
3271
3272 if (DEBUG(JOB))
3273 printf("deposit token\n");
3274 write(job_pipe[1], "+", 1);
3275 }
3276
3277 /*-
3278 *-----------------------------------------------------------------------
3279 * Job_ServerStartTokenAdd --
3280 * Prep the job token pipe in the root make process.
3281 *
3282 *-----------------------------------------------------------------------
3283 */
3284
3285 void Job_ServerStart(maxproc)
3286 int maxproc;
3287 {
3288 int i, flags;
3289 char jobarg[64];
3290
3291 if (pipe(job_pipe) < 0)
3292 Fatal ("error in pipe: %s", strerror(errno));
3293
3294 /*
3295 * We mark the input side of the pipe non-blocking; we poll(2) the
3296 * pipe when we're waiting for a job token, but we might lose the
3297 * race for the token when a new one becomes available, so the read
3298 * from the pipe should not block.
3299 */
3300 flags = fcntl(job_pipe[0], F_GETFL, 0);
3301 flags |= O_NONBLOCK;
3302 fcntl(job_pipe[0], F_SETFL, flags);
3303
3304 /*
3305 * Mark job pipes as close-on-exec.
3306 * Note that we will clear this when executing submakes.
3307 */
3308 fcntl(job_pipe[0], F_SETFD, 1);
3309 fcntl(job_pipe[1], F_SETFD, 1);
3310
3311 snprintf(jobarg, sizeof(jobarg), "%d,%d", job_pipe[0], job_pipe[1]);
3312
3313 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
3314 Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
3315
3316 /*
3317 * Preload job_pipe with one token per job, save the one
3318 * "extra" token for the primary job.
3319 *
3320 * XXX should clip maxJobs against PIPE_BUF -- if maxJobs is
3321 * larger than the write buffer size of the pipe, we will
3322 * deadlock here.
3323 */
3324 for (i=1; i < maxproc; i++)
3325 JobTokenAdd();
3326 }
3327
3328 /*
3329 * this tracks the number of tokens currently "out" to build jobs.
3330 */
3331 static int tokensOutstanding = 0;
3332 static int tokensFree = 0;
3333 /*-
3334 *-----------------------------------------------------------------------
3335 * Job_TokenReturn --
3336 * Return a withdrawn token to the pool.
3337 *
3338 *-----------------------------------------------------------------------
3339 */
3340
3341 void
3342 Job_TokenReturn()
3343 {
3344 tokensOutstanding--;
3345 if (tokensOutstanding < 0)
3346 Punt("token botch");
3347 if (tokensOutstanding)
3348 tokensFree++;
3349 }
3350
3351 /*-
3352 *-----------------------------------------------------------------------
3353 * Job_TokenWithdraw --
3354 * Attempt to withdraw a token from the pool.
3355 *
3356 * Results:
3357 * Returns TRUE if a token was withdrawn, and FALSE if the pool
3358 * is currently empty.
3359 *
3360 * Side Effects:
3361 * If pool is empty, set wantToken so that we wake up
3362 * when a token is released.
3363 *
3364 *-----------------------------------------------------------------------
3365 */
3366
3367
3368 Boolean
3369 Job_TokenWithdraw()
3370 {
3371 char tok;
3372 int count;
3373
3374 if (aborting)
3375 return FALSE;
3376
3377 if (tokensOutstanding == 0) {
3378 if (DEBUG(JOB))
3379 printf("first one's free\n");
3380 tokensOutstanding++;
3381 wantToken = FALSE;
3382 return TRUE;
3383 }
3384 if (tokensFree > 0) {
3385 tokensFree--;
3386 tokensOutstanding++;
3387 wantToken = FALSE;
3388 return TRUE;
3389 }
3390 count = read(job_pipe[0], &tok, 1);
3391 if (count == 0)
3392 Fatal("eof on job pipe!");
3393 else if (count < 0) {
3394 if (errno != EAGAIN) {
3395 Fatal("job pipe read: %s", strerror(errno));
3396 }
3397 if (DEBUG(JOB))
3398 printf("blocked for token\n");
3399 wantToken = TRUE;
3400 return FALSE;
3401 }
3402 wantToken = FALSE;
3403 tokensOutstanding++;
3404 if (DEBUG(JOB))
3405 printf("withdrew token\n");
3406 return TRUE;
3407 }
3408
3409 /*-
3410 *-----------------------------------------------------------------------
3411 * Job_TokenFlush --
3412 * Return free tokens to the pool.
3413 *
3414 *-----------------------------------------------------------------------
3415 */
3416
3417 void
3418 Job_TokenFlush()
3419 {
3420 if (compatMake) return;
3421
3422 while (tokensFree-- > 0) {
3423 JobTokenAdd();
3424 }
3425 }
3426
3427