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