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