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