Str_New -> strdup
[unix-history] / usr / src / usr.bin / make / job.c
CommitLineData
9320ab9e
KB
1/*
2 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
ab950546
KB
3 * Copyright (c) 1988, 1989 by Adam de Boor
4 * Copyright (c) 1989 by Berkeley Softworks
9320ab9e
KB
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
ab950546 9 *
9320ab9e
KB
10 * Redistribution and use in source and binary forms are permitted
11 * provided that the above copyright notice and this paragraph are
12 * duplicated in all such forms and that any documentation,
13 * advertising materials, and other materials related to such
14 * distribution and use acknowledge that the software was developed
15 * by the University of California, Berkeley. The name of the
16 * University may not be used to endorse or promote products derived
17 * from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
21 */
22
23#ifndef lint
24static char sccsid[] = "@(#)job.c 5.2 (Berkeley) %G%";
25#endif /* not lint */
26
27/*-
28 * job.c --
29 * handle the creation etc. of our child processes.
ab950546
KB
30 *
31 * Interface:
32 * Job_Make Start the creation of the given target.
33 *
34 * Job_CatchChildren Check for and handle the termination of any
35 * children. This must be called reasonably
36 * frequently to keep the whole make going at
37 * a decent clip, since job table entries aren't
38 * removed until their process is caught this way.
39 * Its single argument is TRUE if the function
40 * should block waiting for a child to terminate.
41 *
42 * Job_CatchOutput Print any output our children have produced.
43 * Should also be called fairly frequently to
44 * keep the user informed of what's going on.
45 * If no output is waiting, it will block for
46 * a time given by the SEL_* constants, below,
47 * or until output is ready.
48 *
49 * Job_Init Called to intialize this module. in addition,
50 * any commands attached to the .BEGIN target
51 * are executed before this function returns.
52 * Hence, the makefile must have been parsed
53 * before this function is called.
54 *
55 * Job_Full Return TRUE if the job table is filled.
56 *
57 * Job_Empty Return TRUE if the job table is completely
58 * empty.
59 *
60 * Job_ParseShell Given the line following a .SHELL target, parse
61 * the line as a shell specification. Returns
62 * FAILURE if the spec was incorrect.
63 *
64 * Job_End Perform any final processing which needs doing.
65 * This includes the execution of any commands
66 * which have been/were attached to the .END
67 * target. It should only be called when the
68 * job table is empty.
69 *
70 * Job_AbortAll Abort all currently running jobs. It doesn't
71 * handle output or do anything for the jobs,
72 * just kills them. It should only be called in
73 * an emergency, as it were.
74 *
75 * Job_CheckCommands Verify that the commands for a target are
76 * ok. Provide them if necessary and possible.
77 *
78 * Job_Touch Update a target without really updating it.
79 *
80 * Job_Wait Wait for all currently-running jobs to finish.
81 */
ab950546
KB
82
83#include <stdio.h>
84#include <string.h>
85#include <sys/types.h>
86#include <sys/signal.h>
87#include <sys/stat.h>
88#include <fcntl.h>
89#include <sys/file.h>
90#include <sys/time.h>
91#include <sys/wait.h>
92#include <ctype.h>
93#include <errno.h>
94extern int errno;
95#include "make.h"
96#include "job.h"
97
98/*
99 * Some systems define the fd_set we use, but not the macros to deal with it
100 * (SunOS 3.5, e.g.)
101 */
102#ifndef FD_SET
103
104# ifdef NEED_FD_SET
105/*
106 * Then there are the systems that don't even define fd_set...
107 */
108# ifndef FD_SETSIZE
109# define FD_SETSIZE 256
110# endif
111# ifndef NBBY
112# define NBBY 8
113# endif
114
115typedef long fd_mask;
116#define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask */
117#ifndef howmany
118#define howmany(x, y) ((unsigned int)(((x)+((y)-1)))/(unsigned int)(y))
119#endif
120
121typedef struct fd_set {
122 fd_mask fds_bits[howmany(FD_SETSIZE, NFDBITS)];
123} fd_set;
124
125# endif /* NEED_FD_SET */
126
127#define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
128#define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
129#define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
130#define FD_ZERO(p) bzero((char *)(p), sizeof(*(p)))
131
132#endif /* FD_SET */
133
134
135/*
136 * error handling variables
137 */
138int errors = 0; /* number of errors reported */
139int aborting = 0; /* why is the make aborting? */
140#define ABORT_ERROR 1 /* Because of an error */
141#define ABORT_INTERRUPT 2 /* Because it was interrupted */
142#define ABORT_WAIT 3 /* Waiting for jobs to finish */
143
144
145/*
146 * post-make command processing. The node postCommands is really just the
147 * .END target but we keep it around to avoid having to search for it
148 * all the time.
149 */
150static GNode *postCommands; /* node containing commands to execute when
151 * everything else is done */
152static int numCommands; /* The number of commands actually printed
153 * for a target. Should this number be
154 * 0, no shell will be executed. */
155
156
157/*
158 * Return values from JobStart.
159 */
160#define JOB_RUNNING 0 /* Job is running */
161#define JOB_ERROR 1 /* Error in starting the job */
162#define JOB_FINISHED 2 /* The job is already finished */
163#define JOB_STOPPED 3 /* The job is stopped */
164
165/*
166 * tfile is the name of a file into which all shell commands are put. It is
167 * used over by removing it before the child shell is executed. The XXXXX in
168 * the string are replaced by the pid of the make process in a 5-character
169 * field with leading zeroes.
170 */
171static char tfile[] = TMPPAT;
172
173
174/*
175 * Descriptions for various shells.
176 */
177static Shell shells[] = {
178 /*
179 * CSH description. The csh can do echo control by playing
180 * with the setting of the 'echo' shell variable. Sadly,
181 * however, it is unable to do error control nicely.
182 */
183{
184 "csh",
185 TRUE, "unset verbose", "set verbose", "unset verbose", 10,
186 FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"",
187 "v", "e",
188},
189 /*
190 * SH description. Echo control is also possible and, under
191 * sun UNIX anyway, one can even control error checking.
192 */
193{
194 "sh",
195 TRUE, "set -", "set -v", "set -", 5,
196#if (defined(sun) && !defined(Sprite)) || defined(SYSV)
197 TRUE, "set -e", "set +e",
198#else
199 FALSE, "echo \"%s\"\n", "sh -c '%s || exit 0'\n",
200#endif
201 "v", "e",
202},
203 /*
204 * UNKNOWN.
205 */
206{
207 (char *)0,
208 FALSE, (char *)0, (char *)0, (char *)0, 0,
209 FALSE, (char *)0, (char *)0,
210 (char *)0, (char *)0,
211}
212};
213Shell *commandShell = &shells[DEFSHELL]; /* this is the shell to
214 * which we pass all
215 * commands in the Makefile.
216 * It is set by the
217 * Job_ParseShell function */
218char *shellPath = (char *) NULL, /* full pathname of
219 * executable image */
220 *shellName; /* last component of shell */
221
222
223static int maxJobs; /* The most children we can run at once */
224static int maxLocal; /* The most local ones we can have */
225int nJobs; /* The number of children currently running */
226int nLocal; /* The number of local children */
227Lst jobs; /* The structures that describe them */
228Boolean jobFull; /* Flag to tell when the job table is full. It
229 * is set TRUE when (1) the total number of
230 * running jobs equals the maximum allowed or
231 * (2) a job can only be run locally, but
232 * nLocal equals maxLocal */
233#ifndef RMT_WILL_WATCH
234static fd_set outputs; /* Set of descriptors of pipes connected to
235 * the output channels of children */
236#endif
237
238GNode *lastNode; /* The node for which output was most recently
239 * produced. */
240char *targFmt; /* Format string to use to head output from a
241 * job when it's not the most-recent job heard
242 * from */
243#define TARG_FMT "--- %s ---\n" /* Default format */
244
245/*
246 * When JobStart attempts to run a job remotely but can't, and isn't allowed
247 * to run the job locally, or when Job_CatchChildren detects a job that has
248 * been migrated home, the job is placed on the stoppedJobs queue to be run
249 * when the next job finishes.
250 */
251Lst stoppedJobs; /* Lst of Job structures describing
252 * jobs that were stopped due to concurrency
253 * limits or migration home */
254
255
256#if defined(USE_PGRP) && defined(SYSV)
257#define KILL(pid,sig) killpg(-(pid),(sig))
258#else
259# if defined(USE_PGRP)
260#define KILL(pid,sig) killpg((pid),(sig))
261# else
262#define KILL(pid,sig) kill((pid),(sig))
263# endif
264#endif
265
266static void JobRestart();
267static int JobStart();
268static void JobInterrupt();
269\f
270/*-
271 *-----------------------------------------------------------------------
272 * JobCondPassSig --
273 * Pass a signal to a job if the job is remote or if USE_PGRP
274 * is defined.
275 *
276 * Results:
277 * === 0
278 *
279 * Side Effects:
280 * None, except the job may bite it.
281 *
282 *-----------------------------------------------------------------------
283 */
284static int
285JobCondPassSig(job, signo)
286 Job *job; /* Job to biff */
287 int signo; /* Signal to send it */
288{
289#ifdef RMT_WANTS_SIGNALS
290 if (job->flags & JOB_REMOTE) {
291 (void)Rmt_Signal(job, signo);
292 } else {
293 KILL(job->pid, signo);
294 }
295#else
296 /*
297 * Assume that sending the signal to job->pid will signal any remote
298 * job as well.
299 */
300 KILL(job->pid, signo);
301#endif
302 return(0);
303}
304
305/*-
306 *-----------------------------------------------------------------------
307 * JobPassSig --
308 * Pass a signal on to all remote jobs and to all local jobs if
309 * USE_PGRP is defined, then die ourselves.
310 *
311 * Results:
312 * None.
313 *
314 * Side Effects:
315 * We die by the same signal.
316 *
317 *-----------------------------------------------------------------------
318 */
319static void
320JobPassSig(signo)
321 int signo; /* The signal number we've received */
322{
323 int mask;
324
325 Lst_ForEach(jobs, JobCondPassSig, (ClientData)signo);
326
327 /*
328 * Deal with proper cleanup based on the signal received. We only run
329 * the .INTERRUPT target if the signal was in fact an interrupt. The other
330 * three termination signals are more of a "get out *now*" command.
331 */
332 if (signo == SIGINT) {
333 JobInterrupt(TRUE);
334 } else if ((signo == SIGHUP) || (signo == SIGTERM) || (signo == SIGQUIT)) {
335 JobInterrupt(FALSE);
336 }
337
338 /*
339 * Leave gracefully if SIGQUIT, rather than core dumping.
340 */
341 if (signo == SIGQUIT) {
342 Finish();
343 }
344
345 /*
346 * Send ourselves the signal now we've given the message to everyone else.
347 * Note we block everything else possible while we're getting the signal.
348 * This ensures that all our jobs get continued when we wake up before
349 * we take any other signal.
350 */
351 mask = sigblock(0);
352 (void) sigsetmask(~0 & ~(1 << (signo-1)));
353 signal(signo, SIG_DFL);
354
355 kill(getpid(), signo);
356
357 Lst_ForEach(jobs, JobCondPassSig, (ClientData)SIGCONT);
358
359 sigsetmask(mask);
360 signal(signo, JobPassSig);
361
362}
363\f
364/*-
365 *-----------------------------------------------------------------------
366 * JobCmpPid --
367 * Compare the pid of the job with the given pid and return 0 if they
368 * are equal. This function is called from Job_CatchChildren via
369 * Lst_Find to find the job descriptor of the finished job.
370 *
371 * Results:
372 * 0 if the pid's match
373 *
374 * Side Effects:
375 * None
376 *-----------------------------------------------------------------------
377 */
378static int
379JobCmpPid (job, pid)
380 int pid; /* process id desired */
381 Job *job; /* job to examine */
382{
383 return (pid - job->pid);
384}
385\f
386/*-
387 *-----------------------------------------------------------------------
388 * JobPrintCommand --
389 * Put out another command for the given job. If the command starts
390 * with an @ or a - we process it specially. In the former case,
391 * so long as the -s and -n flags weren't given to make, we stick
392 * a shell-specific echoOff command in the script. In the latter,
393 * we ignore errors for the entire job, unless the shell has error
394 * control.
395 * If the command is just "..." we take all future commands for this
396 * job to be commands to be executed once the entire graph has been
397 * made and return non-zero to signal that the end of the commands
398 * was reached. These commands are later attached to the postCommands
399 * node and executed by Job_End when all things are done.
400 * This function is called from JobStart via Lst_ForEach.
401 *
402 * Results:
403 * Always 0, unless the command was "..."
404 *
405 * Side Effects:
406 * If the command begins with a '-' and the shell has no error control,
407 * the JOB_IGNERR flag is set in the job descriptor.
408 * If the command is "..." and we're not ignoring such things,
409 * tailCmds is set to the successor node of the cmd.
410 * numCommands is incremented if the command is actually printed.
411 *-----------------------------------------------------------------------
412 */
413static int
414JobPrintCommand (cmd, job)
415 char *cmd; /* command string to print */
416 Job *job; /* job for which to print it */
417{
418 Boolean noSpecials; /* true if we shouldn't worry about
419 * inserting special commands into
420 * the input stream. */
421 Boolean shutUp = FALSE; /* true if we put a no echo command
422 * into the command file */
423 Boolean errOff = FALSE; /* true if we turned error checking
424 * off before printing the command
425 * and need to turn it back on */
426 char *cmdTemplate; /* Template to use when printing the
427 * command */
428 char *cmdStart; /* Start of expanded command */
429 LstNode cmdNode; /* Node for replacing the command */
430
431 noSpecials = (noExecute && ! (job->node->type & OP_MAKE));
432
433 if (strcmp (cmd, "...") == 0) {
434 if ((job->flags & JOB_IGNDOTS) == 0) {
435 job->tailCmds = Lst_Succ (Lst_Member (job->node->commands,
436 (ClientData)cmd));
437 return (1);
438 }
439 return (0);
440 }
441
442#define DBPRINTF(fmt, arg) if (DEBUG(JOB)) printf (fmt, arg); fprintf (job->cmdFILE, fmt, arg)
443
444 numCommands += 1;
445
446 /*
447 * For debugging, we replace each command with the result of expanding
448 * the variables in the command.
449 */
450 cmdNode = Lst_Member (job->node->commands, (ClientData)cmd);
451 cmdStart = cmd = Var_Subst (cmd, job->node, FALSE);
452 Lst_Replace (cmdNode, (ClientData)cmdStart);
453
454 cmdTemplate = "%s\n";
455
456 /*
457 * Check for leading @' and -'s to control echoing and error checking.
458 */
459 while (*cmd == '@' || *cmd == '-') {
460 if (*cmd == '@') {
461 shutUp = TRUE;
462 } else {
463 errOff = TRUE;
464 }
465 cmd++;
466 }
467
468 if (shutUp) {
469 if (! (job->flags & JOB_SILENT) && !noSpecials &&
470 commandShell->hasEchoCtl) {
471 DBPRINTF ("%s\n", commandShell->echoOff);
472 } else {
473 shutUp = FALSE;
474 }
475 }
476
477 if (errOff) {
478 if ( ! (job->flags & JOB_IGNERR) && !noSpecials) {
479 if (commandShell->hasErrCtl) {
480 /*
481 * we don't want the error-control commands showing
482 * up either, so we turn off echoing while executing
483 * them. We could put another field in the shell
484 * structure to tell JobDoOutput to look for this
485 * string too, but why make it any more complex than
486 * it already is?
487 */
488 if (! (job->flags & JOB_SILENT) && !shutUp &&
489 commandShell->hasEchoCtl) {
490 DBPRINTF ("%s\n", commandShell->echoOff);
491 DBPRINTF ("%s\n", commandShell->ignErr);
492 DBPRINTF ("%s\n", commandShell->echoOn);
493 } else {
494 DBPRINTF ("%s\n", commandShell->ignErr);
495 }
496 } else if (commandShell->ignErr &&
497 (*commandShell->ignErr != '\0'))
498 {
499 /*
500 * The shell has no error control, so we need to be
501 * weird to get it to ignore any errors from the command.
502 * If echoing is turned on, we turn it off and use the
503 * errCheck template to echo the command. Leave echoing
504 * off so the user doesn't see the weirdness we go through
505 * to ignore errors. Set cmdTemplate to use the weirdness
506 * instead of the simple "%s\n" template.
507 */
508 if (! (job->flags & JOB_SILENT) && !shutUp &&
509 commandShell->hasEchoCtl) {
510 DBPRINTF ("%s\n", commandShell->echoOff);
511 DBPRINTF (commandShell->errCheck, cmd);
512 shutUp = TRUE;
513 }
514 cmdTemplate = commandShell->ignErr;
515 /*
516 * The error ignoration (hee hee) is already taken care
517 * of by the ignErr template, so pretend error checking
518 * is still on.
519 */
520 errOff = FALSE;
521 } else {
522 errOff = FALSE;
523 }
524 } else {
525 errOff = FALSE;
526 }
527 }
528
529 DBPRINTF (cmdTemplate, cmd);
530
531 if (errOff) {
532 /*
533 * If echoing is already off, there's no point in issuing the
534 * echoOff command. Otherwise we issue it and pretend it was on
535 * for the whole command...
536 */
537 if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl){
538 DBPRINTF ("%s\n", commandShell->echoOff);
539 shutUp = TRUE;
540 }
541 DBPRINTF ("%s\n", commandShell->errCheck);
542 }
543 if (shutUp) {
544 DBPRINTF ("%s\n", commandShell->echoOn);
545 }
546 return (0);
547}
548\f
549/*-
550 *-----------------------------------------------------------------------
551 * JobSaveCommand --
552 * Save a command to be executed when everything else is done.
553 * Callback function for JobFinish...
554 *
555 * Results:
556 * Always returns 0
557 *
558 * Side Effects:
559 * The command is tacked onto the end of postCommands's commands list.
560 *
561 *-----------------------------------------------------------------------
562 */
563static int
564JobSaveCommand (cmd, gn)
565 char *cmd;
566 GNode *gn;
567{
568 cmd = Var_Subst (cmd, gn, FALSE);
569 (void)Lst_AtEnd (postCommands->commands, (ClientData)cmd);
570 return (0);
571}
572\f
573/*-
574 *-----------------------------------------------------------------------
575 * JobFinish --
576 * Do final processing for the given job including updating
577 * parents and starting new jobs as available/necessary. Note
578 * that we pay no attention to the JOB_IGNERR flag here.
579 * This is because when we're called because of a noexecute flag
580 * or something, jstat.w_status is 0 and when called from
581 * Job_CatchChildren, the status is zeroed if it s/b ignored.
582 *
583 * Results:
584 * None
585 *
586 * Side Effects:
587 * Some nodes may be put on the toBeMade queue.
588 * Final commands for the job are placed on postCommands.
589 *
590 * If we got an error and are aborting (aborting == ABORT_ERROR) and
591 * the job list is now empty, we are done for the day.
592 * If we recognized an error (errors !=0), we set the aborting flag
593 * to ABORT_ERROR so no more jobs will be started.
594 *-----------------------------------------------------------------------
595 */
596/*ARGSUSED*/
597void
598JobFinish (job, status)
599 Job *job; /* job to finish */
600 union wait status; /* sub-why job went away */
601{
602 Boolean done;
603
604 if ((WIFEXITED(status) &&
605 (((status.w_retcode != 0) && !(job->flags & JOB_IGNERR)) ||
606 !backwards)) ||
607 (WIFSIGNALED(status) && (status.w_termsig != SIGCONT)))
608 {
609 /*
610 * If it exited non-zero and either we're doing things our
611 * way or we're not ignoring errors, the job is finished.
612 * Similarly, if the shell died because of a signal (the
613 * conditional on SIGCONT is to handle the mapping of Sprite
614 * signal semantics whereby wait will return a signal
615 * termination with SIGCONT being the signal to indicate that the
616 * child has resumed), the job is also finished. In these
617 * cases, finish out the job's output before printing the exit
618 * status...
619 */
620 if (usePipes) {
621#ifdef RMT_WILL_WATCH
622 Rmt_Ignore(job->inPipe);
623#else
624 FD_CLR(job->inPipe, &outputs);
625#endif /* RMT_WILL_WATCH */
626 if (job->outPipe != job->inPipe) {
627 (void)close (job->outPipe);
628 }
629 JobDoOutput (job, TRUE);
630 (void)close (job->inPipe);
631 } else {
632 (void)close (job->outFd);
633 JobDoOutput (job, TRUE);
634 }
635
636 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
637 fclose(job->cmdFILE);
638 }
639 done = TRUE;
640 } else if (backwards && WIFEXITED(status) && status.w_retcode != 0) {
641 /*
642 * Deal with ignored errors in -B mode. We need to print a message
643 * telling of the ignored error as well as setting status.w_status
644 * to 0 so the next command gets run. To do this, we set done to be
645 * TRUE if in -B mode and the job exited non-zero. Note we don't
646 * want to close down any of the streams until we know we're at the
647 * end.
648 */
649 done = TRUE;
650 } else {
651 /*
652 * No need to close things down or anything.
653 */
654 done = FALSE;
655 }
656
657 if (done ||
658 WIFSTOPPED(status) ||
659 (WIFSIGNALED(status) && (status.w_termsig == SIGCONT)) ||
660 DEBUG(JOB))
661 {
662 FILE *out;
663
664 if (backwards && !usePipes && (job->flags & JOB_IGNERR)) {
665 /*
666 * If output is going to a file and this job is ignoring
667 * errors, arrange to have the exit status sent to the
668 * output file as well.
669 */
670 out = fdopen (job->outFd, "w");
671 } else {
672 out = stdout;
673 }
674
675 if (WIFEXITED(status)) {
676 if (status.w_retcode != 0) {
677 if (usePipes && job->node != lastNode) {
678 fprintf (out, targFmt, job->node->name);
679 lastNode = job->node;
680 }
681 fprintf (out, "*** Error code %d%s\n", status.w_retcode,
682 (job->flags & JOB_IGNERR) ? " (ignored)" : "");
683
684 if (job->flags & JOB_IGNERR) {
685 status.w_status = 0;
686 }
687 } else if (DEBUG(JOB)) {
688 if (usePipes && job->node != lastNode) {
689 fprintf (out, targFmt, job->node->name);
690 lastNode = job->node;
691 }
692 fprintf (out, "*** Completed successfully\n");
693 }
694 } else if (WIFSTOPPED(status)) {
695 if (usePipes && job->node != lastNode) {
696 fprintf (out, targFmt, job->node->name);
697 lastNode = job->node;
698 }
699 if (! (job->flags & JOB_REMIGRATE)) {
700 fprintf (out, "*** Stopped -- signal %d\n", status.w_stopsig);
701 }
702 job->flags |= JOB_RESUME;
703 (void)Lst_AtEnd(stoppedJobs, (ClientData)job);
704 fflush(out);
705 return;
706 } else if (status.w_termsig == SIGCONT) {
707 /*
708 * If the beastie has continued, shift the Job from the stopped
709 * list to the running one (or re-stop it if concurrency is
710 * exceeded) and go and get another child.
711 */
712 if (job->flags & (JOB_RESUME|JOB_REMIGRATE|JOB_RESTART)) {
713 if (usePipes && job->node != lastNode) {
714 fprintf (out, targFmt, job->node->name);
715 lastNode = job->node;
716 }
717 fprintf (out, "*** Continued\n");
718 }
719 if (! (job->flags & JOB_CONTINUING)) {
720 JobRestart(job);
721 } else {
722 Lst_AtEnd(jobs, (ClientData)job);
723 nJobs += 1;
724 if (! (job->flags & JOB_REMOTE)) {
725 nLocal += 1;
726 }
727 if (nJobs == maxJobs) {
728 jobFull = TRUE;
729 if (DEBUG(JOB)) {
730 printf("Job queue is full.\n");
731 }
732 }
733 }
734 fflush(out);
735 return;
736 } else {
737 if (usePipes && job->node != lastNode) {
738 fprintf (out, targFmt, job->node->name);
739 lastNode = job->node;
740 }
741 fprintf (out, "*** Signal %d\n", status.w_termsig);
742 }
743
744 fflush (out);
745 }
746
747 /*
748 * Now handle the -B-mode stuff. If the beast still isn't finished,
749 * try and restart the job on the next command. If JobStart says it's
750 * ok, it's ok. If there's an error, this puppy is done.
751 */
752 if (backwards && (status.w_status == 0) &&
753 !Lst_IsAtEnd (job->node->commands))
754 {
755 switch (JobStart (job->node,
756 job->flags & JOB_IGNDOTS,
757 job))
758 {
759 case JOB_RUNNING:
760 done = FALSE;
761 break;
762 case JOB_ERROR:
763 done = TRUE;
764 status.w_retcode = 1;
765 break;
766 case JOB_FINISHED:
767 /*
768 * If we got back a JOB_FINISHED code, JobStart has already
769 * called Make_Update and freed the job descriptor. We set
770 * done to false here to avoid fake cycles and double frees.
771 * JobStart needs to do the update so we can proceed up the
772 * graph when given the -n flag..
773 */
774 done = FALSE;
775 break;
776 }
777 } else {
778 done = TRUE;
779 }
780
781
782 if (done &&
783 (aborting != ABORT_ERROR) &&
784 (aborting != ABORT_INTERRUPT) &&
785 (status.w_status == 0))
786 {
787 /*
788 * As long as we aren't aborting and the job didn't return a non-zero
789 * status that we shouldn't ignore, we call Make_Update to update
790 * the parents. In addition, any saved commands for the node are placed
791 * on the .END target.
792 */
793 if (job->tailCmds != NILLNODE) {
794 Lst_ForEachFrom (job->node->commands, job->tailCmds,
795 JobSaveCommand,
796 (ClientData)job->node);
797 }
798 job->node->made = MADE;
799 Make_Update (job->node);
800 free((Address)job);
801 } else if (status.w_status) {
802 errors += 1;
803 free((Address)job);
804 }
805
806 while (!errors && !jobFull && !Lst_IsEmpty(stoppedJobs)) {
807 JobRestart((Job *)Lst_DeQueue(stoppedJobs));
808 }
809
810 /*
811 * Set aborting if any error.
812 */
813 if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
814 /*
815 * If we found any errors in this batch of children and the -k flag
816 * wasn't given, we set the aborting flag so no more jobs get
817 * started.
818 */
819 aborting = ABORT_ERROR;
820 }
821
822 if ((aborting == ABORT_ERROR) && Job_Empty()) {
823 /*
824 * If we are aborting and the job table is now empty, we finish.
825 */
826 (void) unlink (tfile);
827 Finish (errors);
828 }
829}
830\f
831/*-
832 *-----------------------------------------------------------------------
833 * Job_Touch --
834 * Touch the given target. Called by JobStart when the -t flag was
835 * given
836 *
837 * Results:
838 * None
839 *
840 * Side Effects:
841 * The data modification of the file is changed. In addition, if the
842 * file did not exist, it is created.
843 *-----------------------------------------------------------------------
844 */
845void
846Job_Touch (gn, silent)
847 GNode *gn; /* the node of the file to touch */
848 Boolean silent; /* TRUE if should not print messages */
849{
850 int streamID; /* ID of stream opened to do the touch */
851 struct timeval times[2]; /* Times for utimes() call */
852 struct stat attr; /* Attributes of the file */
853
854 if (gn->type & (OP_JOIN|OP_USE|OP_EXEC|OP_DONTCARE)) {
855 /*
856 * .JOIN, .USE, .ZEROTIME and .DONTCARE targets are "virtual" targets
857 * and, as such, shouldn't really be created.
858 */
859 return;
860 }
861
862 if (!silent) {
863 printf ("touch %s\n", gn->name);
864 }
865
866 if (noExecute) {
867 return;
868 }
869
870 if (gn->type & OP_ARCHV) {
871 Arch_Touch (gn);
872 } else if (gn->type & OP_LIB) {
873 Arch_TouchLib (gn);
874 } else {
875 char *file = gn->path ? gn->path : gn->name;
876
877 times[0].tv_sec = times[1].tv_sec = now;
878 times[0].tv_usec = times[1].tv_usec = 0;
879 if (utimes(file, times) < 0){
880 streamID = open (file, O_RDWR | O_CREAT, 0666);
881
882 if (streamID >= 0) {
883 char c;
884
885 /*
886 * Read and write a byte to the file to change the
887 * modification time, then close the file.
888 */
889 if (read(streamID, &c, 1) == 1) {
890 lseek(streamID, 0L, L_SET);
891 write(streamID, &c, 1);
892 }
893
894 (void)close (streamID);
895 } else {
896 extern char *sys_errlist[];
897
898 printf("*** couldn't touch %s: %s", file, sys_errlist[errno]);
899 }
900 }
901 }
902}
903\f
904/*-
905 *-----------------------------------------------------------------------
906 * Job_CheckCommands --
907 * Make sure the given node has all the commands it needs.
908 *
909 * Results:
910 * TRUE if the commands list is/was ok.
911 *
912 * Side Effects:
913 * The node will have commands from the .DEFAULT rule added to it
914 * if it needs them.
915 *-----------------------------------------------------------------------
916 */
917Boolean
918Job_CheckCommands (gn, abortProc)
919 GNode *gn; /* The target whose commands need
920 * verifying */
921 void (*abortProc)(); /* Function to abort with message */
922{
923 if (OP_NOP(gn->type) && Lst_IsEmpty (gn->commands) &&
924 (gn->type & OP_LIB) == 0) {
925 /*
926 * No commands. Look for .DEFAULT rule from which we might infer
927 * commands
928 */
929 if ((DEFAULT != NILGNODE) && !Lst_IsEmpty(DEFAULT->commands)) {
930 /*
931 * Make only looks for a .DEFAULT if the node was never the
932 * target of an operator, so that's what we do too. If
933 * a .DEFAULT was given, we substitute its commands for gn's
934 * commands and set the IMPSRC variable to be the target's name
935 * The DEFAULT node acts like a transformation rule, in that
936 * gn also inherits any attributes or sources attached to
937 * .DEFAULT itself.
938 */
939 Make_HandleUse(DEFAULT, gn);
940 Var_Set (IMPSRC, Var_Value (TARGET, gn), gn);
941 } else if (Dir_MTime (gn) == 0) {
942 /*
943 * The node wasn't the target of an operator we have no .DEFAULT
944 * rule to go on and the target doesn't already exist. There's
945 * nothing more we can do for this branch. If the -k flag wasn't
946 * given, we stop in our tracks, otherwise we just don't update
947 * this node's parents so they never get examined.
948 */
949 if (gn->type & OP_DONTCARE) {
950 printf ("Can't figure out how to make %s (ignored)\n",
951 gn->name);
952 } else if (keepgoing) {
953 printf ("Can't figure out how to make %s (continuing)\n",
954 gn->name);
955 return (FALSE);
956 } else {
957 (*abortProc) ("Can't figure out how to make %s. Stop",
958 gn->name);
959 return(FALSE);
960 }
961 }
962 }
963 return (TRUE);
964}
965#ifdef RMT_WILL_WATCH
966/*-
967 *-----------------------------------------------------------------------
968 * JobLocalInput --
969 * Handle a pipe becoming readable. Callback function for Rmt_Watch
970 *
971 * Results:
972 * None
973 *
974 * Side Effects:
975 * JobDoOutput is called.
976 *
977 *-----------------------------------------------------------------------
978 */
979/*ARGSUSED*/
980static void
981JobLocalInput(stream, job)
982 int stream; /* Stream that's ready (ignored) */
983 Job *job; /* Job to which the stream belongs */
984{
985 JobDoOutput(job, FALSE);
986}
987#endif /* RMT_WILL_WATCH */
988\f
989/*-
990 *-----------------------------------------------------------------------
991 * JobExec --
992 * Execute the shell for the given job. Called from JobStart and
993 * JobRestart.
994 *
995 * Results:
996 * None.
997 *
998 * Side Effects:
999 * A shell is executed, outputs is altered and the Job structure added
1000 * to the job table.
1001 *
1002 *-----------------------------------------------------------------------
1003 */
1004static void
1005JobExec(job, argv)
1006 Job *job; /* Job to execute */
1007 char **argv;
1008{
1009 int cpid; /* ID of new child */
1010
1011 if (DEBUG(JOB)) {
1012 int i;
1013
1014 printf("Running %s %sly\n", job->node->name,
1015 job->flags&JOB_REMOTE?"remote":"local");
1016 printf("\tCommand: ");
1017 for (i = 0; argv[i] != (char *)NULL; i++) {
1018 printf("%s ", argv[i]);
1019 }
1020 printf("\n");
1021 }
1022
1023 /*
1024 * Some jobs produce no output and it's disconcerting to have
1025 * no feedback of their running (since they produce no output, the
1026 * banner with their name in it never appears). This is an attempt to
1027 * provide that feedback, even if nothing follows it.
1028 */
1029 if ((lastNode != job->node) && (job->flags & JOB_FIRST) &&
1030 !(job->flags & JOB_SILENT))
1031 {
1032 printf(targFmt, job->node->name);
1033 lastNode = job->node;
1034 }
1035
1036#ifdef RMT_NO_EXEC
1037 if (job->flags & JOB_REMOTE) {
1038 goto jobExecFinish;
1039 }
1040#endif /* RMT_NO_EXEC */
1041
1042 if ((cpid = vfork()) == -1) {
1043 Punt ("Cannot fork");
1044 } else if (cpid == 0) {
1045
1046 /*
1047 * Must duplicate the input stream down to the child's input and
1048 * reset it to the beginning (again). Since the stream was marked
1049 * close-on-exec, we must clear that bit in the new input.
1050 */
1051 (void) dup2(fileno(job->cmdFILE), 0);
1052 fcntl(0, F_SETFD, 0);
1053 lseek(0, 0, L_SET);
1054
1055 if (usePipes) {
1056 /*
1057 * Set up the child's output to be routed through the pipe
1058 * we've created for it.
1059 */
1060 (void) dup2 (job->outPipe, 1);
1061 } else {
1062 /*
1063 * We're capturing output in a file, so we duplicate the
1064 * descriptor to the temporary file into the standard
1065 * output.
1066 */
1067 (void) dup2 (job->outFd, 1);
1068 }
1069 /*
1070 * The output channels are marked close on exec. This bit was
1071 * duplicated by the dup2 (on some systems), so we have to clear
1072 * it before routing the shell's error output to the same place as
1073 * its standard output.
1074 */
1075 fcntl(1, F_SETFD, 0);
1076 (void) dup2 (1, 2);
1077
1078#ifdef USE_PGRP
1079 /*
1080 * We want to switch the child into a different process family so
1081 * we can kill it and all its descendants in one fell swoop,
1082 * by killing its process family, but not commit suicide.
1083 */
1084
1085#if defined(SYSV)
1086 (void) setpgrp();
1087#else
1088 (void) setpgrp(0, getpid());
1089#endif
1090#endif USE_PGRP
1091
1092 if (job->flags & JOB_REMOTE) {
1093 Rmt_Exec (shellPath, argv, FALSE);
1094 } else {
1095 (void) execv (shellPath, argv);
1096 }
1097
1098 (void) write (2, "Could not execute shell\n",
1099 sizeof ("Could not execute shell"));
1100 _exit (1);
1101 } else {
1102 job->pid = cpid;
1103
1104 if (usePipes && (job->flags & JOB_FIRST) ) {
1105 /*
1106 * The first time a job is run for a node, we set the current
1107 * position in the buffer to the beginning and mark another
1108 * stream to watch in the outputs mask
1109 */
1110 job->curPos = 0;
1111
1112#ifdef RMT_WILL_WATCH
1113 Rmt_Watch(job->inPipe, JobLocalInput, job);
1114#else
1115 FD_SET(job->inPipe, &outputs);
1116#endif /* RMT_WILL_WATCH */
1117 }
1118
1119 if (job->flags & JOB_REMOTE) {
1120 job->rmtID = (char *)Rmt_LastID(job->pid);
1121 } else {
1122 nLocal += 1;
1123 /*
1124 * XXX: Used to not happen if CUSTOMS. Why?
1125 */
1126 if (job->cmdFILE != stdout) {
1127 fclose(job->cmdFILE);
1128 job->cmdFILE = NULL;
1129 }
1130 }
1131 }
1132
1133jobExecFinish:
1134 /*
1135 * Now the job is actually running, add it to the table.
1136 */
1137 nJobs += 1;
1138 (void)Lst_AtEnd (jobs, (ClientData)job);
1139 if (nJobs == maxJobs) {
1140 jobFull = TRUE;
1141 }
1142}
1143\f
1144/*-
1145 *-----------------------------------------------------------------------
1146 * JobMakeArgv --
1147 * Create the argv needed to execute the shell for a given job.
1148 *
1149 *
1150 * Results:
1151 *
1152 * Side Effects:
1153 *
1154 *-----------------------------------------------------------------------
1155 */
1156static void
1157JobMakeArgv(job, argv)
1158 Job *job;
1159 char **argv;
1160{
1161 int argc;
1162 static char args[10]; /* For merged arguments */
1163
1164 argv[0] = shellName;
1165 argc = 1;
1166
1167 if ((commandShell->exit && (*commandShell->exit != '-')) ||
1168 (commandShell->echo && (*commandShell->echo != '-')))
1169 {
1170 /*
1171 * At least one of the flags doesn't have a minus before it, so
1172 * merge them together. Have to do this because the *(&(@*#*&#$#
1173 * Bourne shell thinks its second argument is a file to source.
1174 * Grrrr. Note the ten-character limitation on the combined arguments.
1175 */
1176 (void)sprintf(args, "-%s%s",
1177 ((job->flags & JOB_IGNERR) ? "" :
1178 (commandShell->exit ? commandShell->exit : "")),
1179 ((job->flags & JOB_SILENT) ? "" :
1180 (commandShell->echo ? commandShell->echo : "")));
1181
1182 if (args[1]) {
1183 argv[argc] = args;
1184 argc++;
1185 }
1186 } else {
1187 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1188 argv[argc] = commandShell->exit;
1189 argc++;
1190 }
1191 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1192 argv[argc] = commandShell->echo;
1193 argc++;
1194 }
1195 }
1196 argv[argc] = (char *)NULL;
1197}
1198\f
1199/*-
1200 *-----------------------------------------------------------------------
1201 * JobRestart --
1202 * Restart a job that stopped for some reason. If the job stopped
1203 * because it migrated home again, we tell the Rmt module to
1204 * find a new home for it and make it runnable if Rmt_ReExport
1205 * succeeded (if it didn't and the job may be run locally, we
1206 * simply resume it). If the job didn't run and can now, we run it.
1207 *
1208 * Results:
1209 * None.
1210 *
1211 * Side Effects:
1212 * jobFull will be set if the job couldn't be run.
1213 *
1214 *-----------------------------------------------------------------------
1215 */
1216static void
1217JobRestart(job)
1218 Job *job; /* Job to restart */
1219{
1220 if (job->flags & JOB_REMIGRATE) {
1221 if (DEBUG(JOB)) {
1222 printf("Remigrating %x\n", job->pid);
1223 }
1224 if (!Rmt_ReExport(job->pid)) {
1225 if (DEBUG(JOB)) {
1226 printf("Couldn't migrate...");
1227 }
1228 if (nLocal != maxLocal) {
1229 /*
1230 * Job cannot be remigrated, but there's room on the local
1231 * machine, so resume the job and note that another
1232 * local job has started.
1233 */
1234 if (DEBUG(JOB)) {
1235 printf("resuming on local machine\n");
1236 }
1237 KILL(job->pid, SIGCONT);
1238 nLocal +=1;
1239 job->flags &= ~(JOB_REMIGRATE|JOB_RESUME);
1240 } else {
1241 /*
1242 * Job cannot be restarted. Mark the table as full and
1243 * place the job back on the list of stopped jobs.
1244 */
1245 if (DEBUG(JOB)) {
1246 printf("holding\n");
1247 }
1248 (void)Lst_AtFront(stoppedJobs, (ClientData)job);
1249 jobFull = TRUE;
1250 if (DEBUG(JOB)) {
1251 printf("Job queue is full.\n");
1252 }
1253 return;
1254 }
1255 } else {
1256 /*
1257 * Clear out the remigrate and resume flags. If MIGRATE was set,
1258 * leave that around for JobFinish to see so it doesn't print out
1259 * that the job was continued.
1260 */
1261 job->flags &= ~(JOB_REMIGRATE|JOB_RESUME);
1262 }
1263
1264 (void)Lst_AtEnd(jobs, (ClientData)job);
1265 nJobs += 1;
1266 if (nJobs == maxJobs) {
1267 jobFull = TRUE;
1268 if (DEBUG(JOB)) {
1269 printf("Job queue is full.\n");
1270 }
1271 }
1272 } else if (job->flags & JOB_RESTART) {
1273 /*
1274 * Set up the control arguments to the shell. This is based on the
1275 * flags set earlier for this job. If the JOB_IGNERR flag is clear,
1276 * the 'exit' flag of the commandShell is used to cause it to exit
1277 * upon receiving an error. If the JOB_SILENT flag is clear, the
1278 * 'echo' flag of the commandShell is used to get it to start echoing
1279 * as soon as it starts processing commands.
1280 */
1281 char *argv[4];
1282
1283 JobMakeArgv(job, argv);
1284
1285 if (DEBUG(JOB)) {
1286 printf("Restarting %s...", job->node->name);
1287 }
1288 if ((job->node->type&OP_NOEXPORT) ||
1289#ifdef RMT_NO_EXEC
1290 !Rmt_Export(shellPath, argv, job)
1291#else
1292 !Rmt_Begin(shellPath, argv, job->node)
1293#endif
1294 )
1295 {
1296 if (
1297#ifdef sparc /* KLUDGE */
1298 (job->node->type & OP_M68020) ||
1299#endif
1300 ((nLocal >= maxLocal) && ! (job->flags & JOB_SPECIAL)))
1301 {
1302 /*
1303 * Can't be exported and not allowed to run locally -- put it
1304 * back on the hold queue and mark the table full
1305 */
1306 if (DEBUG(JOB)) {
1307 printf("holding\n");
1308 }
1309 (void)Lst_AtFront(stoppedJobs, (ClientData)job);
1310 jobFull = TRUE;
1311 if (DEBUG(JOB)) {
1312 printf("Job queue is full.\n");
1313 }
1314 return;
1315 } else {
1316 /*
1317 * Job may be run locally.
1318 */
1319 if (DEBUG(JOB)) {
1320 printf("running locally\n");
1321 }
1322 job->flags &= ~JOB_REMOTE;
1323 }
1324 } else {
1325 /*
1326 * Can be exported. Hooray!
1327 */
1328 if (DEBUG(JOB)) {
1329 printf("exporting\n");
1330 }
1331 job->flags |= JOB_REMOTE;
1332 }
1333 JobExec(job, argv);
1334 } else {
1335 /*
1336 * The job has stopped and needs to be restarted. Why it stopped,
1337 * we don't know...
1338 */
1339 if (DEBUG(JOB)) {
1340 printf("Resuming %s...", job->node->name);
1341 }
1342 if (((job->flags & JOB_REMOTE) ||
1343 (nLocal < maxLocal) ||
1344 (((job->flags & JOB_SPECIAL) ||
1345 (job->node->type & OP_NOEXPORT)) &&
1346 (maxLocal == 0))) &&
1347 (nJobs != maxJobs))
1348 {
1349 /*
1350 * If the job is remote, it's ok to resume it as long as the
1351 * maximum concurrency won't be exceeded. If it's local and
1352 * we haven't reached the local concurrency limit already (or the
1353 * job must be run locally and maxLocal is 0), it's also ok to
1354 * resume it.
1355 */
1356 Boolean error;
1357 extern int errno;
1358 extern char *sys_errlist[];
1359 union wait status;
1360
1361#ifdef RMT_WANTS_SIGNALS
1362 if (job->flags & JOB_REMOTE) {
1363 error = !Rmt_Signal(job, SIGCONT);
1364 } else
1365#endif /* RMT_WANTS_SIGNALS */
1366 error = (KILL(job->pid, SIGCONT) != 0);
1367
1368 if (!error) {
1369 /*
1370 * Make sure the user knows we've continued the beast and
1371 * actually put the thing in the job table.
1372 */
1373 job->flags |= JOB_CONTINUING;
1374 status.w_termsig = SIGCONT;
1375 JobFinish(job, status);
1376
1377 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1378 if (DEBUG(JOB)) {
1379 printf("done\n");
1380 }
1381 } else {
1382 Error("couldn't resume %s: %s", job->node->name,
1383 sys_errlist[errno]);
1384 status.w_status = 0;
1385 status.w_retcode = 1;
1386 JobFinish(job, status);
1387 }
1388 } else {
1389 /*
1390 * Job cannot be restarted. Mark the table as full and
1391 * place the job back on the list of stopped jobs.
1392 */
1393 if (DEBUG(JOB)) {
1394 printf("table full\n");
1395 }
1396 (void)Lst_AtFront(stoppedJobs, (ClientData)job);
1397 jobFull = TRUE;
1398 if (DEBUG(JOB)) {
1399 printf("Job queue is full.\n");
1400 }
1401 }
1402 }
1403}
1404\f
1405/*-
1406 *-----------------------------------------------------------------------
1407 * JobStart --
1408 * Start a target-creation process going for the target described
1409 * by the graph node gn.
1410 *
1411 * Results:
1412 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1413 * if there isn't actually anything left to do for the job and
1414 * JOB_RUNNING if the job has been started.
1415 *
1416 * Side Effects:
1417 * A new Job node is created and added to the list of running
1418 * jobs. PMake is forked and a child shell created.
1419 *-----------------------------------------------------------------------
1420 */
1421static int
1422JobStart (gn, flags, previous)
1423 GNode *gn; /* target to create */
1424 short flags; /* flags for the job to override normal ones.
1425 * e.g. JOB_SPECIAL or JOB_IGNDOTS */
1426 Job *previous; /* The previous Job structure for this node,
1427 * if any. */
1428{
1429 register Job *job; /* new job descriptor */
1430 char *argv[4]; /* Argument vector to shell */
1431 char args[5]; /* arguments to shell */
1432 static int jobno = 0; /* job number of catching output in a file */
1433 Boolean cmdsOK; /* true if the nodes commands were all right */
1434 Boolean local; /* Set true if the job was run locally */
1435 Boolean noExec; /* Set true if we decide not to run the job */
1436
1437 if (previous != (Job *)NULL) {
1438 previous->flags &= ~ (JOB_FIRST|JOB_IGNERR|JOB_SILENT|JOB_REMOTE);
1439 job = previous;
1440 } else {
1441 job = (Job *) malloc (sizeof (Job));
1442 if (job == (Job *)NULL) {
1443 Punt("JobStart out of memory");
1444 }
1445 flags |= JOB_FIRST;
1446 }
1447
1448 job->node = gn;
1449 job->tailCmds = NILLNODE;
1450
1451 /*
1452 * Set the initial value of the flags for this job based on the global
1453 * ones and the node's attributes... Any flags supplied by the caller
1454 * are also added to the field.
1455 */
1456 job->flags = 0;
1457 if (Targ_Ignore (gn)) {
1458 job->flags |= JOB_IGNERR;
1459 }
1460 if (Targ_Silent (gn)) {
1461 job->flags |= JOB_SILENT;
1462 }
1463 job->flags |= flags;
1464
1465 /*
1466 * Check the commands now so any attributes from .DEFAULT have a chance
1467 * to migrate to the node
1468 */
1469 if (!backwards || (job->flags & JOB_FIRST)) {
1470 cmdsOK = Job_CheckCommands(gn, Error);
1471 } else {
1472 cmdsOK = TRUE;
1473 }
1474
1475 /*
1476 * If the -n flag wasn't given, we open up OUR (not the child's)
1477 * temporary file to stuff commands in it. The thing is rd/wr so we don't
1478 * need to reopen it to feed it to the shell. If the -n flag *was* given,
1479 * we just set the file to be stdout. Cute, huh?
1480 */
1481 if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1482 /*
1483 * We're serious here, but if the commands were bogus, we're
1484 * also dead...
1485 */
1486 if (!cmdsOK) {
1487 DieHorribly();
1488 }
1489
1490 job->cmdFILE = fopen (tfile, "w+");
1491 if (job->cmdFILE == (FILE *) NULL) {
1492 Punt ("Could not open %s", tfile);
1493 }
1494 fcntl(fileno(job->cmdFILE), F_SETFD, 1);
1495 /*
1496 * Send the commands to the command file, flush all its buffers then
1497 * rewind and remove the thing.
1498 */
1499 noExec = FALSE;
1500
1501 if (backwards) {
1502 /*
1503 * Be compatible: If this is the first time for this node,
1504 * verify its commands are ok and open the commands list for
1505 * sequential access by later invocations of JobStart.
1506 * Once that is done, we take the next command off the list
1507 * and print it to the command file. If the command was an
1508 * ellipsis, note that there's nothing more to execute.
1509 */
1510 if ((job->flags&JOB_FIRST) && (Lst_Open(gn->commands) != SUCCESS)){
1511 cmdsOK = FALSE;
1512 } else {
1513 LstNode ln = Lst_Next (gn->commands);
1514
1515 if ((ln == NILLNODE) ||
1516 JobPrintCommand ((char *)Lst_Datum (ln), job))
1517 {
1518 noExec = TRUE;
1519 Lst_Close (gn->commands);
1520 }
1521 if (noExec && !(job->flags & JOB_FIRST)) {
1522 /*
1523 * If we're not going to execute anything, the job
1524 * is done and we need to close down the various
1525 * file descriptors we've opened for output, then
1526 * call JobDoOutput to catch the final characters or
1527 * send the file to the screen... Note that the i/o streams
1528 * are only open if this isn't the first job.
1529 * Note also that this could not be done in
1530 * Job_CatchChildren b/c it wasn't clear if there were
1531 * more commands to execute or not...
1532 */
1533 if (usePipes) {
1534#ifdef RMT_WILL_WATCH
1535 Rmt_Ignore(job->inPipe);
1536#else
1537 FD_CLR(job->inPipe, &outputs);
1538#endif
1539 if (job->outPipe != job->inPipe) {
1540 (void)close (job->outPipe);
1541 }
1542 JobDoOutput (job, TRUE);
1543 (void)close (job->inPipe);
1544 } else {
1545 (void)close (job->outFd);
1546 JobDoOutput (job, TRUE);
1547 }
1548 }
1549 }
1550 } else {
1551 /*
1552 * We can do all the commands at once. hooray for sanity
1553 */
1554 numCommands = 0;
1555 Lst_ForEach (gn->commands, JobPrintCommand, (ClientData)job);
1556
1557 /*
1558 * If we didn't print out any commands to the shell script,
1559 * there's not much point in executing the shell, is there?
1560 */
1561 if (numCommands == 0) {
1562 noExec = TRUE;
1563 }
1564 }
1565 } else if (noExecute) {
1566 /*
1567 * Not executing anything -- just print all the commands to stdout
1568 * in one fell swoop. This will still set up job->tailCmds correctly.
1569 */
1570 if (lastNode != gn) {
1571 printf (targFmt, gn->name);
1572 lastNode = gn;
1573 }
1574 job->cmdFILE = stdout;
1575 /*
1576 * Only print the commands if they're ok, but don't die if they're
1577 * not -- just let the user know they're bad and keep going. It
1578 * doesn't do any harm in this case and may do some good.
1579 */
1580 if (cmdsOK) {
1581 Lst_ForEach(gn->commands, JobPrintCommand, (ClientData)job);
1582 }
1583 /*
1584 * Don't execute the shell, thank you.
1585 */
1586 noExec = TRUE;
1587 } else {
1588 /*
1589 * Just touch the target and note that no shell should be executed.
1590 * Set cmdFILE to stdout to make life easier. Check the commands, too,
1591 * but don't die if they're no good -- it does no harm to keep working
1592 * up the graph.
1593 */
1594 job->cmdFILE = stdout;
1595 Job_Touch (gn, job->flags&JOB_SILENT);
1596 noExec = TRUE;
1597 }
1598
1599 /*
1600 * If we're not supposed to execute a shell, don't.
1601 */
1602 if (noExec) {
1603 /*
1604 * Unlink and close the command file if we opened one
1605 */
1606 if (job->cmdFILE != stdout) {
1607 (void) unlink (tfile);
1608 fclose(job->cmdFILE);
1609 } else {
1610 fflush (stdout);
1611 }
1612
1613 /*
1614 * We only want to work our way up the graph if we aren't here because
1615 * the commands for the job were no good.
1616 */
1617 if (cmdsOK) {
1618 if (aborting == 0) {
1619 if (job->tailCmds != NILLNODE) {
1620 Lst_ForEachFrom(job->node->commands, job->tailCmds,
1621 JobSaveCommand,
1622 (ClientData)job->node);
1623 }
1624 Make_Update(job->node);
1625 }
1626 free((Address)job);
1627 return(JOB_FINISHED);
1628 } else {
1629 free((Address)job);
1630 return(JOB_ERROR);
1631 }
1632 } else {
1633 fflush (job->cmdFILE);
1634 (void) unlink (tfile);
1635 }
1636
1637 /*
1638 * Set up the control arguments to the shell. This is based on the flags
1639 * set earlier for this job.
1640 */
1641 JobMakeArgv(job, argv);
1642
1643 /*
1644 * If we're using pipes to catch output, create the pipe by which we'll
1645 * get the shell's output. If we're using files, print out that we're
1646 * starting a job and then set up its temporary-file name. This is just
1647 * tfile with two extra digits tacked on -- jobno.
1648 */
1649 if (!backwards || (job->flags & JOB_FIRST)) {
1650 if (usePipes) {
1651 int fd[2];
1652 (void) pipe(fd);
1653 job->inPipe = fd[0];
1654 job->outPipe = fd[1];
1655 (void)fcntl (job->inPipe, F_SETFD, 1);
1656 (void)fcntl (job->outPipe, F_SETFD, 1);
1657 } else {
1658 printf ("Remaking `%s'\n", gn->name);
1659 fflush (stdout);
1660 sprintf (job->outFile, "%s%02d", tfile, jobno);
1661 jobno = (jobno + 1) % 100;
1662 job->outFd = open(job->outFile,O_WRONLY|O_CREAT|O_APPEND,0600);
1663 (void)fcntl (job->outFd, F_SETFD, 1);
1664 }
1665 }
1666
1667 if (!(gn->type & OP_NOEXPORT)) {
1668#ifdef RMT_NO_EXEC
1669 local = !Rmt_Export(shellPath, argv, job);
1670#else
1671 local = !Rmt_Begin (shellPath, argv, gn);
1672#endif /* RMT_NO_EXEC */
1673 if (!local) {
1674 job->flags |= JOB_REMOTE;
1675 }
1676 } else {
1677 local = TRUE;
1678 }
1679
1680 if (local && (
1681#ifdef sparc /* KLUDGE */
1682 (gn->type & OP_M68020) ||
1683#endif
1684 ((nLocal >= maxLocal) &&
1685 !(job->flags & JOB_SPECIAL) &&
1686 (!(gn->type & OP_NOEXPORT) || (maxLocal != 0)))))
1687 {
1688 /*
1689 * The job can only be run locally, but we've hit the limit of
1690 * local concurrency, so put the job on hold until some other job
1691 * finishes. Note that the special jobs (.BEGIN, .INTERRUPT and .END)
1692 * may be run locally even when the local limit has been reached
1693 * (e.g. when maxLocal == 0), though they will be exported if at
1694 * all possible. In addition, any target marked with .NOEXPORT will
1695 * be run locally if maxLocal is 0.
1696 */
1697 jobFull = TRUE;
1698
1699 if (DEBUG(JOB)) {
1700 printf("Can only run job locally.\n");
1701 }
1702 job->flags |= JOB_RESTART;
1703 (void)Lst_AtEnd(stoppedJobs, (ClientData)job);
1704 } else {
1705 if ((nLocal >= maxLocal) && local) {
1706 /*
1707 * If we're running this job locally as a special case (see above),
1708 * at least say the table is full.
1709 */
1710 jobFull = TRUE;
1711 if (DEBUG(JOB)) {
1712 printf("Local job queue is full.\n");
1713 }
1714 }
1715 JobExec(job, argv);
1716 }
1717 return(JOB_RUNNING);
1718}
1719\f
1720/*-
1721 *-----------------------------------------------------------------------
1722 * JobDoOutput --
1723 * This function is called at different times depending on
1724 * whether the user has specified that output is to be collected
1725 * via pipes or temporary files. In the former case, we are called
1726 * whenever there is something to read on the pipe. We collect more
1727 * output from the given job and store it in the job's outBuf. If
1728 * this makes up a line, we print it tagged by the job's identifier,
1729 * as necessary.
1730 * If output has been collected in a temporary file, we open the
1731 * file and read it line by line, transfering it to our own
1732 * output channel until the file is empty. At which point we
1733 * remove the temporary file.
1734 * In both cases, however, we keep our figurative eye out for the
1735 * 'noPrint' line for the shell from which the output came. If
1736 * we recognize a line, we don't print it. If the command is not
1737 * alone on the line (the character after it is not \0 or \n), we
1738 * do print whatever follows it.
1739 *
1740 * Results:
1741 * None
1742 *
1743 * Side Effects:
1744 * curPos may be shifted as may the contents of outBuf.
1745 *-----------------------------------------------------------------------
1746 */
1747void
1748JobDoOutput (job, finish)
1749 register Job *job; /* the job whose output needs printing */
1750 Boolean finish; /* TRUE if this is the last time we'll be
1751 * called for this job */
1752{
1753 Boolean gotNL = FALSE; /* true if got a newline */
1754 register int nr; /* number of bytes read */
1755 register int i; /* auxiliary index into outBuf */
1756 register int max; /* limit for i (end of current data) */
1757 int nRead; /* (Temporary) number of bytes read */
1758
1759 char c; /* character after noPrint string */
1760 FILE *oFILE; /* Stream pointer to shell's output file */
1761 char inLine[132];
1762
1763
1764 if (usePipes) {
1765 /*
1766 * Read as many bytes as will fit in the buffer.
1767 */
1768end_loop:
1769
1770 nRead = read (job->inPipe, &job->outBuf[job->curPos],
1771 JOB_BUFSIZE - job->curPos);
1772 if (nRead < 0) {
1773 if (DEBUG(JOB)) {
1774 perror("JobDoOutput(piperead)");
1775 }
1776 nr = 0;
1777 } else {
1778 nr = nRead;
1779 }
1780
1781 /*
1782 * If we hit the end-of-file (the job is dead), we must flush its
1783 * remaining output, so pretend we read a newline if there's any
1784 * output remaining in the buffer.
1785 * Also clear the 'finish' flag so we stop looping.
1786 */
1787 if ((nr == 0) && (job->curPos != 0)) {
1788 job->outBuf[job->curPos] = '\n';
1789 nr = 1;
1790 finish = FALSE;
1791 } else if (nr == 0) {
1792 finish = FALSE;
1793 }
1794
1795 /*
1796 * Look for the last newline in the bytes we just got. If there is
1797 * one, break out of the loop with 'i' as its index and gotNL set
1798 * TRUE.
1799 */
1800 max = job->curPos + nr;
1801 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1802 if (job->outBuf[i] == '\n') {
1803 gotNL = TRUE;
1804 break;
1805 } else if (job->outBuf[i] == '\0') {
1806 /*
1807 * Why?
1808 */
1809 job->outBuf[i] = ' ';
1810 }
1811 }
1812
1813 if (!gotNL) {
1814 job->curPos += nr;
1815 if (job->curPos == JOB_BUFSIZE) {
1816 /*
1817 * If we've run out of buffer space, we have no choice
1818 * but to print the stuff. sigh.
1819 */
1820 gotNL = TRUE;
1821 i = job->curPos;
1822 }
1823 }
1824 if (gotNL) {
1825 /*
1826 * Need to send the output to the screen. Null terminate it
1827 * first, overwriting the newline character if there was one.
1828 * So long as the line isn't one we should filter (according
1829 * to the shell description), we print the line, preceeded
1830 * by a target banner if this target isn't the same as the
1831 * one for which we last printed something.
1832 * The rest of the data in the buffer are then shifted down
1833 * to the start of the buffer and curPos is set accordingly.
1834 */
1835 job->outBuf[i] = '\0';
1836 if (i >= job->curPos) {
1837 register char *cp, *ecp;
1838
1839 cp = job->outBuf;
1840 if (commandShell->noPrint) {
1841 ecp = Str_FindSubstring(job->outBuf,
1842 commandShell->noPrint);
1843 while (ecp != (char *)NULL) {
1844 if (cp != ecp) {
1845 *ecp = '\0';
1846 if (job->node != lastNode) {
1847 printf (targFmt, job->node->name);
1848 lastNode = job->node;
1849 }
1850 /*
1851 * The only way there wouldn't be a newline after
1852 * this line is if it were the last in the buffer.
1853 * however, since the non-printable comes after it,
1854 * there must be a newline, so we don't print one.
1855 */
1856 printf ("%s", cp);
1857 }
1858 cp = ecp + commandShell->noPLen;
1859 if (cp != &job->outBuf[i]) {
1860 /*
1861 * Still more to print, look again after skipping
1862 * the whitespace following the non-printable
1863 * command....
1864 */
1865 cp++;
1866 while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
1867 cp++;
1868 }
1869 ecp = Str_FindSubstring (cp,
1870 commandShell->noPrint);
1871 } else {
1872 break;
1873 }
1874 }
1875 }
1876
1877 /*
1878 * There's still more in that thar buffer. This time, though,
1879 * we know there's no newline at the end, so we add one of
1880 * our own free will.
1881 */
1882 if (*cp != '\0') {
1883 if (job->node != lastNode) {
1884 printf (targFmt, job->node->name);
1885 lastNode = job->node;
1886 }
1887 printf ("%s\n", cp);
1888 }
1889
1890 fflush (stdout);
1891 }
1892 if (i < max - 1) {
1893 bcopy (&job->outBuf[i + 1], /* shift the remaining */
1894 job->outBuf, /* characters down */
1895 max - (i + 1));
1896 job->curPos = max - (i + 1);
1897
1898 } else {
1899 /*
1900 * We have written everything out, so we just start over
1901 * from the start of the buffer. No copying. No nothing.
1902 */
1903 job->curPos = 0;
1904 }
1905 }
1906 if (finish) {
1907 /*
1908 * If the finish flag is true, we must loop until we hit
1909 * end-of-file on the pipe. This is guaranteed to happen eventually
1910 * since the other end of the pipe is now closed (we closed it
1911 * explicitly and the child has exited). When we do get an EOF,
1912 * finish will be set FALSE and we'll fall through and out.
1913 */
1914 goto end_loop;
1915 }
1916 } else {
1917 /*
1918 * We've been called to retrieve the output of the job from the
1919 * temporary file where it's been squirreled away. This consists of
1920 * opening the file, reading the output line by line, being sure not
1921 * to print the noPrint line for the shell we used, then close and
1922 * remove the temporary file. Very simple.
1923 *
1924 * Change to read in blocks and do FindSubString type things as for
1925 * pipes? That would allow for "@echo -n..."
1926 */
1927 oFILE = fopen (job->outFile, "r");
1928 if (oFILE != (FILE *) NULL) {
1929 printf ("Results of making %s:\n", job->node->name);
1930 while (fgets (inLine, sizeof(inLine), oFILE) != NULL) {
1931 register char *cp, *ecp, *endp;
1932
1933 cp = inLine;
1934 endp = inLine + strlen(inLine);
1935 if (endp[-1] == '\n') {
1936 *--endp = '\0';
1937 }
1938 if (commandShell->noPrint) {
1939 ecp = Str_FindSubstring(cp, commandShell->noPrint);
1940 while (ecp != (char *)NULL) {
1941 if (cp != ecp) {
1942 *ecp = '\0';
1943 /*
1944 * The only way there wouldn't be a newline after
1945 * this line is if it were the last in the buffer.
1946 * however, since the non-printable comes after it,
1947 * there must be a newline, so we don't print one.
1948 */
1949 printf ("%s", cp);
1950 }
1951 cp = ecp + commandShell->noPLen;
1952 if (cp != endp) {
1953 /*
1954 * Still more to print, look again after skipping
1955 * the whitespace following the non-printable
1956 * command....
1957 */
1958 cp++;
1959 while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
1960 cp++;
1961 }
1962 ecp = Str_FindSubstring(cp, commandShell->noPrint);
1963 } else {
1964 break;
1965 }
1966 }
1967 }
1968
1969 /*
1970 * There's still more in that thar buffer. This time, though,
1971 * we know there's no newline at the end, so we add one of
1972 * our own free will.
1973 */
1974 if (*cp != '\0') {
1975 printf ("%s\n", cp);
1976 }
1977 }
1978 fclose (oFILE);
1979 (void) unlink (job->outFile);
1980 }
1981 }
1982 fflush(stdout);
1983}
1984\f
1985/*-
1986 *-----------------------------------------------------------------------
1987 * Job_CatchChildren --
1988 * Handle the exit of a child. Called from Make_Make.
1989 *
1990 * Results:
1991 * none.
1992 *
1993 * Side Effects:
1994 * The job descriptor is removed from the list of children.
1995 *
1996 * Notes:
1997 * We do waits, blocking or not, according to the wisdom of our
1998 * caller, until there are no more children to report. For each
1999 * job, call JobFinish to finish things off. This will take care of
2000 * putting jobs on the stoppedJobs queue.
2001 *
2002 *-----------------------------------------------------------------------
2003 */
2004void
2005Job_CatchChildren (block)
2006 Boolean block; /* TRUE if should block on the wait. */
2007{
2008 int pid; /* pid of dead child */
2009 register Job *job; /* job descriptor for dead child */
2010 LstNode jnode; /* list element for finding job */
2011 union wait status; /* Exit/termination status */
2012
2013 /*
2014 * Don't even bother if we know there's no one around.
2015 */
2016 if (nLocal == 0) {
2017 return;
2018 }
2019
2020 while ((pid = wait3(&status, (block?0:WNOHANG)|WUNTRACED,
2021 (struct rusage *)0)) > 0)
2022 {
2023 if (DEBUG(JOB)) {
2024#ifdef Sprite
2025 printf("Process %x exited or stopped.\n", pid);
2026#else
2027 printf("Process %d exited or stopped.\n", pid);
2028#endif /* Sprite */
2029 }
2030
2031
2032 jnode = Lst_Find (jobs, (ClientData)pid, JobCmpPid);
2033
2034 if (jnode == NILLNODE) {
2035 if (WIFSIGNALED(status) && (status.w_termsig == SIGCONT)) {
2036 jnode = Lst_Find(stoppedJobs, (ClientData)pid, JobCmpPid);
2037 if (jnode == NILLNODE) {
2038#ifdef Sprite
2039 Error("Resumed child (%x) not in table", pid);
2040#else
2041 Error("Resumed child (%d) not in table", pid);
2042#endif /* Sprite */
2043 continue;
2044 }
2045 job = (Job *)Lst_Datum(jnode);
2046 (void)Lst_Remove(stoppedJobs, jnode);
2047 } else {
2048#ifdef Sprite
2049 Error ("Child (%x) not in table?", pid);
2050#else
2051 Error ("Child (%d) not in table?", pid);
2052#endif /* Sprite */
2053 continue;
2054 }
2055 } else {
2056 job = (Job *) Lst_Datum (jnode);
2057 (void)Lst_Remove (jobs, jnode);
2058 nJobs -= 1;
2059 if (jobFull && DEBUG(JOB)) {
2060 printf("Job queue is no longer full.\n");
2061 }
2062 jobFull = FALSE;
2063
2064 if (job->flags & JOB_REMOTE) {
2065 Rmt_Done (job->rmtID);
2066 } else {
2067 nLocal -= 1;
2068 }
2069 }
2070
2071 JobFinish (job, status);
2072 }
2073}
2074\f
2075/*-
2076 *-----------------------------------------------------------------------
2077 * Job_CatchOutput --
2078 * Catch the output from our children, if we're using
2079 * pipes do so. Otherwise just block time until we get a
2080 * signal (most likely a SIGCHLD) since there's no point in
2081 * just spinning when there's nothing to do and the reaping
2082 * of a child can wait for a while.
2083 *
2084 * Results:
2085 * None
2086 *
2087 * Side Effects:
2088 * Output is read from pipes if we're piping.
2089 * -----------------------------------------------------------------------
2090 */
2091void
2092Job_CatchOutput ()
2093{
2094 int nfds;
2095 struct timeval timeout;
2096 fd_set readfds;
2097 register LstNode ln;
2098 register Job *job;
2099 int pnJobs; /* Previous nJobs */
2100
2101 fflush(stdout);
2102#ifdef RMT_WILL_WATCH
2103 pnJobs = nJobs;
2104
2105 /*
2106 * It is possible for us to be called with nJobs equal to 0. This happens
2107 * if all the jobs finish and a job that is stopped cannot be run
2108 * locally (eg if maxLocal is 0) and cannot be exported. The job will
2109 * be placed back on the stoppedJobs queue, Job_Empty() will return false,
2110 * Make_Run will call us again when there's nothing for which to wait.
2111 * nJobs never changes, so we loop forever. Hence the check. It could
2112 * be argued that we should sleep for a bit so as not to swamp the
2113 * exportation system with requests. Perhaps we should.
2114 *
2115 * NOTE: IT IS THE RESPONSIBILITY OF Rmt_Wait TO CALL Job_CatchChildren
2116 * IN A TIMELY FASHION TO CATCH ANY LOCALLY RUNNING JOBS THAT EXIT.
2117 * It may use the variable nLocal to determine if it needs to call
2118 * Job_CatchChildren (if nLocal is 0, there's nothing for which to
2119 * wait...)
2120 */
2121 while (nJobs != 0 && pnJobs == nJobs) {
2122 Rmt_Wait();
2123 }
2124#else
2125 if (usePipes) {
2126 readfds = outputs;
2127 timeout.tv_sec = SEL_SEC;
2128 timeout.tv_usec = SEL_USEC;
2129
2130 if ((nfds = select (FD_SETSIZE, &readfds, (int *) 0, (int *) 0, &timeout)) < 0)
2131 {
2132 return;
2133 } else {
2134 if (Lst_Open (jobs) == FAILURE) {
2135 Punt ("Cannot open job table");
2136 }
2137 while (nfds && (ln = Lst_Next (jobs)) != NILLNODE) {
2138 job = (Job *) Lst_Datum (ln);
2139 if (FD_ISSET(job->inPipe, &readfds)) {
2140 JobDoOutput (job, FALSE);
2141 nfds -= 1;
2142 }
2143 }
2144 Lst_Close (jobs);
2145 }
2146 }
2147#endif /* RMT_WILL_WATCH */
2148}
2149\f
2150/*-
2151 *-----------------------------------------------------------------------
2152 * Job_Make --
2153 * Start the creation of a target. Basically a front-end for
2154 * JobStart used by the Make module.
2155 *
2156 * Results:
2157 * None.
2158 *
2159 * Side Effects:
2160 * Another job is started.
2161 *
2162 *-----------------------------------------------------------------------
2163 */
2164void
2165Job_Make (gn)
2166 GNode *gn;
2167{
2168 (void)JobStart (gn, 0, (Job *)NULL);
2169}
2170\f
2171/*-
2172 *-----------------------------------------------------------------------
2173 * Job_Init --
2174 * Initialize the process module
2175 *
2176 * Results:
2177 * none
2178 *
2179 * Side Effects:
2180 * lists and counters are initialized
2181 *-----------------------------------------------------------------------
2182 */
2183void
2184Job_Init (maxproc, maxlocal)
2185 int maxproc; /* the greatest number of jobs which may be
2186 * running at one time */
2187 int maxlocal; /* the greatest number of local jobs which may
2188 * be running at once. */
2189{
2190 GNode *begin; /* node for commands to do at the very start */
2191
2192#ifdef Sprite
2193 sprintf (tfile, "/tmp/make%05x", getpid());
2194#else
2195 sprintf (tfile, "/tmp/make%05d", getpid());
2196#endif /* Sprite */
2197
2198 jobs = Lst_Init (FALSE);
2199 stoppedJobs = Lst_Init(FALSE);
2200 maxJobs = maxproc;
2201 maxLocal = maxlocal;
2202 nJobs = 0;
2203 nLocal = 0;
2204 jobFull = FALSE;
2205
2206 aborting = 0;
2207 errors = 0;
2208
2209 lastNode = NILGNODE;
2210
2211 if (maxJobs == 1) {
2212 /*
2213 * If only one job can run at a time, there's no need for a banner,
2214 * no is there?
2215 */
2216 targFmt = "";
2217 } else {
2218 targFmt = TARG_FMT;
2219 }
2220
2221 if (shellPath == (char *) NULL) {
2222 /*
2223 * The user didn't specify a shell to use, so we are using the
2224 * default one... Both the absolute path and the last component
2225 * must be set. The last component is taken from the 'name' field
2226 * of the default shell description pointed-to by commandShell.
2227 * All default shells are located in DEFSHELLDIR.
2228 */
2229 shellName = commandShell->name;
2230 shellPath = Str_Concat (DEFSHELLDIR, shellName, STR_ADDSLASH);
2231 }
2232
2233 if (commandShell->exit == (char *)NULL) {
2234 commandShell->exit = "";
2235 }
2236 if (commandShell->echo == (char *)NULL) {
2237 commandShell->echo = "";
2238 }
2239
2240 /*
2241 * Catch the four signals that POSIX specifies if they aren't ignored.
2242 * JobPassSig will take care of calling JobInterrupt if appropriate.
2243 */
2244 if (signal (SIGINT, SIG_IGN) != SIG_IGN) {
2245 signal (SIGINT, JobPassSig);
2246 }
2247 if (signal (SIGHUP, SIG_IGN) != SIG_IGN) {
2248 signal (SIGHUP, JobPassSig);
2249 }
2250 if (signal (SIGQUIT, SIG_IGN) != SIG_IGN) {
2251 signal (SIGQUIT, JobPassSig);
2252 }
2253 if (signal (SIGTERM, SIG_IGN) != SIG_IGN) {
2254 signal (SIGTERM, JobPassSig);
2255 }
2256 /*
2257 * There are additional signals that need to be caught and passed if
2258 * either the export system wants to be told directly of signals or if
2259 * we're giving each job its own process group (since then it won't get
2260 * signals from the terminal driver as we own the terminal)
2261 */
2262#if defined(RMT_WANTS_SIGNALS) || defined(USE_PGRP)
2263 if (signal (SIGTSTP, SIG_IGN) != SIG_IGN) {
2264 signal (SIGTSTP, JobPassSig);
2265 }
2266 if (signal (SIGTTOU, SIG_IGN) != SIG_IGN) {
2267 signal (SIGTTOU, JobPassSig);
2268 }
2269 if (signal (SIGTTIN, SIG_IGN) != SIG_IGN) {
2270 signal (SIGTTIN, JobPassSig);
2271 }
2272 if (signal (SIGWINCH, SIG_IGN) != SIG_IGN) {
2273 signal (SIGWINCH, JobPassSig);
2274 }
2275#endif
2276
2277 begin = Targ_FindNode (".BEGIN", TARG_NOCREATE);
2278
2279 if (begin != NILGNODE) {
2280 JobStart (begin, JOB_SPECIAL, (Job *)0);
2281 while (nJobs) {
2282 Job_CatchOutput();
2283#ifndef RMT_WILL_WATCH
2284 Job_CatchChildren (!usePipes);
2285#endif /* RMT_WILL_WATCH */
2286 }
2287 }
2288 postCommands = Targ_FindNode (".END", TARG_CREATE);
2289}
2290\f
2291/*-
2292 *-----------------------------------------------------------------------
2293 * Job_Full --
2294 * See if the job table is full. It is considered full if it is OR
2295 * if we are in the process of aborting OR if we have
2296 * reached/exceeded our local quota. This prevents any more jobs
2297 * from starting up.
2298 *
2299 * Results:
2300 * TRUE if the job table is full, FALSE otherwise
2301 * Side Effects:
2302 * None.
2303 *-----------------------------------------------------------------------
2304 */
2305Boolean
2306Job_Full ()
2307{
2308 return (aborting || jobFull);
2309}
2310\f
2311/*-
2312 *-----------------------------------------------------------------------
2313 * Job_Empty --
2314 * See if the job table is empty. Because the local concurrency may
2315 * be set to 0, it is possible for the job table to become empty,
2316 * while the list of stoppedJobs remains non-empty. In such a case,
2317 * we want to restart as many jobs as we can.
2318 *
2319 * Results:
2320 * TRUE if it is. FALSE if it ain't.
2321 *
2322 * Side Effects:
2323 * None.
2324 *
2325 * -----------------------------------------------------------------------
2326 */
2327Boolean
2328Job_Empty ()
2329{
2330 if (nJobs == 0) {
2331 if (!Lst_IsEmpty(stoppedJobs) && !aborting) {
2332 /*
2333 * The job table is obviously not full if it has no jobs in
2334 * it...Try and restart the stopped jobs.
2335 */
2336 jobFull = FALSE;
2337 while (!jobFull && !Lst_IsEmpty(stoppedJobs)) {
2338 JobRestart((Job *)Lst_DeQueue(stoppedJobs));
2339 }
2340 return(FALSE);
2341 } else {
2342 return(TRUE);
2343 }
2344 } else {
2345 return(FALSE);
2346 }
2347}
2348\f
2349/*-
2350 *-----------------------------------------------------------------------
2351 * JobMatchShell --
2352 * Find a matching shell in 'shells' given its final component.
2353 *
2354 * Results:
2355 * A pointer to the Shell structure.
2356 *
2357 * Side Effects:
2358 * None.
2359 *
2360 *-----------------------------------------------------------------------
2361 */
2362static Shell *
2363JobMatchShell (name)
2364 char *name; /* Final component of shell path */
2365{
2366 register Shell *sh; /* Pointer into shells table */
2367 Shell *match; /* Longest-matching shell */
2368 register char *cp1,
2369 *cp2;
2370 char *eoname;
2371
2372 eoname = name + strlen (name);
2373
2374 match = (Shell *) NULL;
2375
2376 for (sh = shells; sh->name != NULL; sh++) {
2377 for (cp1 = eoname - strlen (sh->name), cp2 = sh->name;
2378 *cp1 != '\0' && *cp1 == *cp2;
2379 cp1++, cp2++) {
2380 continue;
2381 }
2382 if (*cp1 != *cp2) {
2383 continue;
2384 } else if (match == (Shell *) NULL ||
2385 strlen (match->name) < strlen (sh->name)) {
2386 match = sh;
2387 }
2388 }
2389 return (match == (Shell *) NULL ? sh : match);
2390}
2391\f
2392/*-
2393 *-----------------------------------------------------------------------
2394 * Job_ParseShell --
2395 * Parse a shell specification and set up commandShell, shellPath
2396 * and shellName appropriately.
2397 *
2398 * Results:
2399 * FAILURE if the specification was incorrect.
2400 *
2401 * Side Effects:
2402 * commandShell points to a Shell structure (either predefined or
2403 * created from the shell spec), shellPath is the full path of the
2404 * shell described by commandShell, while shellName is just the
2405 * final component of shellPath.
2406 *
2407 * Notes:
2408 * A shell specification consists of a .SHELL target, with dependency
2409 * operator, followed by a series of blank-separated words. Double
2410 * quotes can be used to use blanks in words. A backslash escapes
2411 * anything (most notably a double-quote and a space) and
2412 * provides the functionality it does in C. Each word consists of
2413 * keyword and value separated by an equal sign. There should be no
2414 * unnecessary spaces in the word. The keywords are as follows:
2415 * name Name of shell.
2416 * path Location of shell. Overrides "name" if given
2417 * quiet Command to turn off echoing.
2418 * echo Command to turn echoing on
2419 * filter Result of turning off echoing that shouldn't be
2420 * printed.
2421 * echoFlag Flag to turn echoing on at the start
2422 * errFlag Flag to turn error checking on at the start
2423 * hasErrCtl True if shell has error checking control
2424 * check Command to turn on error checking if hasErrCtl
2425 * is TRUE or template of command to echo a command
2426 * for which error checking is off if hasErrCtl is
2427 * FALSE.
2428 * ignore Command to turn off error checking if hasErrCtl
2429 * is TRUE or template of command to execute a
2430 * command so as to ignore any errors it returns if
2431 * hasErrCtl is FALSE.
2432 *
2433 *-----------------------------------------------------------------------
2434 */
2435ReturnStatus
2436Job_ParseShell (line)
2437 char *line; /* The shell spec */
2438{
2439 char **words;
2440 int wordCount;
2441 register char **argv;
2442 register int argc;
2443 char *path;
2444 Shell newShell;
2445 Boolean fullSpec = FALSE;
2446
2447 while (isspace (*line)) {
2448 line++;
2449 }
2450 words = Str_BreakString (line, " \t", "\n", &wordCount);
2451
2452 bzero ((Address)&newShell, sizeof(newShell));
2453
2454 /*
2455 * Parse the specification by keyword
2456 */
2457 for (path = (char *)NULL, argc = wordCount - 1, argv = words + 1;
2458 argc != 0;
2459 argc--, argv++) {
2460 if (strncmp (*argv, "path=", 5) == 0) {
2461 path = &argv[0][5];
2462 } else if (strncmp (*argv, "name=", 5) == 0) {
2463 newShell.name = &argv[0][5];
2464 } else {
2465 if (strncmp (*argv, "quiet=", 6) == 0) {
2466 newShell.echoOff = &argv[0][6];
2467 } else if (strncmp (*argv, "echo=", 5) == 0) {
2468 newShell.echoOn = &argv[0][5];
2469 } else if (strncmp (*argv, "filter=", 7) == 0) {
2470 newShell.noPrint = &argv[0][7];
2471 newShell.noPLen = strlen(newShell.noPrint);
2472 } else if (strncmp (*argv, "echoFlag=", 9) == 0) {
2473 newShell.echo = &argv[0][9];
2474 } else if (strncmp (*argv, "errFlag=", 8) == 0) {
2475 newShell.exit = &argv[0][8];
2476 } else if (strncmp (*argv, "hasErrCtl=", 10) == 0) {
2477 char c = argv[0][10];
2478 newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
2479 (c != 'T') && (c != 't'));
2480 } else if (strncmp (*argv, "check=", 6) == 0) {
2481 newShell.errCheck = &argv[0][6];
2482 } else if (strncmp (*argv, "ignore=", 7) == 0) {
2483 newShell.ignErr = &argv[0][7];
2484 } else {
2485 Parse_Error (PARSE_FATAL, "Unknown keyword \"%s\"",
2486 *argv);
2487 Str_FreeVec (wordCount, words);
2488 return (FAILURE);
2489 }
2490 fullSpec = TRUE;
2491 }
2492 }
2493
2494 if (path == (char *)NULL) {
2495 /*
2496 * If no path was given, the user wants one of the pre-defined shells,
2497 * yes? So we find the one s/he wants with the help of JobMatchShell
2498 * and set things up the right way. shellPath will be set up by
2499 * Job_Init.
2500 */
2501 if (newShell.name == (char *)NULL) {
2502 Parse_Error (PARSE_FATAL, "Neither path nor name specified");
2503 Str_FreeVec (wordCount, words);
2504 return (FAILURE);
2505 } else {
2506 commandShell = JobMatchShell (newShell.name);
2507 shellName = newShell.name;
2508 }
2509 } else {
2510 /*
2511 * The user provided a path. If s/he gave nothing else (fullSpec is
2512 * FALSE), try and find a matching shell in the ones we know of.
2513 * Else we just take the specification at its word and copy it
2514 * to a new location. In either case, we need to record the
2515 * path the user gave for the shell.
2516 */
2517 shellPath = path;
2518 path = rindex (path, '/');
2519 if (path == (char *)NULL) {
2520 path = shellPath;
2521 } else {
2522 path += 1;
2523 }
2524 if (newShell.name != (char *)NULL) {
2525 shellName = newShell.name;
2526 } else {
2527 shellName = path;
2528 }
2529 if (!fullSpec) {
2530 commandShell = JobMatchShell (shellName);
2531 } else {
2532 commandShell = (Shell *) malloc(sizeof(Shell));
2533 *commandShell = newShell;
2534 }
2535 }
2536
2537 if (commandShell->echoOn && commandShell->echoOff) {
2538 commandShell->hasEchoCtl = TRUE;
2539 }
2540
2541 if (!commandShell->hasErrCtl) {
2542 if (commandShell->errCheck == (char *)NULL) {
2543 commandShell->errCheck = "";
2544 }
2545 if (commandShell->ignErr == (char *)NULL) {
2546 commandShell->ignErr = "%s\n";
2547 }
2548 }
2549
2550 /*
2551 * Do not free up the words themselves, since they might be in use by the
2552 * shell specification...
2553 */
2554 free (words);
2555 return SUCCESS;
2556}
2557\f
2558/*-
2559 *-----------------------------------------------------------------------
2560 * JobInterrupt --
2561 * Handle the receipt of an interrupt.
2562 *
2563 * Results:
2564 * None
2565 *
2566 * Side Effects:
2567 * All children are killed. Another job will be started if the
2568 * .INTERRUPT target was given.
2569 *-----------------------------------------------------------------------
2570 */
2571static void
2572JobInterrupt (runINTERRUPT)
2573 int runINTERRUPT; /* Non-zero if commands for the .INTERRUPT
2574 * target should be executed */
2575{
2576 LstNode ln; /* element in job table */
2577 Job *job; /* job descriptor in that element */
2578 GNode *interrupt; /* the node describing the .INTERRUPT target */
2579
2580 aborting = ABORT_INTERRUPT;
2581
2582 (void)Lst_Open (jobs);
2583 while ((ln = Lst_Next (jobs)) != NILLNODE) {
2584 job = (Job *) Lst_Datum (ln);
2585
2586 if (!Targ_Precious (job->node)) {
2587 char *file = (job->node->path == (char *)NULL ?
2588 job->node->name :
2589 job->node->path);
2590 if (unlink (file) == 0) {
2591 Error ("*** %s removed", file);
2592 }
2593 }
2594#ifdef RMT_WANTS_SIGNALS
2595 if (job->flags & JOB_REMOTE) {
2596 /*
2597 * If job is remote, let the Rmt module do the killing.
2598 */
2599 if (!Rmt_Signal(job, SIGINT)) {
2600 /*
2601 * If couldn't kill the thing, finish it out now with an
2602 * error code, since no exit report will come in likely.
2603 */
2604 union wait status;
2605
2606 status.w_status = 0;
2607 status.w_retcode = 1;
2608 JobFinish(job, status);
2609 }
2610 } else if (job->pid) {
2611 KILL(job->pid, SIGINT);
2612 }
2613#else
2614 if (job->pid) {
2615 KILL(job->pid, SIGINT);
2616 }
2617#endif /* RMT_WANTS_SIGNALS */
2618 }
2619 Lst_Close (jobs);
2620
2621 if (runINTERRUPT && !touchFlag) {
2622 interrupt = Targ_FindNode (".INTERRUPT", TARG_NOCREATE);
2623 if (interrupt != NILGNODE) {
2624 ignoreErrors = FALSE;
2625
2626 JobStart (interrupt, JOB_IGNDOTS, (Job *)0);
2627 while (nJobs) {
2628 Job_CatchOutput();
2629#ifndef RMT_WILL_WATCH
2630 Job_CatchChildren (!usePipes);
2631#endif /* RMT_WILL_WATCH */
2632 }
2633 }
2634 }
2635 (void) unlink (tfile);
2636 exit (0);
2637}
2638\f
2639/*
2640 *-----------------------------------------------------------------------
2641 * Job_End --
2642 * Do final processing such as the running of the commands
2643 * attached to the .END target.
2644 *
2645 * Results:
2646 * Number of errors reported.
2647 *
2648 * Side Effects:
2649 * The process' temporary file (tfile) is removed if it still
2650 * existed.
2651 *-----------------------------------------------------------------------
2652 */
2653int
2654Job_End ()
2655{
2656 if (postCommands != NILGNODE && !Lst_IsEmpty (postCommands->commands)) {
2657 if (errors) {
2658 Error ("Errors reported so .END ignored");
2659 } else {
2660 JobStart (postCommands, JOB_SPECIAL | JOB_IGNDOTS,
2661 (Job *)0);
2662
2663 while (nJobs) {
2664 Job_CatchOutput();
2665#ifndef RMT_WILL_WATCH
2666 Job_CatchChildren (!usePipes);
2667#endif /* RMT_WILL_WATCH */
2668 }
2669 }
2670 }
2671 (void) unlink (tfile);
2672 return(errors);
2673}
2674\f
2675/*-
2676 *-----------------------------------------------------------------------
2677 * Job_Wait --
2678 * Waits for all running jobs to finish and returns. Sets 'aborting'
2679 * to ABORT_WAIT to prevent other jobs from starting.
2680 *
2681 * Results:
2682 * None.
2683 *
2684 * Side Effects:
2685 * Currently running jobs finish.
2686 *
2687 *-----------------------------------------------------------------------
2688 */
2689void
2690Job_Wait()
2691{
2692 aborting = ABORT_WAIT;
2693 while (nJobs != 0) {
2694 Job_CatchOutput();
2695#ifndef RMT_WILL_WATCH
2696 Job_CatchChildren(!usePipes);
2697#endif /* RMT_WILL_WATCH */
2698 }
2699 aborting = 0;
2700}
2701\f
2702/*-
2703 *-----------------------------------------------------------------------
2704 * Job_AbortAll --
2705 * Abort all currently running jobs without handling output or anything.
2706 * This function is to be called only in the event of a major
2707 * error. Most definitely NOT to be called from JobInterrupt.
2708 *
2709 * Results:
2710 * None
2711 *
2712 * Side Effects:
2713 * All children are killed, not just the firstborn
2714 *-----------------------------------------------------------------------
2715 */
2716void
2717Job_AbortAll ()
2718{
2719 LstNode ln; /* element in job table */
2720 Job *job; /* the job descriptor in that element */
2721 int foo;
2722
2723 aborting = ABORT_ERROR;
2724
2725 if (nJobs) {
2726
2727 (void)Lst_Open (jobs);
2728 while ((ln = Lst_Next (jobs)) != NILLNODE) {
2729 job = (Job *) Lst_Datum (ln);
2730
2731 /*
2732 * kill the child process with increasingly drastic signals to make
2733 * darn sure it's dead.
2734 */
2735#ifdef RMT_WANTS_SIGNALS
2736 if (job->flags & JOB_REMOTE) {
2737 Rmt_Signal(job, SIGINT);
2738 Rmt_Signal(job, SIGKILL);
2739 } else {
2740 KILL(job->pid, SIGINT);
2741 KILL(job->pid, SIGKILL);
2742 }
2743#else
2744 KILL(job->pid, SIGINT);
2745 KILL(job->pid, SIGKILL);
2746#endif /* RMT_WANTS_SIGNALS */
2747 }
2748 }
2749
2750 /*
2751 * Catch as many children as want to report in at first, then give up
2752 */
2753 while (wait3(&foo, WNOHANG, (struct rusage *)0) > 0) {
2754 ;
2755 }
2756 (void) unlink (tfile);
2757}