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