Move ProcExec() into proc.c
[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 $
1caaff2f 41 * $DragonFly: src/usr.bin/make/job.c,v 1.108 2005/05/23 18:24:59 okumoto Exp $
984263bc
MD
42 */
43
984263bc 44#ifndef OLD_JOKE
b83dbac0 45#define OLD_JOKE 0
984263bc
MD
46#endif /* OLD_JOKE */
47
90b7ba34
MO
48/**
49 * job.c
984263bc
MD
50 * handle the creation etc. of our child processes.
51 *
52 * Interface:
df64c352 53 * Job_Make Start the creation of the given target.
984263bc 54 *
df64c352
MO
55 * Job_CatchChildren
56 * Check for and handle the termination of any children.
57 * This must be called reasonably frequently to keep the
58 * whole make going at a decent clip, since job table
59 * entries aren't removed until their process is caught
60 * this way. Its single argument is TRUE if the function
61 * should block waiting for a child to terminate.
984263bc 62 *
df64c352
MO
63 * Job_CatchOutput Print any output our children have produced. Should
64 * also be called fairly frequently to keep the user
65 * informed of what's going on. If no output is waiting,
66 * it will block for a time given by the SEL_* constants,
67 * below, or until output is ready.
984263bc 68 *
df64c352
MO
69 * Job_Init Called to intialize this module. in addition, any
70 * commands attached to the .BEGIN target are executed
71 * before this function returns. Hence, the makefile must
72 * have been parsed before this function is called.
984263bc 73 *
df64c352 74 * Job_Full Return TRUE if the job table is filled.
984263bc 75 *
df64c352 76 * Job_Empty Return TRUE if the job table is completely empty.
984263bc 77 *
df64c352
MO
78 * Job_Finish Perform any final processing which needs doing. This
79 * includes the execution of any commands which have
80 * been/were attached to the .END target. It should only
81 * be called when the job table is empty.
984263bc 82 *
df64c352
MO
83 * Job_AbortAll Abort all currently running jobs. It doesn't handle
84 * output or do anything for the jobs, just kills them.
85 * It should only be called in an emergency, as it were.
984263bc 86 *
df64c352
MO
87 * Job_CheckCommands
88 * Verify that the commands for a target are ok. Provide
89 * them if necessary and possible.
984263bc 90 *
df64c352 91 * Job_Touch Update a target without really updating it.
984263bc 92 *
df64c352 93 * Job_Wait Wait for all currently-running jobs to finish.
29004ef5 94 *
90b7ba34 95 * compat.c
29004ef5
MO
96 * The routines in this file implement the full-compatibility
97 * mode of PMake. Most of the special functionality of PMake
98 * is available in this mode. Things not supported:
99 * - different shells.
100 * - friendly variable substitution.
101 *
102 * Interface:
103 * Compat_Run Initialize things for this module and recreate
104 * thems as need creatin'
984263bc
MD
105 */
106
9de1d47a 107#include <sys/queue.h>
984263bc 108#include <sys/types.h>
9863ce62 109#include <sys/select.h>
984263bc 110#include <sys/stat.h>
edf6dd37
MO
111#ifdef USE_KQUEUE
112#include <sys/event.h>
113#endif
984263bc 114#include <sys/wait.h>
9863ce62 115#include <ctype.h>
7e8aa26d 116#include <err.h>
984263bc 117#include <errno.h>
ef1537e7 118#include <fcntl.h>
9de1d47a 119#include <inttypes.h>
edf6dd37 120#include <string.h>
984263bc 121#include <signal.h>
9863ce62 122#include <stdlib.h>
d0f0ba15 123#include <unistd.h>
ef1537e7 124#include <utime.h>
9863ce62 125
9863ce62 126#include "arch.h"
b0ef9278 127#include "buf.h"
5f530f85 128#include "config.h"
984263bc 129#include "dir.h"
9863ce62
MO
130#include "globals.h"
131#include "GNode.h"
984263bc 132#include "job.h"
9863ce62
MO
133#include "make.h"
134#include "parse.h"
984263bc 135#include "pathnames.h"
1caaff2f 136#include "proc.h"
880b6521 137#include "shell.h"
9863ce62 138#include "str.h"
5f530f85 139#include "suff.h"
9863ce62
MO
140#include "targ.h"
141#include "util.h"
142#include "var.h"
a34ec481 143
6999645d 144#define TMPPAT "/tmp/makeXXXXXXXXXX"
04cee6af
MO
145#define MKLVL_MAXVAL 500
146#define MKLVL_ENVVAR "__MKLVL__"
6999645d
MO
147
148#ifndef USE_KQUEUE
149/*
150 * The SEL_ constants determine the maximum amount of time spent in select
151 * before coming out to see if a child has finished. SEL_SEC is the number of
152 * seconds and SEL_USEC is the number of micro-seconds
153 */
154#define SEL_SEC 2
155#define SEL_USEC 0
156#endif /* !USE_KQUEUE */
157
7051be4f
MO
158/*
159 * Job Table definitions.
160 *
161 * The job "table" is kept as a linked Lst in 'jobs', with the number of
162 * active jobs maintained in the 'nJobs' variable. At no time will this
163 * exceed the value of 'maxJobs', initialized by the Job_Init function.
164 *
165 * When a job is finished, the Make_Update function is called on each of the
166 * parents of the node which was just remade. This takes care of the upward
167 * traversal of the dependency graph.
168 */
169#define JOB_BUFSIZE 1024
170typedef struct Job {
9de1d47a 171 pid_t pid; /* The child's process ID */
7051be4f
MO
172
173 struct GNode *node; /* The target the child is making */
174
175 /*
176 * A LstNode for the first command to be saved after the job completes.
177 * This is NULL if there was no "..." in the job's commands.
178 */
179 LstNode *tailCmds;
180
181 /*
182 * An FILE* for writing out the commands. This is only
183 * used before the job is actually started.
184 */
185 FILE *cmdFILE;
186
187 /*
188 * A word of flags which determine how the module handles errors,
189 * echoing, etc. for the job
190 */
191 short flags; /* Flags to control treatment of job */
192#define JOB_IGNERR 0x001 /* Ignore non-zero exits */
193#define JOB_SILENT 0x002 /* no output */
194#define JOB_SPECIAL 0x004 /* Target is a special one. i.e. run it locally
195 * if we can't export it and maxLocal is 0 */
b04c4147 196#define JOB_IGNDOTS 0x008 /* Ignore "..." lines when processing
7051be4f
MO
197 * commands */
198#define JOB_FIRST 0x020 /* Job is first job for the node */
199#define JOB_RESTART 0x080 /* Job needs to be completely restarted */
200#define JOB_RESUME 0x100 /* Job needs to be resumed b/c it stopped,
201 * for some reason */
202#define JOB_CONTINUING 0x200 /* We are in the process of resuming this job.
203 * Used to avoid infinite recursion between
204 * JobFinish and JobRestart */
205
206 /* union for handling shell's output */
207 union {
208 /*
209 * This part is used when usePipes is true.
b04c4147 210 * The output is being caught via a pipe and the descriptors
7051be4f
MO
211 * of our pipe, an array in which output is line buffered and
212 * the current position in that buffer are all maintained for
213 * each job.
214 */
215 struct {
216 /*
217 * Input side of pipe associated with
218 * job's output channel
219 */
220 int op_inPipe;
221
222 /*
223 * Output side of pipe associated with job's
224 * output channel
225 */
226 int op_outPipe;
227
228 /*
229 * Buffer for storing the output of the
230 * job, line by line
231 */
232 char op_outBuf[JOB_BUFSIZE + 1];
233
234 /* Current position in op_outBuf */
235 int op_curPos;
236 } o_pipe;
237
238 /*
239 * If usePipes is false the output is routed to a temporary
240 * file and all that is kept is the name of the file and the
241 * descriptor open to the file.
242 */
243 struct {
244 /* Name of file to which shell output was rerouted */
245 char of_outFile[sizeof(TMPPAT)];
246
247 /*
248 * Stream open to the output file. Used to funnel all
249 * from a single job to one file while still allowing
250 * multiple shell invocations
251 */
252 int of_outFd;
253 } o_file;
254
90b7ba34 255 } output; /* Data for tracking a shell's output */
9de1d47a
MO
256
257 TAILQ_ENTRY(Job) link; /* list link */
7051be4f
MO
258} Job;
259
b04c4147
MO
260#define outPipe output.o_pipe.op_outPipe
261#define inPipe output.o_pipe.op_inPipe
7051be4f
MO
262#define outBuf output.o_pipe.op_outBuf
263#define curPos output.o_pipe.op_curPos
264#define outFile output.o_file.of_outFile
b04c4147 265#define outFd output.o_file.of_outFd
7051be4f 266
9de1d47a
MO
267TAILQ_HEAD(JobList, Job);
268
984263bc
MD
269/*
270 * error handling variables
271 */
df64c352
MO
272static int errors = 0; /* number of errors reported */
273static int aborting = 0; /* why is the make aborting? */
274#define ABORT_ERROR 1 /* Because of an error */
275#define ABORT_INTERRUPT 2 /* Because it was interrupted */
276#define ABORT_WAIT 3 /* Waiting for jobs to finish */
984263bc
MD
277
278/*
279 * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
280 * is a char! So when we go above 127 we turn negative!
281 */
fbfaa208 282#define FILENO(a) ((unsigned)fileno(a))
984263bc
MD
283
284/*
285 * post-make command processing. The node postCommands is really just the
286 * .END target but we keep it around to avoid having to search for it
287 * all the time.
288 */
df64c352
MO
289static GNode *postCommands;
290
291/*
292 * The number of commands actually printed for a target. Should this
293 * number be 0, no shell will be executed.
294 */
295static int numCommands;
984263bc
MD
296
297/*
298 * Return values from JobStart.
299 */
df64c352 300#define JOB_RUNNING 0 /* Job is running */
b04c4147 301#define JOB_ERROR 1 /* Error in starting the job */
df64c352
MO
302#define JOB_FINISHED 2 /* The job is already finished */
303#define JOB_STOPPED 3 /* The job is stopped */
984263bc 304
c5784061
MO
305/*
306 * The maximum number of jobs that may run. This is initialize from the
307 * -j argument for the leading make and from the FIFO for sub-makes.
308 */
309static int maxJobs;
9de1d47a 310static int nJobs; /* The number of children currently running */
0a7e0b85
MO
311
312/* The structures that describe them */
9de1d47a 313static struct JobList jobs = TAILQ_HEAD_INITIALIZER(jobs);
0a7e0b85 314
b04c4147 315static Boolean jobFull; /* Flag to tell when the job table is full. It
984263bc 316 * is set TRUE when (1) the total number of
a34ec481 317 * running jobs equals the maximum allowed */
218b5aa1
MD
318#ifdef USE_KQUEUE
319static int kqfd; /* File descriptor obtained by kqueue() */
320#else
b04c4147 321static fd_set outputs; /* Set of descriptors of pipes connected to
984263bc
MD
322 * the output channels of children */
323#endif
324
b04c4147 325static GNode *lastNode; /* The node for which output was most recently
984263bc 326 * produced. */
b04c4147 327static const char *targFmt; /* Format string to use to head output from a
984263bc
MD
328 * job when it's not the most-recent job heard
329 * from */
330
a34ec481
JS
331#define TARG_FMT "--- %s ---\n" /* Default format */
332#define MESSAGE(fp, gn) \
fbfaa208 333 fprintf(fp, targFmt, gn->name);
984263bc
MD
334
335/*
a34ec481
JS
336 * When JobStart attempts to run a job but isn't allowed to
337 * or when Job_CatchChildren detects a job that has
338 * been stopped somehow, the job is placed on the stoppedJobs queue to be run
984263bc 339 * when the next job finishes.
0a7e0b85
MO
340 *
341 * Lst of Job structures describing jobs that were stopped due to
342 * concurrency limits or externally
984263bc 343 */
9de1d47a 344static struct JobList stoppedJobs = TAILQ_HEAD_INITIALIZER(stoppedJobs);
984263bc 345
9de1d47a
MO
346static int fifoFd; /* Fd of our job fifo */
347static char fifoName[] = "/tmp/make_fifo_XXXXXXXXX";
348static int fifoMaster;
984263bc 349
89a1b397
JS
350static sig_atomic_t interrupted;
351
352
984263bc
MD
353#if defined(USE_PGRP) && defined(SYSV)
354# define KILL(pid, sig) killpg(-(pid), (sig))
355#else
356# if defined(USE_PGRP)
357# define KILL(pid, sig) killpg((pid), (sig))
358# else
359# define KILL(pid, sig) kill((pid), (sig))
360# endif
361#endif
362
363/*
364 * Grmpf... There is no way to set bits of the wait structure
365 * anymore with the stupid W*() macros. I liked the union wait
366 * stuff much more. So, we devise our own macros... This is
367 * really ugly, use dramamine sparingly. You have been warned.
368 */
913800f5 369#define W_SETMASKED(st, val, fun) \
984263bc 370 { \
fbfaa208 371 int sh = (int)~0; \
984263bc
MD
372 int mask = fun(sh); \
373 \
374 for (sh = 0; ((mask >> sh) & 1) == 0; sh++) \
375 continue; \
376 *(st) = (*(st) & ~mask) | ((val) << sh); \
377 }
378
913800f5
MD
379#define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
380#define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
984263bc 381
2d8a3be7
EN
382static void JobRestart(Job *);
383static int JobStart(GNode *, int, Job *);
2d8a3be7 384static void JobDoOutput(Job *, Boolean);
2d8a3be7
EN
385static void JobInterrupt(int, int);
386static void JobRestartJobs(void);
53e478a3
MO
387static int Compat_RunCommand(char *, struct GNode *);
388
29004ef5
MO
389static GNode *curTarg = NULL;
390static GNode *ENDNode;
391
140bd23a
MO
392/**
393 * Create a fifo file with a uniq filename, and returns a file
394 * descriptor to that fifo.
395 */
396static int
397mkfifotemp(char *template)
398{
399 char *start;
400 char *pathend;
401 char *ptr;
b2760e78 402 const char padchar[] =
140bd23a
MO
403 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
404
405 if (template[0] == '\0') {
406 errno = EINVAL; /* bad input string */
407 return (-1);
408 }
409
410 /* Find end of template string. */
411 pathend = strchr(template, '\0');
412 ptr = pathend - 1;
413
414 /*
415 * Starting from the end of the template replace spaces with 'X' in
416 * them with random characters until there are no more 'X'.
417 */
418 while (ptr >= template && *ptr == 'X') {
419 uint32_t rand_num = arc4random() % (sizeof(padchar) - 1);
420 *ptr-- = padchar[rand_num];
421 }
422 start = ptr + 1;
423
424 /* Check the target directory. */
425 for (; ptr > template; --ptr) {
426 if (*ptr == '/') {
427 struct stat sbuf;
428
429 *ptr = '\0';
430 if (stat(template, &sbuf) != 0)
431 return (-1);
432
433 if (!S_ISDIR(sbuf.st_mode)) {
434 errno = ENOTDIR;
435 return (-1);
436 }
437 *ptr = '/';
438 break;
439 }
440 }
441
442 for (;;) {
443 if (mkfifo(template, 0600) == 0) {
444 int fd;
445
446 if ((fd = open(template, O_RDWR, 0600)) < 0) {
447 unlink(template);
448 return (-1);
449 } else {
450 return (fd);
451 }
452 } else {
453 if (errno != EEXIST) {
454 return (-1);
455 }
456 }
457
458 /*
459 * If we have a collision, cycle through the space of
460 * filenames.
461 */
462 for (ptr = start;;) {
463 char *pad;
464
465 if (*ptr == '\0' || ptr == pathend)
466 return (-1);
467
468 pad = strchr(padchar, *ptr);
469 if (pad == NULL || *++pad == '\0') {
470 *ptr++ = padchar[0];
471 } else {
472 *ptr++ = *pad;
473 break;
474 }
475 }
476 }
477 /*NOTREACHED*/
478}
479
ca8582e4
MO
480static void
481catch_child(int sig __unused)
482{
483}
484
04cee6af
MO
485/**
486 * In lieu of a good way to prevent every possible looping in make(1), stop
487 * there from being more than MKLVL_MAXVAL processes forked by make(1), to
488 * prevent a forkbomb from happening, in a dumb and mechanical way.
489 *
490 * Side Effects:
491 * Creates or modifies enviornment variable MKLVL_ENVVAR via setenv().
492 */
493static void
494check_make_level(void)
495{
496 char *value = getenv(MKLVL_ENVVAR);
497 int level = (value == NULL) ? 0 : atoi(value);
498
499 if (level < 0) {
500 errc(2, EAGAIN, "Invalid value for recursion level (%d).",
501 level);
502 } else if (level > MKLVL_MAXVAL) {
503 errc(2, EAGAIN, "Max recursion level (%d) exceeded.",
504 MKLVL_MAXVAL);
505 } else {
506 char new_value[32];
507 sprintf(new_value, "%d", level + 1);
508 setenv(MKLVL_ENVVAR, new_value, 1);
509 }
510}
511
ca8582e4
MO
512/**
513 */
514void
515Proc_Init()
516{
517 /*
518 * Catch SIGCHLD so that we get kicked out of select() when we
519 * need to look at a child. This is only known to matter for the
520 * -j case (perhaps without -P).
521 *
522 * XXX this is intentionally misplaced.
523 */
524 struct sigaction sa;
525
526 sigemptyset(&sa.sa_mask);
527 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
528 sa.sa_handler = catch_child;
529 sigaction(SIGCHLD, &sa, NULL);
530
04cee6af
MO
531 check_make_level();
532
533#ifdef RLIMIT_NOFILE
534 /*
535 * get rid of resource limit on file descriptors
536 */
537 {
538 struct rlimit rl;
539 if (getrlimit(RLIMIT_NOFILE, &rl) == -1) {
540 err(2, "getrlimit");
541 }
542 rl.rlim_cur = rl.rlim_max;
543 if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
544 err(2, "setrlimit");
545 }
546 }
547#endif
548
ca8582e4
MO
549#if DEFSHELL == 2
550 /*
551 * Turn off ENV to make ksh happier.
552 */
553 unsetenv("ENV");
554#endif
555}
556
ebf8e7fe 557/**
6319dcf0 558 * Wait for child process to terminate.
ebf8e7fe
MO
559 */
560static int
561ProcWait(ProcStuff *ps)
562{
563 pid_t pid;
564 int status;
565
566 /*
567 * Wait for the process to exit.
568 */
6319dcf0 569 for (;;) {
22e8072a 570 pid = waitpid(ps->child_pid, &status, 0);
6319dcf0
MO
571 if (pid == -1 && errno != EINTR) {
572 Fatal("error in wait: %d", pid);
573 /* NOTREACHED */
574 }
575 if (pid == ps->child_pid) {
576 break;
577 }
578 if (interrupted) {
579 break;
580 }
ebf8e7fe
MO
581 }
582
583 return (status);
584}
585
df64c352 586/**
89a1b397 587 * JobCatchSignal
df64c352
MO
588 * Got a signal. Set global variables and hope that someone will
589 * handle it.
89a1b397
JS
590 */
591static void
592JobCatchSig(int signo)
593{
594
595 interrupted = signo;
596}
597
df64c352 598/**
90b7ba34 599 * JobPassSig
a34ec481 600 * Pass a signal on to all local jobs if
984263bc
MD
601 * USE_PGRP is defined, then die ourselves.
602 *
984263bc
MD
603 * Side Effects:
604 * We die by the same signal.
984263bc
MD
605 */
606static void
84de9e23 607JobPassSig(int signo)
984263bc 608{
3120aaed 609 Job *job;
df64c352
MO
610 sigset_t nmask, omask;
611 struct sigaction act;
612
613 sigemptyset(&nmask);
614 sigaddset(&nmask, signo);
615 sigprocmask(SIG_SETMASK, &nmask, &omask);
616
617 DEBUGF(JOB, ("JobPassSig(%d) called.\n", signo));
3120aaed
MO
618 TAILQ_FOREACH(job, &jobs, link) {
619 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
620 signo, (intmax_t)job->pid));
621 KILL(job->pid, signo);
622 }
df64c352
MO
623
624 /*
625 * Deal with proper cleanup based on the signal received. We only run
626 * the .INTERRUPT target if the signal was in fact an interrupt.
627 * The other three termination signals are more of a "get out *now*"
628 * command.
629 */
630 if (signo == SIGINT) {
631 JobInterrupt(TRUE, signo);
9de1d47a 632 } else if (signo == SIGHUP || signo == SIGTERM || signo == SIGQUIT) {
df64c352
MO
633 JobInterrupt(FALSE, signo);
634 }
635
636 /*
637 * Leave gracefully if SIGQUIT, rather than core dumping.
638 */
639 if (signo == SIGQUIT) {
640 signo = SIGINT;
641 }
642
643 /*
644 * Send ourselves the signal now we've given the message to everyone
645 * else. Note we block everything else possible while we're getting
646 * the signal. This ensures that all our jobs get continued when we
647 * wake up before we take any other signal.
648 * XXX this comment seems wrong.
649 */
650 act.sa_handler = SIG_DFL;
651 sigemptyset(&act.sa_mask);
652 act.sa_flags = 0;
653 sigaction(signo, &act, NULL);
654
655 DEBUGF(JOB, ("JobPassSig passing signal to self, mask = %x.\n",
656 ~0 & ~(1 << (signo - 1))));
657 signal(signo, SIG_DFL);
658
659 KILL(getpid(), signo);
660
661 signo = SIGCONT;
3120aaed
MO
662 TAILQ_FOREACH(job, &jobs, link) {
663 DEBUGF(JOB, ("JobPassSig passing signal %d to child %jd.\n",
664 signo, (intmax_t)job->pid));
665 KILL(job->pid, signo);
666 }
df64c352
MO
667
668 sigprocmask(SIG_SETMASK, &omask, NULL);
669 sigprocmask(SIG_SETMASK, &omask, NULL);
670 act.sa_handler = JobPassSig;
671 sigaction(signo, &act, NULL);
984263bc
MD
672}
673
df64c352 674/**
90b7ba34 675 * JobPrintCommand
984263bc
MD
676 * Put out another command for the given job. If the command starts
677 * with an @ or a - we process it specially. In the former case,
678 * so long as the -s and -n flags weren't given to make, we stick
679 * a shell-specific echoOff command in the script. In the latter,
680 * we ignore errors for the entire job, unless the shell has error
681 * control.
682 * If the command is just "..." we take all future commands for this
683 * job to be commands to be executed once the entire graph has been
684 * made and return non-zero to signal that the end of the commands
685 * was reached. These commands are later attached to the postCommands
9a309bcc 686 * node and executed by Job_Finish when all things are done.
3637a988 687 * This function is called from JobStart via LST_FOREACH.
984263bc
MD
688 *
689 * Results:
690 * Always 0, unless the command was "..."
691 *
692 * Side Effects:
693 * If the command begins with a '-' and the shell has no error control,
694 * the JOB_IGNERR flag is set in the job descriptor.
695 * If the command is "..." and we're not ignoring such things,
696 * tailCmds is set to the successor node of the cmd.
697 * numCommands is incremented if the command is actually printed.
984263bc
MD
698 */
699static int
3120aaed 700JobPrintCommand(char *cmd, Job *job)
984263bc 701{
df64c352 702 Boolean noSpecials; /* true if we shouldn't worry about
271e747f
MO
703 * inserting special commands into
704 * the input stream. */
df64c352 705 Boolean shutUp = FALSE; /* true if we put a no echo command
271e747f 706 * into the command file */
df64c352 707 Boolean errOff = FALSE; /* true if we turned error checking
271e747f
MO
708 * off before printing the command
709 * and need to turn it back on */
df64c352
MO
710 const char *cmdTemplate;/* Template to use when printing the command */
711 char *cmdStart; /* Start of expanded command */
712 LstNode *cmdNode; /* Node for replacing the command */
df64c352
MO
713
714 noSpecials = (noExecute && !(job->node->type & OP_MAKE));
715
716 if (strcmp(cmd, "...") == 0) {
717 job->node->type |= OP_SAVE_CMDS;
718 if ((job->flags & JOB_IGNDOTS) == 0) {
719 job->tailCmds =
720 Lst_Succ(Lst_Member(&job->node->commands, cmd));
721 return (1);
722 }
723 return (0);
984263bc 724 }
984263bc 725
df64c352
MO
726#define DBPRINTF(fmt, arg) \
727 DEBUGF(JOB, (fmt, arg)); \
728 fprintf(job->cmdFILE, fmt, arg); \
729 fflush(job->cmdFILE);
984263bc 730
df64c352 731 numCommands += 1;
984263bc 732
df64c352
MO
733 /*
734 * For debugging, we replace each command with the result of expanding
735 * the variables in the command.
736 */
737 cmdNode = Lst_Member(&job->node->commands, cmd);
68061244 738
e576a084 739 cmd = Buf_Peel(Var_Subst(cmd, job->node, FALSE));
df64c352 740 cmdStart = cmd;
68061244 741
df64c352 742 Lst_Replace(cmdNode, cmdStart);
984263bc 743
df64c352 744 cmdTemplate = "%s\n";
984263bc 745
df64c352
MO
746 /*
747 * Check for leading @', -' or +'s to control echoing, error checking,
748 * and execution on -n.
749 */
750 while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
751 switch (*cmd) {
40763d81 752
df64c352
MO
753 case '@':
754 shutUp = DEBUG(LOUD) ? FALSE : TRUE;
755 break;
40763d81 756
df64c352
MO
757 case '-':
758 errOff = TRUE;
759 break;
40763d81 760
df64c352
MO
761 case '+':
762 if (noSpecials) {
763 /*
764 * We're not actually exececuting anything...
765 * but this one needs to be - use compat mode
766 * just for it.
767 */
3120aaed 768 Compat_RunCommand(cmd, job->node);
df64c352
MO
769 return (0);
770 }
771 break;
772 }
773 cmd++;
984263bc 774 }
984263bc 775
df64c352
MO
776 while (isspace((unsigned char)*cmd))
777 cmd++;
984263bc 778
df64c352
MO
779 if (shutUp) {
780 if (!(job->flags & JOB_SILENT) && !noSpecials &&
984263bc
MD
781 commandShell->hasEchoCtl) {
782 DBPRINTF("%s\n", commandShell->echoOff);
984263bc 783 } else {
df64c352 784 shutUp = FALSE;
984263bc 785 }
df64c352
MO
786 }
787
788 if (errOff) {
789 if (!(job->flags & JOB_IGNERR) && !noSpecials) {
790 if (commandShell->hasErrCtl) {
791 /*
792 * We don't want the error-control commands
793 * showing up either, so we turn off echoing
794 * while executing them. We could put another
795 * field in the shell structure to tell
796 * JobDoOutput to look for this string too,
797 * but why make it any more complex than
798 * it already is?
799 */
800 if (!(job->flags & JOB_SILENT) && !shutUp &&
801 commandShell->hasEchoCtl) {
802 DBPRINTF("%s\n", commandShell->echoOff);
803 DBPRINTF("%s\n", commandShell->ignErr);
804 DBPRINTF("%s\n", commandShell->echoOn);
805 } else {
806 DBPRINTF("%s\n", commandShell->ignErr);
807 }
808 } else if (commandShell->ignErr &&
9de1d47a 809 *commandShell->ignErr != '\0') {
df64c352
MO
810 /*
811 * The shell has no error control, so we need to
812 * be weird to get it to ignore any errors from
813 * the command. If echoing is turned on, we turn
814 * it off and use the errCheck template to echo
815 * the command. Leave echoing off so the user
816 * doesn't see the weirdness we go through to
817 * ignore errors. Set cmdTemplate to use the
818 * weirdness instead of the simple "%s\n"
819 * template.
820 */
821 if (!(job->flags & JOB_SILENT) && !shutUp &&
822 commandShell->hasEchoCtl) {
823 DBPRINTF("%s\n", commandShell->echoOff);
824 DBPRINTF(commandShell->errCheck, cmd);
825 shutUp = TRUE;
826 }
827 cmdTemplate = commandShell->ignErr;
828 /*
829 * The error ignoration (hee hee) is already
830 * taken care of by the ignErr template, so
831 * pretend error checking is still on.
832 */
833 errOff = FALSE;
834 } else {
835 errOff = FALSE;
836 }
837 } else {
838 errOff = FALSE;
839 }
840 }
841
842 DBPRINTF(cmdTemplate, cmd);
843
844 if (errOff) {
984263bc 845 /*
df64c352
MO
846 * If echoing is already off, there's no point in issuing the
847 * echoOff command. Otherwise we issue it and pretend it was on
848 * for the whole command...
984263bc 849 */
df64c352 850 if (!shutUp && !(job->flags & JOB_SILENT) &&
984263bc
MD
851 commandShell->hasEchoCtl) {
852 DBPRINTF("%s\n", commandShell->echoOff);
984263bc
MD
853 shutUp = TRUE;
854 }
df64c352 855 DBPRINTF("%s\n", commandShell->errCheck);
984263bc 856 }
df64c352
MO
857 if (shutUp) {
858 DBPRINTF("%s\n", commandShell->echoOn);
859 }
860 return (0);
984263bc
MD
861}
862
df64c352 863/**
90b7ba34 864 * JobClose
984263bc
MD
865 * Called to close both input and output pipes when a job is finished.
866 *
984263bc
MD
867 * Side Effects:
868 * The file descriptors associated with the job are closed.
984263bc
MD
869 */
870static void
84de9e23 871JobClose(Job *job)
984263bc 872{
fbfaa208 873
df64c352 874 if (usePipes) {
a34ec481 875#if !defined(USE_KQUEUE)
df64c352 876 FD_CLR(job->inPipe, &outputs);
984263bc 877#endif
df64c352
MO
878 if (job->outPipe != job->inPipe) {
879 close(job->outPipe);
880 }
881 JobDoOutput(job, TRUE);
882 close(job->inPipe);
883 } else {
884 close(job->outFd);
885 JobDoOutput(job, TRUE);
886 }
984263bc
MD
887}
888
df64c352 889/**
90b7ba34 890 * JobFinish
984263bc
MD
891 * Do final processing for the given job including updating
892 * parents and starting new jobs as available/necessary. Note
893 * that we pay no attention to the JOB_IGNERR flag here.
894 * This is because when we're called because of a noexecute flag
895 * or something, jstat.w_status is 0 and when called from
896 * Job_CatchChildren, the status is zeroed if it s/b ignored.
897 *
984263bc
MD
898 * Side Effects:
899 * Some nodes may be put on the toBeMade queue.
900 * Final commands for the job are placed on postCommands.
901 *
902 * If we got an error and are aborting (aborting == ABORT_ERROR) and
903 * the job list is now empty, we are done for the day.
904 * If we recognized an error (errors !=0), we set the aborting flag
905 * to ABORT_ERROR so no more jobs will be started.
984263bc 906 */
984263bc 907static void
84de9e23 908JobFinish(Job *job, int *status)
984263bc 909{
df64c352
MO
910 Boolean done;
911 LstNode *ln;
984263bc 912
afdaaa9e
MO
913 if (WIFEXITED(*status)) {
914 int job_status = WEXITSTATUS(*status);
df64c352 915
afdaaa9e 916 JobClose(job);
df64c352 917 /*
afdaaa9e
MO
918 * Deal with ignored errors in -B mode. We need to
919 * print a message telling of the ignored error as
920 * well as setting status.w_status to 0 so the next
921 * command gets run. To do this, we set done to be
922 * TRUE if in -B mode and the job exited non-zero.
df64c352 923 */
afdaaa9e
MO
924 if (job_status == 0) {
925 done = FALSE;
926 } else {
927 if (job->flags & JOB_IGNERR) {
928 done = TRUE;
929 } else {
930 /*
931 * If it exited non-zero and either we're
932 * doing things our way or we're not ignoring
933 * errors, the job is finished. Similarly, if
934 * the shell died because of a signal the job
935 * is also finished. In these cases, finish
936 * out the job's output before printing the
937 * exit status...
938 */
939 done = TRUE;
940 if (job->cmdFILE != NULL &&
941 job->cmdFILE != stdout) {
942 fclose(job->cmdFILE);
943 }
df64c352 944
afdaaa9e
MO
945 }
946 }
947 } else if (WIFSIGNALED(*status)) {
948 if (WTERMSIG(*status) == SIGCONT) {
949 /*
950 * No need to close things down or anything.
951 */
952 done = FALSE;
953 } else {
954 /*
955 * If it exited non-zero and either we're
956 * doing things our way or we're not ignoring
957 * errors, the job is finished. Similarly, if
958 * the shell died because of a signal the job
959 * is also finished. In these cases, finish
960 * out the job's output before printing the
961 * exit status...
962 */
963 JobClose(job);
964 if (job->cmdFILE != NULL &&
965 job->cmdFILE != stdout) {
966 fclose(job->cmdFILE);
967 }
968 done = TRUE;
969 }
984263bc 970 } else {
df64c352
MO
971 /*
972 * No need to close things down or anything.
973 */
974 done = FALSE;
984263bc
MD
975 }
976
6c8f235e
MO
977 if (WIFEXITED(*status)) {
978 if (done || DEBUG(JOB)) {
979 FILE *out;
df64c352 980
6c8f235e
MO
981 if (compatMake &&
982 !usePipes &&
983 (job->flags & JOB_IGNERR)) {
984 /*
985 * If output is going to a file and this job
986 * is ignoring errors, arrange to have the
987 * exit status sent to the output file as
988 * well.
989 */
990 out = fdopen(job->outFd, "w");
991 if (out == NULL)
992 Punt("Cannot fdopen");
993 } else {
994 out = stdout;
995 }
984263bc 996
9de1d47a
MO
997 DEBUGF(JOB, ("Process %jd exited.\n",
998 (intmax_t)job->pid));
6c8f235e
MO
999
1000 if (WEXITSTATUS(*status) == 0) {
1001 if (DEBUG(JOB)) {
1002 if (usePipes && job->node != lastNode) {
1003 MESSAGE(out, job->node);
1004 lastNode = job->node;
1005 }
1006 fprintf(out,
1007 "*** Completed successfully\n");
1008 }
1009 } else {
df64c352
MO
1010 if (usePipes && job->node != lastNode) {
1011 MESSAGE(out, job->node);
1012 lastNode = job->node;
1013 }
1014 fprintf(out, "*** Error code %d%s\n",
6c8f235e
MO
1015 WEXITSTATUS(*status),
1016 (job->flags & JOB_IGNERR) ?
1017 "(ignored)" : "");
df64c352
MO
1018
1019 if (job->flags & JOB_IGNERR) {
1020 *status = 0;
1021 }
df64c352
MO
1022 }
1023
df64c352 1024 fflush(out);
6c8f235e
MO
1025 }
1026 } else if (WIFSIGNALED(*status)) {
1027 if (done || DEBUG(JOB) || (WTERMSIG(*status) == SIGCONT)) {
1028 FILE *out;
df64c352 1029
6c8f235e
MO
1030 if (compatMake &&
1031 !usePipes &&
1032 (job->flags & JOB_IGNERR)) {
1033 /*
1034 * If output is going to a file and this job
1035 * is ignoring errors, arrange to have the
1036 * exit status sent to the output file as
1037 * well.
1038 */
1039 out = fdopen(job->outFd, "w");
1040 if (out == NULL)
1041 Punt("Cannot fdopen");
1042 } else {
1043 out = stdout;
df64c352 1044 }
6c8f235e
MO
1045
1046 if (WTERMSIG(*status) == SIGCONT) {
df64c352 1047 /*
6c8f235e
MO
1048 * If the beastie has continued, shift the
1049 * Job from the stopped list to the running
1050 * one (or re-stop it if concurrency is
1051 * exceeded) and go and get another child.
df64c352 1052 */
6c8f235e
MO
1053 if (job->flags & (JOB_RESUME | JOB_RESTART)) {
1054 if (usePipes && job->node != lastNode) {
1055 MESSAGE(out, job->node);
1056 lastNode = job->node;
1057 }
1058 fprintf(out, "*** Continued\n");
1059 }
1060 if (!(job->flags & JOB_CONTINUING)) {
1061 DEBUGF(JOB, ("Warning: process %jd was not "
1062 "continuing.\n", (intmax_t) job->pid));
1063#ifdef notdef
1064 /*
1065 * We don't really want to restart a
1066 * job from scratch just because it
1067 * continued, especially not without
1068 * killing the continuing process!
1069 * That's why this is ifdef'ed out.
1070 * FD - 9/17/90
1071 */
1072 JobRestart(job);
984263bc 1073#endif
6c8f235e
MO
1074 }
1075 job->flags &= ~JOB_CONTINUING;
1076 TAILQ_INSERT_TAIL(&jobs, job, link);
1077 nJobs += 1;
1078 DEBUGF(JOB, ("Process %jd is continuing locally.\n",
1079 (intmax_t) job->pid));
1080 if (nJobs == maxJobs) {
1081 jobFull = TRUE;
1082 DEBUGF(JOB, ("Job queue is full.\n"));
1083 }
1084 fflush(out);
1085 return;
1086
1087 } else {
1088 if (usePipes && job->node != lastNode) {
1089 MESSAGE(out, job->node);
1090 lastNode = job->node;
1091 }
1092 fprintf(out,
1093 "*** Signal %d\n", WTERMSIG(*status));
1094 fflush(out);
df64c352 1095 }
6c8f235e
MO
1096 }
1097 } else {
1098 /* STOPPED */
1099 FILE *out;
df64c352 1100
6c8f235e
MO
1101 if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
1102 /*
1103 * If output is going to a file and this job
1104 * is ignoring errors, arrange to have the
1105 * exit status sent to the output file as
1106 * well.
1107 */
1108 out = fdopen(job->outFd, "w");
1109 if (out == NULL)
1110 Punt("Cannot fdopen");
df64c352 1111 } else {
6c8f235e 1112 out = stdout;
df64c352
MO
1113 }
1114
6c8f235e
MO
1115 DEBUGF(JOB, ("Process %jd stopped.\n", (intmax_t) job->pid));
1116 if (usePipes && job->node != lastNode) {
1117 MESSAGE(out, job->node);
1118 lastNode = job->node;
1119 }
1120 fprintf(out, "*** Stopped -- signal %d\n", WSTOPSIG(*status));
1121 job->flags |= JOB_RESUME;
1122 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
df64c352 1123 fflush(out);
6c8f235e 1124 return;
df64c352
MO
1125 }
1126
984263bc 1127 /*
df64c352
MO
1128 * Now handle the -B-mode stuff. If the beast still isn't finished,
1129 * try and restart the job on the next command. If JobStart says it's
1130 * ok, it's ok. If there's an error, this puppy is done.
984263bc 1131 */
df64c352
MO
1132 if (compatMake && WIFEXITED(*status) &&
1133 Lst_Succ(job->node->compat_command) != NULL) {
1134 switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
1135 case JOB_RUNNING:
1136 done = FALSE;
1137 break;
1138 case JOB_ERROR:
1139 done = TRUE;
1140 W_SETEXITSTATUS(status, 1);
1141 break;
1142 case JOB_FINISHED:
1143 /*
1144 * If we got back a JOB_FINISHED code, JobStart has
1145 * already called Make_Update and freed the job
1146 * descriptor. We set done to false here to avoid fake
1147 * cycles and double frees. JobStart needs to do the
1148 * update so we can proceed up the graph when given
1149 * the -n flag..
1150 */
1151 done = FALSE;
1152 break;
1153 default:
1154 break;
1155 }
1156 } else {
1157 done = TRUE;
984263bc 1158 }
14ba7c54 1159
9de1d47a
MO
1160 if (done && aborting != ABORT_ERROR &&
1161 aborting != ABORT_INTERRUPT && *status == 0) {
df64c352
MO
1162 /*
1163 * As long as we aren't aborting and the job didn't return a
1164 * non-zero status that we shouldn't ignore, we call
1165 * Make_Update to update the parents. In addition, any saved
1166 * commands for the node are placed on the .END target.
1167 */
1168 for (ln = job->tailCmds; ln != NULL; ln = LST_NEXT(ln)) {
1169 Lst_AtEnd(&postCommands->commands,
e576a084
MO
1170 Buf_Peel(
1171 Var_Subst(Lst_Datum(ln), job->node, FALSE)));
df64c352 1172 }
984263bc 1173
df64c352
MO
1174 job->node->made = MADE;
1175 Make_Update(job->node);
1176 free(job);
984263bc 1177
df64c352
MO
1178 } else if (*status != 0) {
1179 errors += 1;
1180 free(job);
1181 }
1182
1183 JobRestartJobs();
984263bc 1184
984263bc 1185 /*
df64c352 1186 * Set aborting if any error.
984263bc 1187 */
9de1d47a 1188 if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
df64c352
MO
1189 /*
1190 * If we found any errors in this batch of children and the -k
1191 * flag wasn't given, we set the aborting flag so no more jobs
1192 * get started.
1193 */
1194 aborting = ABORT_ERROR;
1195 }
1196
9de1d47a 1197 if (aborting == ABORT_ERROR && Job_Empty()) {
df64c352
MO
1198 /*
1199 * If we are aborting and the job table is now empty, we finish.
1200 */
1201 Finish(errors);
1202 }
984263bc
MD
1203}
1204
df64c352
MO
1205/**
1206 * Job_Touch
984263bc 1207 * Touch the given target. Called by JobStart when the -t flag was
84de9e23 1208 * given. Prints messages unless told to be silent.
984263bc 1209 *
984263bc
MD
1210 * Side Effects:
1211 * The data modification of the file is changed. In addition, if the
1212 * file did not exist, it is created.
984263bc
MD
1213 */
1214void
84de9e23 1215Job_Touch(GNode *gn, Boolean silent)
984263bc 1216{
df64c352
MO
1217 int streamID; /* ID of stream opened to do the touch */
1218 struct utimbuf times; /* Times for utime() call */
984263bc 1219
df64c352
MO
1220 if (gn->type & (OP_JOIN | OP_USE | OP_EXEC | OP_OPTIONAL)) {
1221 /*
1222 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual"
1223 * targets and, as such, shouldn't really be created.
1224 */
1225 return;
1226 }
984263bc 1227
df64c352
MO
1228 if (!silent) {
1229 fprintf(stdout, "touch %s\n", gn->name);
1230 fflush(stdout);
1231 }
984263bc 1232
df64c352
MO
1233 if (noExecute) {
1234 return;
1235 }
984263bc 1236
df64c352
MO
1237 if (gn->type & OP_ARCHV) {
1238 Arch_Touch(gn);
1239 } else if (gn->type & OP_LIB) {
1240 Arch_TouchLib(gn);
1241 } else {
1242 char *file = gn->path ? gn->path : gn->name;
1243
1244 times.actime = times.modtime = now;
1245 if (utime(file, &times) < 0) {
1246 streamID = open(file, O_RDWR | O_CREAT, 0666);
1247
1248 if (streamID >= 0) {
1249 char c;
1250
1251 /*
1252 * Read and write a byte to the file to change
1253 * the modification time, then close the file.
1254 */
1255 if (read(streamID, &c, 1) == 1) {
1256 lseek(streamID, (off_t)0, SEEK_SET);
1257 write(streamID, &c, 1);
1258 }
1259
1260 close(streamID);
1261 } else {
1262 fprintf(stdout, "*** couldn't touch %s: %s",
1263 file, strerror(errno));
1264 fflush(stdout);
1265 }
984263bc 1266 }
984263bc 1267 }
984263bc
MD
1268}
1269
df64c352
MO
1270/**
1271 * Job_CheckCommands
984263bc
MD
1272 * Make sure the given node has all the commands it needs.
1273 *
1274 * Results:
1275 * TRUE if the commands list is/was ok.
1276 *
1277 * Side Effects:
1278 * The node will have commands from the .DEFAULT rule added to it
1279 * if it needs them.
984263bc
MD
1280 */
1281Boolean
84de9e23 1282Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
984263bc 1283{
fbfaa208 1284
df64c352
MO
1285 if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->commands) &&
1286 (gn->type & OP_LIB) == 0) {
1287 /*
1288 * No commands. Look for .DEFAULT rule from which we might infer
1289 * commands.
1290 */
9de1d47a 1291 if (DEFAULT != NULL && !Lst_IsEmpty(&DEFAULT->commands)) {
df64c352
MO
1292 /*
1293 * Make only looks for a .DEFAULT if the node was
1294 * never the target of an operator, so that's what we
1295 * do too. If a .DEFAULT was given, we substitute its
1296 * commands for gn's commands and set the IMPSRC
1297 * variable to be the target's name The DEFAULT node
1298 * acts like a transformation rule, in that gn also
1299 * inherits any attributes or sources attached to
1300 * .DEFAULT itself.
1301 */
1302 Make_HandleUse(DEFAULT, gn);
a2e49af9 1303 Var_Set(IMPSRC, Var_Value(TARGET, gn), gn);
df64c352
MO
1304
1305 } else if (Dir_MTime(gn) == 0) {
1306 /*
1307 * The node wasn't the target of an operator we have
1308 * no .DEFAULT rule to go on and the target doesn't
1309 * already exist. There's nothing more we can do for
1310 * this branch. If the -k flag wasn't given, we stop
1311 * in our tracks, otherwise we just don't update
1312 * this node's parents so they never get examined.
1313 */
1314 static const char msg[] =
1315 "make: don't know how to make";
1316
1317 if (gn->type & OP_OPTIONAL) {
1318 fprintf(stdout, "%s %s(ignored)\n",
1319 msg, gn->name);
1320 fflush(stdout);
1321 } else if (keepgoing) {
1322 fprintf(stdout, "%s %s(continuing)\n",
1323 msg, gn->name);
1324 fflush(stdout);
1325 return (FALSE);
1326 } else {
984263bc 1327#if OLD_JOKE
df64c352
MO
1328 if (strcmp(gn->name,"love") == 0)
1329 (*abortProc)("Not war.");
1330 else
984263bc 1331#endif
df64c352
MO
1332 (*abortProc)("%s %s. Stop",
1333 msg, gn->name);
1334 return (FALSE);
1335 }
1336 }
984263bc 1337 }
df64c352 1338 return (TRUE);
984263bc 1339}
984263bc 1340
df64c352
MO
1341/**
1342 * JobExec
984263bc
MD
1343 * Execute the shell for the given job. Called from JobStart and
1344 * JobRestart.
1345 *
984263bc
MD
1346 * Side Effects:
1347 * A shell is executed, outputs is altered and the Job structure added
1348 * to the job table.
984263bc
MD
1349 */
1350static void
84de9e23 1351JobExec(Job *job, char **argv)
984263bc 1352{
8a538fd1 1353 ProcStuff ps;
984263bc 1354
df64c352 1355 if (DEBUG(JOB)) {
b04c4147 1356 int i;
df64c352
MO
1357
1358 DEBUGF(JOB, ("Running %s\n", job->node->name));
1359 DEBUGF(JOB, ("\tCommand: "));
1360 for (i = 0; argv[i] != NULL; i++) {
1361 DEBUGF(JOB, ("%s ", argv[i]));
1362 }
1363 DEBUGF(JOB, ("\n"));
984263bc 1364 }
df64c352 1365
984263bc 1366 /*
df64c352
MO
1367 * Some jobs produce no output and it's disconcerting to have
1368 * no feedback of their running (since they produce no output, the
1369 * banner with their name in it never appears). This is an attempt to
1370 * provide that feedback, even if nothing follows it.
984263bc 1371 */
9de1d47a 1372 if (lastNode != job->node && (job->flags & JOB_FIRST) &&
df64c352
MO
1373 !(job->flags & JOB_SILENT)) {
1374 MESSAGE(stdout, job->node);
1375 lastNode = job->node;
1376 }
1377
3e10c271
MO
1378 ps.in = FILENO(job->cmdFILE);
1379 if (usePipes) {
1380 /*
1381 * Set up the child's output to be routed through the
1382 * pipe we've created for it.
1383 */
1384 ps.out = job->outPipe;
1385 } else {
1386 /*
1387 * We're capturing output in a file, so we duplicate
1388 * the descriptor to the temporary file into the
1389 * standard output.
1390 */
1391 ps.out = job->outFd;
1392 }
1393 ps.err = STDERR_FILENO;
1394
1395 ps.merge_errors = 1;
1396 ps.pgroup = 1;
1397 ps.searchpath = 0;
1398
1399 ps.argv = argv;
d0a12c98 1400 ps.argv_free = 0;
3e10c271
MO
1401
1402 /*
7c2a9959
MO
1403 * Fork. Warning since we are doing vfork() instead of fork(),
1404 * do not allocate memory in the child process!
3e10c271 1405 */
ebf8e7fe 1406 if ((ps.child_pid = vfork()) == -1) {
df64c352
MO
1407 Punt("Cannot fork");
1408
ebf8e7fe 1409 } else if (ps.child_pid == 0) {
9de1d47a
MO
1410 /*
1411 * Child
1412 */
df64c352
MO
1413 if (fifoFd >= 0)
1414 close(fifoFd);
1415
8a538fd1 1416 ProcExec(&ps);
257e9734 1417 /* NOTREACHED */
984263bc 1418
53a3ba77 1419 } else {
9de1d47a 1420 /*
53a3ba77 1421 * Parent
9de1d47a 1422 */
ebf8e7fe 1423 job->pid = ps.child_pid;
53a3ba77
MO
1424
1425 if (usePipes && (job->flags & JOB_FIRST)) {
1426 /*
1427 * The first time a job is run for a node, we set the
1428 * current position in the buffer to the beginning and
1429 * mark another stream to watch in the outputs mask.
1430 */
218b5aa1 1431#ifdef USE_KQUEUE
53a3ba77 1432 struct kevent kev[2];
218b5aa1 1433#endif
53a3ba77 1434 job->curPos = 0;
984263bc 1435
a34ec481 1436#if defined(USE_KQUEUE)
53a3ba77
MO
1437 EV_SET(&kev[0], job->inPipe, EVFILT_READ, EV_ADD, 0, 0, job);
1438 EV_SET(&kev[1], job->pid, EVFILT_PROC,
1439 EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);
1440 if (kevent(kqfd, kev, 2, NULL, 0, NULL) != 0) {
1441 /*
1442 * kevent() will fail if the job is already
1443 * finished
1444 */
1445 if (errno != EINTR && errno != EBADF && errno != ESRCH)
1446 Punt("kevent: %s", strerror(errno));
1447 }
984263bc 1448#else
53a3ba77 1449 FD_SET(job->inPipe, &outputs);
a34ec481 1450#endif /* USE_KQUEUE */
53a3ba77 1451 }
984263bc 1452
53a3ba77
MO
1453 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1454 fclose(job->cmdFILE);
1455 job->cmdFILE = NULL;
1456 }
984263bc 1457
53a3ba77
MO
1458 /*
1459 * Now the job is actually running, add it to the table.
1460 */
1461 nJobs += 1;
1462 TAILQ_INSERT_TAIL(&jobs, job, link);
1463 if (nJobs == maxJobs) {
1464 jobFull = TRUE;
1465 }
df64c352 1466 }
984263bc
MD
1467}
1468
df64c352
MO
1469/**
1470 * JobMakeArgv
984263bc 1471 * Create the argv needed to execute the shell for a given job.
984263bc
MD
1472 */
1473static void
84de9e23 1474JobMakeArgv(Job *job, char **argv)
984263bc 1475{
df64c352
MO
1476 int argc;
1477 static char args[10]; /* For merged arguments */
984263bc 1478
880b6521 1479 argv[0] = commandShell->name;
df64c352 1480 argc = 1;
984263bc 1481
9de1d47a
MO
1482 if ((commandShell->exit && *commandShell->exit != '-') ||
1483 (commandShell->echo && *commandShell->echo != '-')) {
df64c352
MO
1484 /*
1485 * At least one of the flags doesn't have a minus before it, so
1486 * merge them together. Have to do this because the *(&(@*#*&#$#
1487 * Bourne shell thinks its second argument is a file to source.
1488 * Grrrr. Note the ten-character limitation on the combined
1489 * arguments.
1490 */
9de1d47a
MO
1491 sprintf(args, "-%s%s", (job->flags & JOB_IGNERR) ? "" :
1492 commandShell->exit ? commandShell->exit : "",
1493 (job->flags & JOB_SILENT) ? "" :
1494 commandShell->echo ? commandShell->echo : "");
df64c352
MO
1495
1496 if (args[1]) {
1497 argv[argc] = args;
1498 argc++;
1499 }
1500 } else {
1501 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1502 argv[argc] = commandShell->exit;
1503 argc++;
1504 }
1505 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1506 argv[argc] = commandShell->echo;
1507 argc++;
1508 }
1509 }
1510 argv[argc] = NULL;
984263bc
MD
1511}
1512
df64c352
MO
1513/**
1514 * JobRestart
9de1d47a
MO
1515 * Restart a job that stopped for some reason. The job must be neither
1516 * on the jobs nor on the stoppedJobs list.
984263bc 1517 *
984263bc
MD
1518 * Side Effects:
1519 * jobFull will be set if the job couldn't be run.
984263bc
MD
1520 */
1521static void
84de9e23 1522JobRestart(Job *job)
984263bc 1523{
984263bc 1524
df64c352 1525 if (job->flags & JOB_RESTART) {
984263bc 1526 /*
df64c352
MO
1527 * Set up the control arguments to the shell. This is based on
1528 * the flags set earlier for this job. If the JOB_IGNERR flag
1529 * is clear, the 'exit' flag of the commandShell is used to
1530 * cause it to exit upon receiving an error. If the JOB_SILENT
1531 * flag is clear, the 'echo' flag of the commandShell is used
1532 * to get it to start echoing as soon as it starts
1533 * processing commands.
984263bc 1534 */
df64c352
MO
1535 char *argv[4];
1536
1537 JobMakeArgv(job, argv);
1538
1539 DEBUGF(JOB, ("Restarting %s...", job->node->name));
9de1d47a 1540 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL)) {
df64c352 1541 /*
9de1d47a
MO
1542 * Not allowed to run -- put it back on the hold
1543 * queue and mark the table full
df64c352
MO
1544 */
1545 DEBUGF(JOB, ("holding\n"));
9de1d47a 1546 TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
df64c352
MO
1547 jobFull = TRUE;
1548 DEBUGF(JOB, ("Job queue is full.\n"));
1549 return;
1550 } else {
1551 /*
1552 * Job may be run locally.
1553 */
1554 DEBUGF(JOB, ("running locally\n"));
1555 }
1556 JobExec(job, argv);
984263bc 1557
984263bc 1558 } else {
df64c352
MO
1559 /*
1560 * The job has stopped and needs to be restarted.
1561 * Why it stopped, we don't know...
1562 */
1563 DEBUGF(JOB, ("Resuming %s...", job->node->name));
9de1d47a
MO
1564 if ((nJobs < maxJobs || ((job->flags & JOB_SPECIAL) &&
1565 maxJobs == 0)) && nJobs != maxJobs) {
df64c352
MO
1566 /*
1567 * If we haven't reached the concurrency limit already
1568 * (or the job must be run and maxJobs is 0), it's ok
1569 * to resume it.
1570 */
1571 Boolean error;
1572 int status;
1573
1574 error = (KILL(job->pid, SIGCONT) != 0);
1575
1576 if (!error) {
1577 /*
1578 * Make sure the user knows we've continued
1579 * the beast and actually put the thing in the
1580 * job table.
1581 */
1582 job->flags |= JOB_CONTINUING;
1583 status = 0;
1584 W_SETTERMSIG(&status, SIGCONT);
1585 JobFinish(job, &status);
1586
1587 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1588 DEBUGF(JOB, ("done\n"));
1589 } else {
1590 Error("couldn't resume %s: %s",
1591 job->node->name, strerror(errno));
1592 status = 0;
1593 W_SETEXITSTATUS(&status, 1);
1594 JobFinish(job, &status);
1595 }
1596 } else {
1597 /*
1598 * Job cannot be restarted. Mark the table as full and
1599 * place the job back on the list of stopped jobs.
1600 */
1601 DEBUGF(JOB, ("table full\n"));
9de1d47a 1602 TAILQ_INSERT_HEAD(&stoppedJobs, job, link);
df64c352
MO
1603 jobFull = TRUE;
1604 DEBUGF(JOB, ("Job queue is full.\n"));
1605 }
1606 }
984263bc
MD
1607}
1608
df64c352
MO
1609/**
1610 * JobStart
984263bc
MD
1611 * Start a target-creation process going for the target described
1612 * by the graph node gn.
1613 *
1614 * Results:
1615 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1616 * if there isn't actually anything left to do for the job and
1617 * JOB_RUNNING if the job has been started.
1618 *
1619 * Side Effects:
1620 * A new Job node is created and added to the list of running
1621 * jobs. PMake is forked and a child shell created.
984263bc
MD
1622 */
1623static int
84de9e23 1624JobStart(GNode *gn, int flags, Job *previous)
984263bc 1625{
df64c352
MO
1626 Job *job; /* new job descriptor */
1627 char *argv[4]; /* Argument vector to shell */
1628 Boolean cmdsOK; /* true if the nodes commands were all right */
1629 Boolean noExec; /* Set true if we decide not to run the job */
1630 int tfd; /* File descriptor for temp file */
1631 LstNode *ln;
9de1d47a 1632 char tfile[sizeof(TMPPAT)];
df64c352
MO
1633
1634 if (interrupted) {
1635 JobPassSig(interrupted);
1636 return (JOB_ERROR);
1637 }
1638 if (previous != NULL) {
1639 previous->flags &= ~(JOB_FIRST | JOB_IGNERR | JOB_SILENT);
1640 job = previous;
1641 } else {
1642 job = emalloc(sizeof(Job));
1643 flags |= JOB_FIRST;
1644 }
1645
1646 job->node = gn;
1647 job->tailCmds = NULL;
1648
984263bc 1649 /*
df64c352
MO
1650 * Set the initial value of the flags for this job based on the global
1651 * ones and the node's attributes... Any flags supplied by the caller
1652 * are also added to the field.
984263bc 1653 */
df64c352
MO
1654 job->flags = 0;
1655 if (Targ_Ignore(gn)) {
1656 job->flags |= JOB_IGNERR;
984263bc 1657 }
df64c352
MO
1658 if (Targ_Silent(gn)) {
1659 job->flags |= JOB_SILENT;
984263bc 1660 }
df64c352
MO
1661 job->flags |= flags;
1662
984263bc 1663 /*
df64c352
MO
1664 * Check the commands now so any attributes from .DEFAULT have a chance
1665 * to migrate to the node.
984263bc 1666 */
9de1d47a 1667 if (!compatMake && (job->flags & JOB_FIRST)) {
df64c352
MO
1668 cmdsOK = Job_CheckCommands(gn, Error);
1669 } else {
1670 cmdsOK = TRUE;
1671 }
984263bc
MD
1672
1673 /*
df64c352
MO
1674 * If the -n flag wasn't given, we open up OUR (not the child's)
1675 * temporary file to stuff commands in it. The thing is rd/wr so we
1676 * don't need to reopen it to feed it to the shell. If the -n flag
1677 * *was* given, we just set the file to be stdout. Cute, huh?
984263bc 1678 */
df64c352
MO
1679 if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
1680 /*
1681 * We're serious here, but if the commands were bogus, we're
1682 * also dead...
1683 */
1684 if (!cmdsOK) {
1685 DieHorribly();
1686 }
513bf0db 1687
df64c352
MO
1688 strcpy(tfile, TMPPAT);
1689 if ((tfd = mkstemp(tfile)) == -1)
1690 Punt("Cannot create temp file: %s", strerror(errno));
1691 job->cmdFILE = fdopen(tfd, "w+");
1692 eunlink(tfile);
1693 if (job->cmdFILE == NULL) {
1694 close(tfd);
1695 Punt("Could not open %s", tfile);
1696 }
1697 fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
513bf0db 1698 /*
df64c352
MO
1699 * Send the commands to the command file, flush all its
1700 * buffers then rewind and remove the thing.
513bf0db 1701 */
df64c352
MO
1702 noExec = FALSE;
1703
1704 /*
1705 * Used to be backwards; replace when start doing multiple
1706 * commands per shell.
1707 */
1708 if (compatMake) {
1709 /*
1710 * Be compatible: If this is the first time for this
1711 * node, verify its commands are ok and open the
1712 * commands list for sequential access by later
1713 * invocations of JobStart. Once that is done, we take
1714 * the next command off the list and print it to the
1715 * command file. If the command was an ellipsis, note
1716 * that there's nothing more to execute.
1717 */
1718 if (job->flags & JOB_FIRST)
1719 gn->compat_command = Lst_First(&gn->commands);
1720 else
1721 gn->compat_command =
1722 Lst_Succ(gn->compat_command);
1723
1724 if (gn->compat_command == NULL ||
1725 JobPrintCommand(Lst_Datum(gn->compat_command), job))
1726 noExec = TRUE;
1727
1728 if (noExec && !(job->flags & JOB_FIRST)) {
1729 /*
1730 * If we're not going to execute anything, the
1731 * job is done and we need to close down the
1732 * various file descriptors we've opened for
1733 * output, then call JobDoOutput to catch the
1734 * final characters or send the file to the
1735 * screen... Note that the i/o streams are only
1736 * open if this isn't the first job. Note also
1737 * that this could not be done in
1738 * Job_CatchChildren b/c it wasn't clear if
1739 * there were more commands to execute or not...
1740 */
1741 JobClose(job);
1742 }
1743 } else {
1744 /*
1745 * We can do all the commands at once. hooray for sanity
1746 */
1747 numCommands = 0;
1748 LST_FOREACH(ln, &gn->commands) {
1749 if (JobPrintCommand(Lst_Datum(ln), job))
1750 break;
1751 }
1752
1753 /*
1754 * If we didn't print out any commands to the shell
1755 * script, there's not much point in executing the
1756 * shell, is there?
1757 */
1758 if (numCommands == 0) {
1759 noExec = TRUE;
1760 }
1761 }
1762
1763 } else if (noExecute) {
1764 /*
1765 * Not executing anything -- just print all the commands to
1766 * stdout in one fell swoop. This will still set up
1767 * job->tailCmds correctly.
1768 */
1769 if (lastNode != gn) {
1770 MESSAGE(stdout, gn);
1771 lastNode = gn;
1772 }
1773 job->cmdFILE = stdout;
1774
1775 /*
1776 * Only print the commands if they're ok, but don't die if
1777 * they're not -- just let the user know they're bad and keep
1778 * going. It doesn't do any harm in this case and may do
1779 * some good.
1780 */
1781 if (cmdsOK) {
1782 LST_FOREACH(ln, &gn->commands) {
1783 if (JobPrintCommand(Lst_Datum(ln), job))
1784 break;
1785 }
1786 }
1787 /*
1788 * Don't execute the shell, thank you.
1789 */
984263bc 1790 noExec = TRUE;
df64c352 1791
984263bc 1792 } else {
df64c352
MO
1793 /*
1794 * Just touch the target and note that no shell should be
1795 * executed. Set cmdFILE to stdout to make life easier. Check
1796 * the commands, too, but don't die if they're no good -- it
1797 * does no harm to keep working up the graph.
1798 */
1799 job->cmdFILE = stdout;
1800 Job_Touch(gn, job->flags & JOB_SILENT);
1801 noExec = TRUE;
984263bc
MD
1802 }
1803
1804 /*
df64c352 1805 * If we're not supposed to execute a shell, don't.
984263bc 1806 */
df64c352
MO
1807 if (noExec) {
1808 /*
1809 * Unlink and close the command file if we opened one
1810 */
1811 if (job->cmdFILE != stdout) {
1812 if (job->cmdFILE != NULL)
1813 fclose(job->cmdFILE);
1814 } else {
1815 fflush(stdout);
1816 }
1817
1818 /*
1819 * We only want to work our way up the graph if we aren't here
1820 * because the commands for the job were no good.
1821 */
1822 if (cmdsOK) {
1823 if (aborting == 0) {
1824 for (ln = job->tailCmds; ln != NULL;
1825 ln = LST_NEXT(ln)) {
1826 Lst_AtEnd(&postCommands->commands,
e576a084
MO
1827 Buf_Peel(Var_Subst(Lst_Datum(ln),
1828 job->node, FALSE)));
df64c352
MO
1829 }
1830 job->node->made = MADE;
1831 Make_Update(job->node);
1832 }
1833 free(job);
1834 return(JOB_FINISHED);
1835 } else {
1836 free(job);
1837 return(JOB_ERROR);
984263bc 1838 }
984263bc 1839 } else {
df64c352 1840 fflush(job->cmdFILE);
984263bc 1841 }
984263bc 1842
984263bc 1843 /*
df64c352
MO
1844 * Set up the control arguments to the shell. This is based on the flags
1845 * set earlier for this job.
984263bc 1846 */
df64c352 1847 JobMakeArgv(job, argv);
984263bc 1848
df64c352
MO
1849 /*
1850 * If we're using pipes to catch output, create the pipe by which we'll
1851 * get the shell's output. If we're using files, print out that we're
1852 * starting a job and then set up its temporary-file name.
1853 */
1854 if (!compatMake || (job->flags & JOB_FIRST)) {
1855 if (usePipes) {
1856 int fd[2];
1857
1858 if (pipe(fd) == -1)
1859 Punt("Cannot create pipe: %s", strerror(errno));
1860 job->inPipe = fd[0];
1861 job->outPipe = fd[1];
1862 fcntl(job->inPipe, F_SETFD, 1);
1863 fcntl(job->outPipe, F_SETFD, 1);
1864 } else {
1865 fprintf(stdout, "Remaking `%s'\n", gn->name);
1866 fflush(stdout);
1867 strcpy(job->outFile, TMPPAT);
1868 if ((job->outFd = mkstemp(job->outFile)) == -1)
1869 Punt("cannot create temp file: %s",
1870 strerror(errno));
1871 fcntl(job->outFd, F_SETFD, 1);
984263bc 1872 }
df64c352
MO
1873 }
1874
9de1d47a 1875 if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL) && maxJobs != 0) {
984263bc 1876 /*
df64c352
MO
1877 * We've hit the limit of concurrency, so put the job on hold
1878 * until some other job finishes. Note that the special jobs
1879 * (.BEGIN, .INTERRUPT and .END) may be run even when the
1880 * limit has been reached (e.g. when maxJobs == 0).
984263bc 1881 */
df64c352
MO
1882 jobFull = TRUE;
1883
1884 DEBUGF(JOB, ("Can only run job locally.\n"));
1885 job->flags |= JOB_RESTART;
9de1d47a 1886 TAILQ_INSERT_TAIL(&stoppedJobs, job, link);
df64c352
MO
1887 } else {
1888 if (nJobs >= maxJobs) {
1889 /*
9de1d47a 1890 * If we're running this job as a special case
df64c352
MO
1891 * (see above), at least say the table is full.
1892 */
1893 jobFull = TRUE;
1894 DEBUGF(JOB, ("Local job queue is full.\n"));
984263bc 1895 }
df64c352
MO
1896 JobExec(job, argv);
1897 }
1898 return (JOB_RUNNING);
1899}
1900
1901static char *
1902JobOutput(Job *job, char *cp, char *endp, int msg)
1903{
1904 char *ecp;
1905
1906 if (commandShell->noPrint) {
4faecc47 1907 ecp = strstr(cp, commandShell->noPrint);
df64c352
MO
1908 while (ecp != NULL) {
1909 if (cp != ecp) {
1910 *ecp = '\0';
1911 if (msg && job->node != lastNode) {
1912 MESSAGE(stdout, job->node);
1913 lastNode = job->node;
1914 }
1915 /*
1916 * The only way there wouldn't be a newline
1917 * after this line is if it were the last in
1918 * the buffer. However, since the non-printable
1919 * comes after it, there must be a newline, so
1920 * we don't print one.
1921 */
1922 fprintf(stdout, "%s", cp);
1923 fflush(stdout);
1924 }
3120aaed 1925 cp = ecp + strlen(commandShell->noPrint);
df64c352
MO
1926 if (cp != endp) {
1927 /*
1928 * Still more to print, look again after
1929 * skipping the whitespace following the
1930 * non-printable command....
1931 */
1932 cp++;
1933 while (*cp == ' ' || *cp == '\t' ||
1934 *cp == '\n') {
1935 cp++;
1936 }
1937 ecp = strstr(cp, commandShell->noPrint);
1938 } else {
1939 return (cp);
1940 }
1941 }
984263bc 1942 }
df64c352 1943 return (cp);
984263bc
MD
1944}
1945
df64c352
MO
1946/**
1947 * JobDoOutput
984263bc
MD
1948 * This function is called at different times depending on
1949 * whether the user has specified that output is to be collected
1950 * via pipes or temporary files. In the former case, we are called
1951 * whenever there is something to read on the pipe. We collect more
1952 * output from the given job and store it in the job's outBuf. If
1953 * this makes up a line, we print it tagged by the job's identifier,
1954 * as necessary.
1955 * If output has been collected in a temporary file, we open the
1956 * file and read it line by line, transfering it to our own
1957 * output channel until the file is empty. At which point we
1958 * remove the temporary file.
1959 * In both cases, however, we keep our figurative eye out for the
1960 * 'noPrint' line for the shell from which the output came. If
1961 * we recognize a line, we don't print it. If the command is not
1962 * alone on the line (the character after it is not \0 or \n), we
1963 * do print whatever follows it.
1964 *
984263bc
MD
1965 * Side Effects:
1966 * curPos may be shifted as may the contents of outBuf.
984263bc 1967 */
9de1d47a 1968static void
84de9e23 1969JobDoOutput(Job *job, Boolean finish)
984263bc 1970{
df64c352
MO
1971 Boolean gotNL = FALSE; /* true if got a newline */
1972 Boolean fbuf; /* true if our buffer filled up */
1973 int nr; /* number of bytes read */
1974 int i; /* auxiliary index into outBuf */
1975 int max; /* limit for i (end of current data) */
1976 int nRead; /* (Temporary) number of bytes read */
1977 FILE *oFILE; /* Stream pointer to shell's output file */
1978 char inLine[132];
984263bc 1979
df64c352 1980 if (usePipes) {
984263bc 1981 /*
df64c352 1982 * Read as many bytes as will fit in the buffer.
984263bc 1983 */
df64c352
MO
1984 end_loop:
1985 gotNL = FALSE;
1986 fbuf = FALSE;
984263bc 1987
df64c352
MO
1988 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1989 JOB_BUFSIZE - job->curPos);
984263bc 1990 /*
df64c352
MO
1991 * Check for interrupt here too, because the above read may
1992 * block when the child process is stopped. In this case the
1993 * interrupt will unblock it (we don't use SA_RESTART).
984263bc 1994 */
df64c352
MO
1995 if (interrupted)
1996 JobPassSig(interrupted);
1997
1998 if (nRead < 0) {
1999 DEBUGF(JOB, ("JobDoOutput(piperead)"));
2000 nr = 0;
2001 } else {
2002 nr = nRead;
2003 }
984263bc
MD
2004
2005 /*
df64c352
MO
2006 * If we hit the end-of-file (the job is dead), we must flush
2007 * its remaining output, so pretend we read a newline if
2008 * there's any output remaining in the buffer.
2009 * Also clear the 'finish' flag so we stop looping.
984263bc 2010 */
9de1d47a 2011 if (nr == 0 && job->curPos != 0) {
df64c352
MO
2012 job->outBuf[job->curPos] = '\n';
2013 nr = 1;
2014 finish = FALSE;
2015 } else if (nr == 0) {
2016 finish = FALSE;
984263bc 2017 }
984263bc 2018
984263bc 2019 /*
df64c352
MO
2020 * Look for the last newline in the bytes we just got. If there
2021 * is one, break out of the loop with 'i' as its index and
2022 * gotNL set TRUE.
2023 */
2024 max = job->curPos + nr;
2025 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
2026 if (job->outBuf[i] == '\n') {
2027 gotNL = TRUE;
2028 break;
2029 } else if (job->outBuf[i] == '\0') {
2030 /*
2031 * Why?
2032 */
2033 job->outBuf[i] = ' ';
2034 }
2035 }
2036
2037 if (!gotNL) {
2038 job->curPos += nr;
2039 if (job->curPos == JOB_BUFSIZE) {
2040 /*
2041 * If we've run out of buffer space, we have
2042 * no choice but to print the stuff. sigh.
2043 */
2044 fbuf = TRUE;
2045 i = job->curPos;
2046 }
2047 }
2048 if (gotNL || fbuf) {
2049 /*
2050 * Need to send the output to the screen. Null terminate
2051 * it first, overwriting the newline character if there
2052 * was one. So long as the line isn't one we should
2053 * filter (according to the shell description), we print
2054 * the line, preceded by a target banner if this target
2055 * isn't the same as the one for which we last printed
2056 * something. The rest of the data in the buffer are
2057 * then shifted down to the start of the buffer and
2058 * curPos is set accordingly.
2059 */
2060 job->outBuf[i] = '\0';
2061 if (i >= job->curPos) {
2062 char *cp;
2063
2064 cp = JobOutput(job, job->outBuf,
2065 &job->outBuf[i], FALSE);
2066
2067 /*
2068 * There's still more in that buffer. This time,
2069 * though, we know there's no newline at the
2070 * end, so we add one of our own free will.
2071 */
2072 if (*cp != '\0') {
2073 if (job->node != lastNode) {
2074 MESSAGE(stdout, job->node);
2075 lastNode = job->node;
2076 }
2077 fprintf(stdout, "%s%s", cp,
2078 gotNL ? "\n" : "");
2079 fflush(stdout);
2080 }
2081 }
2082 if (i < max - 1) {
2083 /* shift the remaining characters down */
2084 memcpy(job->outBuf, &job->outBuf[i + 1],
2085 max - (i + 1));
2086 job->curPos = max - (i + 1);
2087
2088 } else {
2089 /*
2090 * We have written everything out, so we just
2091 * start over from the start of the buffer.
2092 * No copying. No nothing.
2093 */
2094 job->curPos = 0;
2095 }
2096 }
2097 if (finish) {
2098 /*
2099 * If the finish flag is true, we must loop until we hit
2100 * end-of-file on the pipe. This is guaranteed to happen
2101 * eventually since the other end of the pipe is now
2102 * closed (we closed it explicitly and the child has
2103 * exited). When we do get an EOF, finish will be set
2104 * FALSE and we'll fall through and out.
2105 */
2106 goto end_loop;
984263bc 2107 }
984263bc 2108
df64c352 2109 } else {
984263bc 2110 /*
df64c352
MO
2111 * We've been called to retrieve the output of the job from the
2112 * temporary file where it's been squirreled away. This consists
2113 * of opening the file, reading the output line by line, being
2114 * sure not to print the noPrint line for the shell we used,
2115 * then close and remove the temporary file. Very simple.
2116 *
2117 * Change to read in blocks and do FindSubString type things
2118 * as for pipes? That would allow for "@echo -n..."
984263bc 2119 */
df64c352
MO
2120 oFILE = fopen(job->outFile, "r");
2121 if (oFILE != NULL) {
2122 fprintf(stdout, "Results of making %s:\n",
2123 job->node->name);
2124 fflush(stdout);
2125
2126 while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2127 char *cp, *endp, *oendp;
2128
2129 cp = inLine;
2130 oendp = endp = inLine + strlen(inLine);
2131 if (endp[-1] == '\n') {
2132 *--endp = '\0';
2133 }
2134 cp = JobOutput(job, inLine, endp, FALSE);
2135
2136 /*
2137 * There's still more in that buffer. This time,
2138 * though, we know there's no newline at the
2139 * end, so we add one of our own free will.
2140 */
2141 fprintf(stdout, "%s", cp);
2142 fflush(stdout);
2143 if (endp != oendp) {
2144 fprintf(stdout, "\n");
2145 fflush(stdout);
2146 }
2147 }
2148 fclose(oFILE);
2149 eunlink(job->outFile);
984263bc 2150 }
984263bc 2151 }
984263bc
MD
2152}
2153
df64c352
MO
2154/**
2155 * Job_CatchChildren
984263bc
MD
2156 * Handle the exit of a child. Called from Make_Make.
2157 *
984263bc
MD
2158 * Side Effects:
2159 * The job descriptor is removed from the list of children.
2160 *
2161 * Notes:
2162 * We do waits, blocking or not, according to the wisdom of our
2163 * caller, until there are no more children to report. For each
2164 * job, call JobFinish to finish things off. This will take care of
2165 * putting jobs on the stoppedJobs queue.
984263bc
MD
2166 */
2167void
84de9e23 2168Job_CatchChildren(Boolean block)
984263bc 2169{
9de1d47a 2170 pid_t pid; /* pid of dead child */
df64c352 2171 Job *job; /* job descriptor for dead child */
df64c352
MO
2172 int status; /* Exit/termination status */
2173
2174 /*
2175 * Don't even bother if we know there's no one around.
2176 */
2177 if (nJobs == 0) {
2178 return;
2179 }
2180
2181 for (;;) {
2182 pid = waitpid((pid_t)-1, &status,
2183 (block ? 0 : WNOHANG) | WUNTRACED);
2184 if (pid <= 0)
0515f7ac 2185 break;
df64c352 2186
9de1d47a
MO
2187 DEBUGF(JOB, ("Process %jd exited or stopped.\n",
2188 (intmax_t)pid));
df64c352 2189
9de1d47a
MO
2190 TAILQ_FOREACH(job, &jobs, link) {
2191 if (job->pid == pid)
df64c352 2192 break;
0515f7ac 2193 }
df64c352 2194
9de1d47a 2195 if (job == NULL) {
df64c352
MO
2196 if (WIFSIGNALED(status) &&
2197 (WTERMSIG(status) == SIGCONT)) {
9de1d47a
MO
2198 TAILQ_FOREACH(job, &jobs, link) {
2199 if (job->pid == pid)
df64c352
MO
2200 break;
2201 }
9de1d47a
MO
2202 if (job == NULL) {
2203 Error("Resumed child (%jd) "
2204 "not in table", (intmax_t)pid);
df64c352
MO
2205 continue;
2206 }
9de1d47a 2207 TAILQ_REMOVE(&stoppedJobs, job, link);
df64c352 2208 } else {
9de1d47a
MO
2209 Error("Child (%jd) not in table?",
2210 (intmax_t)pid);
df64c352
MO
2211 continue;
2212 }
2213 } else {
9de1d47a 2214 TAILQ_REMOVE(&jobs, job, link);
df64c352
MO
2215 nJobs -= 1;
2216 if (fifoFd >= 0 && maxJobs > 1) {
2217 write(fifoFd, "+", 1);
2218 maxJobs--;
2219 if (nJobs >= maxJobs)
2220 jobFull = TRUE;
2221 else
2222 jobFull = FALSE;
2223 } else {
2224 DEBUGF(JOB, ("Job queue is no longer full.\n"));
2225 jobFull = FALSE;
2226 }
984263bc 2227 }
df64c352
MO
2228
2229 JobFinish(job, &status);
2230 }
2231 if (interrupted)
2232 JobPassSig(interrupted);
984263bc
MD
2233}
2234
df64c352
MO
2235/**
2236 * Job_CatchOutput
984263bc
MD
2237 * Catch the output from our children, if we're using
2238 * pipes do so. Otherwise just block time until we get a
fbfaa208 2239 * signal(most likely a SIGCHLD) since there's no point in
984263bc
MD
2240 * just spinning when there's nothing to do and the reaping
2241 * of a child can wait for a while.
2242 *
984263bc
MD
2243 * Side Effects:
2244 * Output is read from pipes if we're piping.
984263bc
MD
2245 */
2246void
b24361c9
MO
2247#ifdef USE_KQUEUE
2248Job_CatchOutput(int flag __unused)
2249#else
aa582f64 2250Job_CatchOutput(int flag)
b24361c9 2251#endif
984263bc 2252{
df64c352 2253 int nfds;
218b5aa1
MD
2254#ifdef USE_KQUEUE
2255#define KEV_SIZE 4
df64c352
MO
2256 struct kevent kev[KEV_SIZE];
2257 int i;
218b5aa1 2258#else
df64c352
MO
2259 struct timeval timeout;
2260 fd_set readfds;
df64c352 2261 Job *job;
218b5aa1 2262#endif
984263bc 2263
df64c352 2264 fflush(stdout);
984263bc 2265
df64c352 2266 if (usePipes) {
218b5aa1 2267#ifdef USE_KQUEUE
df64c352
MO
2268 if ((nfds = kevent(kqfd, NULL, 0, kev, KEV_SIZE, NULL)) == -1) {
2269 if (errno != EINTR)
2270 Punt("kevent: %s", strerror(errno));
2271 if (interrupted)
2272 JobPassSig(interrupted);
2273 } else {
2274 for (i = 0; i < nfds; i++) {
2275 if (kev[i].flags & EV_ERROR) {
2276 warnc(kev[i].data, "kevent");
2277 continue;
2278 }
2279 switch (kev[i].filter) {
2280 case EVFILT_READ:
2281 JobDoOutput(kev[i].udata, FALSE);
2282 break;
2283 case EVFILT_PROC:
2284 /*
2285 * Just wake up and let
2286 * Job_CatchChildren() collect the
2287 * terminated job.
2288 */
2289 break;
2290 }
2291 }
218b5aa1 2292 }
218b5aa1 2293#else
df64c352
MO
2294 readfds = outputs;
2295 timeout.tv_sec = SEL_SEC;
2296 timeout.tv_usec = SEL_USEC;
2297 if (flag && jobFull && fifoFd >= 0)
2298 FD_SET(fifoFd, &readfds);
2299
2300 nfds = select(FD_SETSIZE, &readfds, (fd_set *)NULL,
2301 (fd_set *)NULL, &timeout);
2302 if (nfds <= 0) {
2303 if (interrupted)
2304 JobPassSig(interrupted);
2305 return;
2306 }
2307 if (fifoFd >= 0 && FD_ISSET(fifoFd, &readfds)) {
2308 if (--nfds <= 0)
2309 return;
2310 }
9de1d47a
MO
2311 job = TAILQ_FIRST(&jobs);
2312 while (nfds != 0 && job != NULL) {
df64c352
MO
2313 if (FD_ISSET(job->inPipe, &readfds)) {
2314 JobDoOutput(job, FALSE);
9de1d47a 2315 nfds--;
df64c352 2316 }
9de1d47a 2317 job = TAILQ_NEXT(job, link);
df64c352 2318 }
218b5aa1 2319#endif /* !USE_KQUEUE */
df64c352 2320 }
984263bc
MD
2321}
2322
df64c352
MO
2323/**
2324 * Job_Make
984263bc
MD
2325 * Start the creation of a target. Basically a front-end for
2326 * JobStart used by the Make module.
2327 *
984263bc
MD
2328 * Side Effects:
2329 * Another job is started.
984263bc
MD
2330 */
2331void
84de9e23 2332Job_Make(GNode *gn)
984263bc 2333{
fbfaa208 2334
df64c352 2335 JobStart(gn, 0, NULL);
984263bc
MD
2336}
2337
df64c352
MO
2338/**
2339 * Job_Init
a34ec481 2340 * Initialize the process module, given a maximum number of jobs.
984263bc 2341 *
984263bc
MD
2342 * Side Effects:
2343 * lists and counters are initialized
984263bc
MD
2344 */
2345void
a34ec481 2346Job_Init(int maxproc)
984263bc 2347{
df64c352
MO
2348 GNode *begin; /* node for commands to do at the very start */
2349 const char *env;
2350 struct sigaction sa;
984263bc 2351
df64c352
MO
2352 fifoFd = -1;
2353 env = getenv("MAKE_JOBS_FIFO");
aa582f64 2354
df64c352
MO
2355 if (env == NULL && maxproc > 1) {
2356 /*
2357 * We did not find the environment variable so we are the
2358 * leader. Create the fifo, open it, write one char per
2359 * allowed job into the pipe.
2360 */
140bd23a
MO
2361 fifoFd = mkfifotemp(fifoName);
2362 if (fifoFd < 0) {
2363 env = NULL;
2364 } else {
2365 fifoMaster = 1;
2366 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2367 env = fifoName;
2368 setenv("MAKE_JOBS_FIFO", env, 1);
2369 while (maxproc-- > 0) {
2370 write(fifoFd, "+", 1);
df64c352 2371 }
140bd23a
MO
2372 /* The master make does not get a magic token */
2373 jobFull = TRUE;
2374 maxJobs = 0;
aa582f64 2375 }
df64c352
MO
2376
2377 } else if (env != NULL) {
2378 /*
2379 * We had the environment variable so we are a slave.
2380 * Open fifo and give ourselves a magic token which represents
2381 * the token our parent make has grabbed to start his make
2382 * process. Otherwise the sub-makes would gobble up tokens and
2383 * the proper number of tokens to specify to -j would depend
2384 * on the depth of the tree and the order of execution.
2385 */
2386 fifoFd = open(env, O_RDWR, 0);
2387 if (fifoFd >= 0) {
2388 fcntl(fifoFd, F_SETFL, O_NONBLOCK);
2389 maxJobs = 1;
2390 jobFull = FALSE;
2391 }
2392 }
2393 if (fifoFd <= 0) {
2394 maxJobs = maxproc;
2395 jobFull = FALSE;
2396 } else {
2397 }
2398 nJobs = 0;
2399
2400 aborting = 0;
2401 errors = 0;
2402
2403 lastNode = NULL;
2404
2405 if ((maxJobs == 1 && fifoFd < 0) || beVerbose == 0) {
2406 /*
2407 * If only one job can run at a time, there's no need for a
2408 * banner, no is there?
2409 */
2410 targFmt = "";
2411 } else {
2412 targFmt = TARG_FMT;
aa582f64 2413 }
984263bc 2414
df64c352
MO
2415 /*
2416 * Catch the four signals that POSIX specifies if they aren't ignored.
2417 * JobCatchSignal will just set global variables and hope someone
2418 * else is going to handle the interrupt.
2419 */
2420 sa.sa_handler = JobCatchSig;
2421 sigemptyset(&sa.sa_mask);
2422 sa.sa_flags = 0;
984263bc 2423
df64c352
MO
2424 if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
2425 sigaction(SIGINT, &sa, NULL);
2426 }
2427 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
2428 sigaction(SIGHUP, &sa, NULL);
2429 }
2430 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
2431 sigaction(SIGQUIT, &sa, NULL);
2432 }
2433 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
2434 sigaction(SIGTERM, &sa, NULL);
2435 }
984263bc 2436 /*
df64c352
MO
2437 * There are additional signals that need to be caught and passed if
2438 * either the export system wants to be told directly of signals or if
2439 * we're giving each job its own process group (since then it won't get
2440 * signals from the terminal driver as we own the terminal)
984263bc 2441 */
a34ec481 2442#if defined(USE_PGRP)
df64c352
MO
2443 if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
2444 sigaction(SIGTSTP, &sa, NULL);
2445 }
2446 if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
2447 sigaction(SIGTTOU, &sa, NULL);
2448 }
2449 if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
2450 sigaction(SIGTTIN, &sa, NULL);
2451 }
2452 if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
2453 sigaction(SIGWINCH, &sa, NULL);
2454 }
984263bc
MD
2455#endif
2456
218b5aa1 2457#ifdef USE_KQUEUE
df64c352
MO
2458 if ((kqfd = kqueue()) == -1) {
2459 Punt("kqueue: %s", strerror(errno));
2460 }
218b5aa1
MD
2461#endif
2462
df64c352 2463 begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
984263bc 2464
df64c352
MO
2465 if (begin != NULL) {
2466 JobStart(begin, JOB_SPECIAL, (Job *)NULL);
2467 while (nJobs) {
2468 Job_CatchOutput(0);
2469 Job_CatchChildren(!usePipes);
2470 }
984263bc 2471 }
df64c352 2472 postCommands = Targ_FindNode(".END", TARG_CREATE);
984263bc
MD
2473}
2474
df64c352
MO
2475/**
2476 * Job_Full
984263bc
MD
2477 * See if the job table is full. It is considered full if it is OR
2478 * if we are in the process of aborting OR if we have
2479 * reached/exceeded our local quota. This prevents any more jobs
2480 * from starting up.
2481 *
2482 * Results:
2483 * TRUE if the job table is full, FALSE otherwise
984263bc
MD
2484 */
2485Boolean
84de9e23 2486Job_Full(void)
984263bc 2487{
df64c352
MO
2488 char c;
2489 int i;
2490
2491 if (aborting)
2492 return (aborting);
2493 if (fifoFd >= 0 && jobFull) {
2494 i = read(fifoFd, &c, 1);
2495 if (i > 0) {
2496 maxJobs++;
2497 jobFull = FALSE;
2498 }
2499 }
2500 return (jobFull);
984263bc
MD
2501}
2502
df64c352
MO
2503/**
2504 * Job_Empty
984263bc
MD
2505 * See if the job table is empty. Because the local concurrency may
2506 * be set to 0, it is possible for the job table to become empty,
2507 * while the list of stoppedJobs remains non-empty. In such a case,
2508 * we want to restart as many jobs as we can.
2509 *
2510 * Results:
2511 * TRUE if it is. FALSE if it ain't.
984263bc
MD
2512 */
2513Boolean
84de9e23 2514Job_Empty(void)
984263bc 2515{
df64c352 2516 if (nJobs == 0) {
9de1d47a 2517 if (!TAILQ_EMPTY(&stoppedJobs) && !aborting) {
df64c352
MO
2518 /*
2519 * The job table is obviously not full if it has no
2520 * jobs in it...Try and restart the stopped jobs.
2521 */
2522 jobFull = FALSE;
2523 JobRestartJobs();
2524 return (FALSE);
2525 } else {
2526 return (TRUE);
2527 }
984263bc 2528 } else {
df64c352 2529 return (FALSE);
984263bc 2530 }
984263bc
MD
2531}
2532
df64c352
MO
2533/**
2534 * JobInterrupt
984263bc
MD
2535 * Handle the receipt of an interrupt.
2536 *
984263bc
MD
2537 * Side Effects:
2538 * All children are killed. Another job will be started if the
2539 * .INTERRUPT target was given.
984263bc
MD
2540 */
2541static void
84de9e23 2542JobInterrupt(int runINTERRUPT, int signo)
984263bc 2543{
df64c352
MO
2544 Job *job; /* job descriptor in that element */
2545 GNode *interrupt; /* the node describing the .INTERRUPT target */
984263bc 2546
df64c352 2547 aborting = ABORT_INTERRUPT;
984263bc 2548
9de1d47a 2549 TAILQ_FOREACH(job, &jobs, link) {
df64c352
MO
2550 if (!Targ_Precious(job->node)) {
2551 char *file = (job->node->path == NULL ?
2552 job->node->name : job->node->path);
2553
2554 if (!noExecute && eunlink(file) != -1) {
2555 Error("*** %s removed", file);
2556 }
2557 }
2558 if (job->pid) {
2559 DEBUGF(JOB, ("JobInterrupt passing signal to child "
9de1d47a 2560 "%jd.\n", (intmax_t)job->pid));
df64c352
MO
2561 KILL(job->pid, signo);
2562 }
984263bc 2563 }
984263bc 2564
df64c352
MO
2565 if (runINTERRUPT && !touchFlag) {
2566 /*
2567 * clear the interrupted flag because we would get an
2568 * infinite loop otherwise.
2569 */
2570 interrupted = 0;
89a1b397 2571
df64c352
MO
2572 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2573 if (interrupt != NULL) {
2574 ignoreErrors = FALSE;
984263bc 2575
df64c352
MO
2576 JobStart(interrupt, JOB_IGNDOTS, (Job *)NULL);
2577 while (nJobs) {
2578 Job_CatchOutput(0);
2579 Job_CatchChildren(!usePipes);
2580 }
2581 }
984263bc 2582 }
984263bc
MD
2583}
2584
df64c352
MO
2585/**
2586 * Job_Finish
984263bc
MD
2587 * Do final processing such as the running of the commands
2588 * attached to the .END target.
2589 *
2590 * Results:
2591 * Number of errors reported.
984263bc
MD
2592 */
2593int
84de9e23 2594Job_Finish(void)
984263bc 2595{
fbfaa208 2596
df64c352
MO
2597 if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
2598 if (errors) {
2599 Error("Errors reported so .END ignored");
2600 } else {
2601 JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
984263bc 2602
df64c352
MO
2603 while (nJobs) {
2604 Job_CatchOutput(0);
2605 Job_CatchChildren(!usePipes);
2606 }
2607 }
984263bc 2608 }
df64c352
MO
2609 if (fifoFd >= 0) {
2610 close(fifoFd);
2611 fifoFd = -1;
2612 if (fifoMaster)
2613 unlink(fifoName);
2614 }
2615 return (errors);
984263bc
MD
2616}
2617
df64c352
MO
2618/**
2619 * Job_Wait
984263bc
MD
2620 * Waits for all running jobs to finish and returns. Sets 'aborting'
2621 * to ABORT_WAIT to prevent other jobs from starting.
2622 *
984263bc
MD
2623 * Side Effects:
2624 * Currently running jobs finish.
984263bc
MD
2625 */
2626void
84de9e23 2627Job_Wait(void)
984263bc 2628{
fbfaa208 2629
df64c352
MO
2630 aborting = ABORT_WAIT;
2631 while (nJobs != 0) {
2632 Job_CatchOutput(0);
2633 Job_CatchChildren(!usePipes);
2634 }
2635 aborting = 0;
984263bc
MD
2636}
2637
df64c352
MO
2638/**
2639 * Job_AbortAll
984263bc
MD
2640 * Abort all currently running jobs without handling output or anything.
2641 * This function is to be called only in the event of a major
2642 * error. Most definitely NOT to be called from JobInterrupt.
2643 *
984263bc
MD
2644 * Side Effects:
2645 * All children are killed, not just the firstborn
984263bc
MD
2646 */
2647void
84de9e23 2648Job_AbortAll(void)
984263bc 2649{
df64c352 2650 Job *job; /* the job descriptor in that element */
90b7ba34 2651 int status;
984263bc 2652
df64c352 2653 aborting = ABORT_ERROR;
984263bc 2654
df64c352 2655 if (nJobs) {
9de1d47a 2656 TAILQ_FOREACH(job, &jobs, link) {
df64c352
MO
2657 /*
2658 * kill the child process with increasingly drastic
2659 * signals to make darn sure it's dead.
2660 */
2661 KILL(job->pid, SIGINT);
2662 KILL(job->pid, SIGKILL);
2663 }
2664 }
2665
2666 /*
2667 * Catch as many children as want to report in at first, then give up
2668 */
90b7ba34 2669 while (waitpid((pid_t)-1, &status, WNOHANG) > 0)
9de1d47a 2670 ;
984263bc
MD
2671}
2672
df64c352
MO
2673/**
2674 * JobRestartJobs
984263bc
MD
2675 * Tries to restart stopped jobs if there are slots available.
2676 * Note that this tries to restart them regardless of pending errors.
2677 * It's not good to leave stopped jobs lying around!
2678 *
984263bc
MD
2679 * Side Effects:
2680 * Resumes(and possibly migrates) jobs.
984263bc
MD
2681 */
2682static void
84de9e23 2683JobRestartJobs(void)
984263bc 2684{
9de1d47a
MO
2685 Job *job;
2686
2687 while (!jobFull && (job = TAILQ_FIRST(&stoppedJobs)) != NULL) {
df64c352
MO
2688 DEBUGF(JOB, ("Job queue is not full. "
2689 "Restarting a stopped job.\n"));
9de1d47a
MO
2690 TAILQ_REMOVE(&stoppedJobs, job, link);
2691 JobRestart(job);
df64c352 2692 }
984263bc 2693}
69572075
MO
2694
2695/**
2696 * Cmd_Exec
2697 * Execute the command in cmd, and return the output of that command
2698 * in a string.
2699 *
2700 * Results:
2701 * A string containing the output of the command, or the empty string
2702 * If error is not NULL, it contains the reason for the command failure
b582d309
MO
2703 * Any output sent to stderr in the child process is passed to stderr,
2704 * and not captured in the string.
69572075
MO
2705 *
2706 * Side Effects:
2707 * The string must be freed by the caller.
2708 */
2709Buffer *
2710Cmd_Exec(const char *cmd, const char **error)
2711{
2712 int fds[2]; /* Pipe streams */
69572075
MO
2713 int status; /* command exit status */
2714 Buffer *buf; /* buffer to store the result */
2715 ssize_t rcnt;
8a538fd1 2716 ProcStuff ps;
69572075
MO
2717
2718 *error = NULL;
2719 buf = Buf_Init(0);
2720
69572075
MO
2721 /*
2722 * Open a pipe for fetching its output
2723 */
2724 if (pipe(fds) == -1) {
2725 *error = "Couldn't create pipe for \"%s\"";
2726 return (buf);
2727 }
2728
69e43d67
MO
2729 /* Set close-on-exec on read side of pipe. */
2730 fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC);
2731
3e10c271
MO
2732 ps.in = STDIN_FILENO;
2733 ps.out = fds[1];
2734 ps.err = STDERR_FILENO;
2735
2736 ps.merge_errors = 0;
2737 ps.pgroup = 0;
2738 ps.searchpath = 0;
2739
2740 /* Set up arguments for shell */
7c2a9959 2741 ps.argv = emalloc(4 * sizeof(char *));
880b6521 2742 ps.argv[0] = strdup(commandShell->name);
7c2a9959
MO
2743 ps.argv[1] = strdup("-c");
2744 ps.argv[2] = strdup(cmd);
2745 ps.argv[3] = NULL;
d0a12c98 2746 ps.argv_free = 1;
3e10c271 2747
69572075 2748 /*
7c2a9959
MO
2749 * Fork. Warning since we are doing vfork() instead of fork(),
2750 * do not allocate memory in the child process!
69572075 2751 */
ebf8e7fe 2752 if ((ps.child_pid = vfork()) == -1) {
53a3ba77 2753 *error = "Couldn't exec \"%s\"";
53a3ba77 2754
ebf8e7fe 2755 } else if (ps.child_pid == 0) {
69572075 2756 /*
3e10c271 2757 * Child
69572075 2758 */
8a538fd1 2759 ProcExec(&ps);
257e9734 2760 /* NOTREACHED */
69572075 2761
53a3ba77 2762 } else {
7c2a9959
MO
2763 free(ps.argv[2]);
2764 free(ps.argv[1]);
2765 free(ps.argv[0]);
2766 free(ps.argv);
2767
69e43d67 2768 close(fds[1]); /* No need for the writing half of the pipe. */
69572075
MO
2769
2770 do {
2771 char result[BUFSIZ];
2772
2773 rcnt = read(fds[0], result, sizeof(result));
2774 if (rcnt != -1)
2775 Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
2776 } while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
2777
2778 if (rcnt == -1)
2779 *error = "Error reading shell's output for \"%s\"";
2780
2781 /*
2782 * Close the input side of the pipe.
2783 */
2784 close(fds[0]);
2785
ebf8e7fe 2786 status = ProcWait(&ps);
69572075
MO
2787 if (status)
2788 *error = "\"%s\" returned non-zero status";
2789
2790 Buf_StripNewlines(buf);
2791
69572075 2792 }
30bb92cf 2793 return (buf);
69572075
MO
2794}
2795
5f530f85
MO
2796/*
2797 * Interrupt handler - set flag and defer handling to the main code
2798 */
2799static void
2800CompatCatchSig(int signo)
2801{
2802
2803 interrupted = signo;
2804}
2805
90b7ba34
MO
2806/**
2807 * CompatInterrupt
5f530f85
MO
2808 * Interrupt the creation of the current target and remove it if
2809 * it ain't precious.
2810 *
2811 * Results:
2812 * None.
2813 *
2814 * Side Effects:
2815 * The target is removed and the process exits. If .INTERRUPT exists,
2816 * its commands are run first WITH INTERRUPTS IGNORED..
5f530f85
MO
2817 */
2818static void
2819CompatInterrupt(int signo)
2820{
2821 GNode *gn;
2822 sigset_t nmask, omask;
2823 LstNode *ln;
2824
2825 sigemptyset(&nmask);
2826 sigaddset(&nmask, SIGINT);
2827 sigaddset(&nmask, SIGTERM);
2828 sigaddset(&nmask, SIGHUP);
2829 sigaddset(&nmask, SIGQUIT);
2830 sigprocmask(SIG_SETMASK, &nmask, &omask);
2831
2832 /* prevent recursion in evaluation of .INTERRUPT */
2833 interrupted = 0;
2834
2835 if (curTarg != NULL && !Targ_Precious(curTarg)) {
10d0fb4c 2836 const char *file = Var_Value(TARGET, curTarg);
5f530f85
MO
2837
2838 if (!noExecute && eunlink(file) != -1) {
2839 printf("*** %s removed\n", file);
2840 }
5f530f85
MO
2841 }
2842
2843 /*
2844 * Run .INTERRUPT only if hit with interrupt signal
2845 */
2846 if (signo == SIGINT) {
2847 gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2848 if (gn != NULL) {
2849 LST_FOREACH(ln, &gn->commands) {
2850 if (Compat_RunCommand(Lst_Datum(ln), gn))
2851 break;
2852 }
2853 }
2854 }
2855
2856 sigprocmask(SIG_SETMASK, &omask, NULL);
2857
2858 if (signo == SIGQUIT)
2859 exit(signo);
2860 signal(signo, SIG_DFL);
2861 kill(getpid(), signo);
2862}
2863
90b7ba34
MO
2864/**
2865 * Compat_RunCommand
5f530f85
MO
2866 * Execute the next command for a target. If the command returns an
2867 * error, the node's made field is set to ERROR and creation stops.
2868 * The node from which the command came is also given.
2869 *
2870 * Results:
2871 * 0 if the command succeeded, 1 if an error occurred.
2872 *
2873 * Side Effects:
2874 * The node's 'made' field may be set to ERROR.
5f530f85 2875 */
53e478a3 2876static int
5f530f85
MO
2877Compat_RunCommand(char *cmd, GNode *gn)
2878{
db647c9e
MO
2879 ArgArray aa;
2880 char *cmdStart; /* Start of expanded command */
db647c9e
MO
2881 Boolean silent; /* Don't print command */
2882 Boolean doit; /* Execute even in -n */
2883 Boolean errCheck; /* Check errors */
2884 int reason; /* Reason for child's death */
2885 int status; /* Description of child's death */
2886 LstNode *cmdNode; /* Node where current cmd is located */
2887 char **av; /* Argument vector for thing to exec */
8a538fd1 2888 ProcStuff ps;
5f530f85 2889
5f530f85
MO
2890 silent = gn->type & OP_SILENT;
2891 errCheck = !(gn->type & OP_IGNORE);
2892 doit = FALSE;
2893
2894 cmdNode = Lst_Member(&gn->commands, cmd);
2895 cmdStart = Buf_Peel(Var_Subst(cmd, gn, FALSE));
2896
5f530f85
MO
2897 if (*cmdStart == '\0') {
2898 free(cmdStart);
2899 Error("%s expands to empty string", cmd);
2900 return (0);
2901 } else {
2902 cmd = cmdStart;
2903 }
2904 Lst_Replace(cmdNode, cmdStart);
2905
2906 if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
2907 Lst_AtEnd(&ENDNode->commands, cmdStart);
2908 return (0);
2909 } else if (strcmp(cmdStart, "...") == 0) {
2910 gn->type |= OP_SAVE_CMDS;
2911 return (0);
2912 }
2913
2914 while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
2915 switch (*cmd) {
2916
2917 case '@':
2918 silent = DEBUG(LOUD) ? FALSE : TRUE;
2919 break;
2920
2921 case '-':
2922 errCheck = FALSE;
2923 break;
2924
2925 case '+':
2926 doit = TRUE;
5f530f85
MO
2927 break;
2928 }
2929 cmd++;
2930 }
2931
2932 while (isspace((unsigned char)*cmd))
2933 cmd++;
2934
5f530f85
MO
2935 /*
2936 * Print the command before echoing if we're not supposed to be quiet
2937 * for this one. We also print the command if -n given, but not if '+'.
2938 */
2939 if (!silent || (noExecute && !doit)) {
2940 printf("%s\n", cmd);
2941 fflush(stdout);
2942 }
2943
2944 /*
2945 * If we're not supposed to execute any commands, this is as far as
2946 * we go...
2947 */
2948 if (!doit && noExecute) {
2949 return (0);
2950 }
2951
9b39b389 2952 if (strpbrk(cmd, "#=|^(){};&<>*?[]:$`\\\n")) {
5f530f85 2953 /*
9b39b389
MO
2954 * We found a "meta" character and need to pass the command
2955 * off to the shell.
5f530f85 2956 */
7c2a9959 2957 av = NULL;
5f530f85
MO
2958
2959 } else {
47d26f55
MO
2960 const char **p;
2961 const char *sh_builtin[] = {
2962 "alias", "cd", "eval", "exec",
2963 "exit", "read", "set", "ulimit",
2964 "unalias", "umask", "unset", "wait",
2965 ":", NULL
2966 };
2967
5f530f85 2968 /*
47d26f55 2969 * Break the command into words to form an argument
db647c9e 2970 * vector we can execute.
5f530f85 2971 */
db647c9e
MO
2972 brk_string(&aa, cmd, TRUE);
2973 av = aa.argv + 1;
47d26f55
MO
2974
2975 for (p = sh_builtin; *p != 0; p++) {
2976 if (strcmp(av[0], *p) == 0) {
2977 /*
2978 * This command must be passed by the shell
2979 * for other reasons.. or.. possibly not at
2980 * all.
2981 */
2982 av = NULL;
2983 break;
2984 }
2985 }
5f530f85
MO
2986 }
2987
3e10c271
MO
2988 ps.in = STDIN_FILENO;
2989 ps.out = STDOUT_FILENO;
2990 ps.err = STDERR_FILENO;
2991
2992 ps.merge_errors = 0;
2993 ps.pgroup = 0;
2994 ps.searchpath = 1;
2995
7c2a9959 2996 if (av == NULL) {
47d26f55
MO
2997 /*
2998 * We give the shell the -e flag as well as -c if it's
2999 * supposed to exit when it hits an error.
3000 */
7c2a9959 3001 ps.argv = emalloc(4 * sizeof(char *));
b34dfd7e 3002 ps.argv[0] = strdup(commandShell->path);
7c2a9959
MO
3003 ps.argv[1] = strdup(errCheck ? "-ec" : "-c");
3004 ps.argv[2] = strdup(cmd);
3005 ps.argv[3] = NULL;
d0a12c98 3006 ps.argv_free = 1;
7c2a9959
MO
3007 } else {
3008 ps.argv = av;
d0a12c98 3009 ps.argv_free = 0;
7c2a9959 3010 }
d0a12c98 3011 ps.errCheck = errCheck;
3e10c271 3012
5f530f85
MO
3013 /*
3014 * Fork and execute the single command. If the fork fails, we abort.
7c2a9959
MO
3015 * Warning since we are doing vfork() instead of fork(),
3016 * do not allocate memory in the child process!
5f530f85 3017 */
ebf8e7fe 3018 if ((ps.child_pid = vfork()) == -1) {
5f530f85 3019 Fatal("Could not fork");
53a3ba77 3020
ebf8e7fe 3021 } else if (ps.child_pid == 0) {
3e10c271
MO
3022 /*
3023 * Child
3024 */
8a538fd1 3025 ProcExec(&ps);
30bb92cf
MO
3026 /* NOTREACHED */
3027
53a3ba77 3028 } else {
d0a12c98 3029 if (ps.argv_free) {
7c2a9959
MO
3030 free(ps.argv[2]);
3031 free(ps.argv[1]);
3032 free(ps.argv[0]);
3033 free(ps.argv);
db647c9e
MO
3034 } else {
3035 ArgArray_Done(&aa);
7c2a9959
MO
3036 }
3037
53a3ba77
MO
3038 /*
3039 * we need to print out the command associated with this
3040 * Gnode in Targ_PrintCmd from Targ_PrintGraph when debugging
3041 * at level g2, in main(), Fatal() and DieHorribly(),
3042 * therefore do not free it when debugging.
3043 */
3044 if (!DEBUG(GRAPH2)) {
3045 free(cmdStart);
5f530f85 3046 }
69e43d67 3047
53a3ba77
MO
3048 /*
3049 * The child is off and running. Now all we can do is wait...
3050 */
6319dcf0 3051 reason = ProcWait(&ps);
29004ef5 3052
6319dcf0
MO
3053 if (interrupted)
3054 CompatInterrupt(interrupted);
5f530f85 3055
29004ef5 3056 /*
f0e0c7c5 3057 * Decode and report the reason child exited, then
29004ef5
MO
3058 * indicate how we handled it.
3059 */
6319dcf0 3060 if (WIFEXITED(reason)) {
6319dcf0
MO
3061 status = WEXITSTATUS(reason);
3062 if (status == 0) {
3063 return (0);
53a3ba77 3064 } else {
6319dcf0 3065 printf("*** Error code %d", status);
5f530f85 3066 }
6319dcf0
MO
3067 } else if (WIFSTOPPED(reason)) {
3068 status = WSTOPSIG(reason);
3069 } else {
3070 status = WTERMSIG(reason);
3071 printf("*** Signal %d", status);
5f530f85 3072 }
5f530f85 3073
d0a12c98 3074 if (ps.errCheck) {
6319dcf0
MO
3075 gn->made = ERROR;
3076 if (keepgoing) {
3077 /*
3078 * Abort the current
3079 * target, but let
3080 * others continue.
3081 */
3082 printf(" (continuing)\n");
3083 }
3084 return (status);
3085 } else {
3086 /*
3087 * Continue executing
3088 * commands for this target.
3089 * If we return 0, this will
3090 * happen...
3091 */
3092 printf(" (ignored)\n");
3093 return (0);
3094 }
53a3ba77 3095 }
5f530f85
MO
3096}
3097
90b7ba34
MO
3098/**
3099 * CompatMake
5f530f85
MO
3100 * Make a target, given the parent, to abort if necessary.
3101 *
3102 * Side Effects:
3103 * If an error is detected and not being ignored, the process exits.
5f530f85
MO
3104 */
3105static int
3106CompatMake(GNode *gn, GNode *pgn)
3107{
3108 LstNode *ln;
3109
3110 if (gn->type & OP_USE) {
3111 Make_HandleUse(gn, pgn);
3112
3113 } else if (gn->made == UNMADE) {
3114 /*
3115 * First mark ourselves to be made, then apply whatever
3116 * transformations the suffix module thinks are necessary.
3117 * Once that's done, we can descend and make all our children.
3118 * If any of them has an error but the -k flag was given, our
3119 * 'make' field will be set FALSE again. This is our signal to
3120 * not attempt to do anything but abort our parent as well.
3121 */
3122 gn->make = TRUE;
3123 gn->made = BEINGMADE;
3124 Suff_FindDeps(gn);
3125 LST_FOREACH(ln, &gn->children)
3126 CompatMake(Lst_Datum(ln), gn);
3127 if (!gn->make) {
3128 gn->made = ABORTED;
3129 pgn->make = FALSE;
3130 return (0);
3131 }
3132
3133 if (Lst_Member(&gn->iParents, pgn) != NULL) {
a2e49af9 3134 Var_Set(IMPSRC, Var_Value(TARGET, gn), pgn);
5f530f85
MO
3135 }
3136
3137 /*
3138 * All the children were made ok. Now cmtime contains the
3139 * modification time of the newest child, we need to find out
3140 * if we exist and when we were modified last. The criteria for
3141 * datedness are defined by the Make_OODate function.
3142 */
3143 DEBUGF(MAKE, ("Examining %s...", gn->name));
3144 if (!Make_OODate(gn)) {
3145 gn->made = UPTODATE;
3146 DEBUGF(MAKE, ("up-to-date.\n"));
3147 return (0);
3148 } else {
3149 DEBUGF(MAKE, ("out-of-date.\n"));
3150 }
3151
3152 /*
3153 * If the user is just seeing if something is out-of-date,
3154 * exit now to tell him/her "yes".
3155 */
3156 if (queryFlag) {
3157 exit(1);
3158 }
3159
3160 /*
3161 * We need to be re-made. We also have to make sure we've got
3162 * a $? variable. To be nice, we also define the $> variable
3163 * using Make_DoAllVar().
3164 */
3165 Make_DoAllVar(gn);
3166
3167 /*
3168 * Alter our type to tell if errors should be ignored or things
3169 * should not be printed so Compat_RunCommand knows what to do.
3170 */
3171 if (Targ_Ignore(gn)) {
3172 gn->type |= OP_IGNORE;
3173 }
3174 if (Targ_Silent(gn)) {
3175 gn->type |= OP_SILENT;
3176 }
3177
3178 if (Job_CheckCommands(gn, Fatal)) {
3179 /*
3180 * Our commands are ok, but we still have to worry
3181 * about the -t flag...
3182 */
3183 if (!touchFlag) {
3184 curTarg = gn;
3185 LST_FOREACH(ln, &gn->commands) {
3186 if (Compat_RunCommand(Lst_Datum(ln),
3187 gn))
3188 break;
3189 }
3190 curTarg = NULL;
3191 } else {
3192 Job_Touch(gn, gn->type & OP_SILENT);
3193 }
3194 } else {
3195 gn->made = ERROR;
3196 }
3197
3198 if (gn->made != ERROR) {
3199 /*
3200 * If the node was made successfully, mark it so, update
3201 * its modification time and timestamp all its parents.
3202 * Note that for .ZEROTIME targets, the timestamping
3203 * isn't done. This is to keep its state from affecting
3204 * that of its parent.
3205 */
3206 gn->made = MADE;
3207#ifndef RECHECK
3208 /*
3209 * We can't re-stat the thing, but we can at least take
3210 * care of rules where a target depends on a source that
3211 * actually creates the target, but only if it has
3212 * changed, e.g.
3213 *
3214 * parse.h : parse.o
3215 *
3216 * parse.o : parse.y
b04c4147
MO
3217 * yacc -d parse.y
3218 * cc -c y.tab.c
3219 * mv y.tab.o parse.o
3220 * cmp -s y.tab.h parse.h || mv y.tab.h parse.h
5f530f85
MO
3221 *
3222 * In this case, if the definitions produced by yacc
3223 * haven't changed from before, parse.h won't have been
3224 * updated and gn->mtime will reflect the current
3225 * modification time for parse.h. This is something of a
3226 * kludge, I admit, but it's a useful one..
3227 *
3228 * XXX: People like to use a rule like
3229 *
3230 * FRC:
3231 *
3232 * To force things that depend on FRC to be made, so we
3233 * have to check for gn->children being empty as well...
3234 */
3235 if (!Lst_IsEmpty(&gn->commands) ||
3236 Lst_IsEmpty(&gn->children)) {
3237 gn->mtime = now;
3238 }
3239#else
3240 /*
3241 * This is what Make does and it's actually a good
3242 * thing, as it allows rules like
3243 *
3244 * cmp -s y.tab.h parse.h || cp y.tab.h parse.h
3245 *
3246 * to function as intended. Unfortunately, thanks to
3247 * the stateless nature of NFS (and the speed of this
3248 * program), there are times when the modification time
3249 * of a file created on a remote machine will not be
3250 * modified before the stat() implied by the Dir_MTime
3251 * occurs, thus leading us to believe that the file
3252 * is unchanged, wreaking havoc with files that depend
3253 * on this one.
3254 *
3255 * I have decided it is better to make too much than to
3256 * make too little, so this stuff is commented out
3257 * unless you're sure it's ok.
3258 * -- ardeb 1/12/88
3259 */
3260 if (noExecute || Dir_MTime(gn) == 0) {
3261 gn->mtime = now;
3262 }
3263 if (gn->cmtime > gn->mtime)
3264 gn->mtime = gn->cmtime;
3265 DEBUGF(MAKE, ("update time: %s\n",
3266 Targ_FmtTime(gn->mtime)));
3267#endif
3268 if (!(gn->type & OP_EXEC)) {
3269 pgn->childMade = TRUE;
3270 Make_TimeStamp(pgn, gn);
3271 }
3272
3273 } else if (keepgoing) {
3274 pgn->make = FALSE;
3275
3276 } else {
a2e49af9 3277 printf("\n\nStop in %s.\n", Var_Value(".CURDIR", gn));
5f530f85
MO
3278 exit(1);
3279 }
3280 } else if (gn->made == ERROR) {
3281 /*
3282 * Already had an error when making this beastie. Tell the
3283 * parent to abort.
3284 */
3285 pgn->make = FALSE;
3286 } else {
3287 if (Lst_Member(&gn->iParents, pgn) != NULL) {
a2e49af9 3288 Var_Set(IMPSRC, Var_Value(TARGET, gn), pgn);
5f530f85
MO
3289 }
3290 switch(gn->made) {
3291 case BEINGMADE:
3292 Error("Graph cycles through %s\n", gn->name);
3293 gn->made = ERROR;
3294 pgn->make = FALSE;
3295 break;
3296 case MADE:
3297 if ((gn->type & OP_EXEC) == 0) {
3298 pgn->childMade = TRUE;
3299 Make_TimeStamp(pgn, gn);
3300 }
3301 break;
3302 case UPTODATE:
3303 if ((gn->type & OP_EXEC) == 0) {
3304 Make_TimeStamp(pgn, gn);
3305 }
3306 break;
3307 default:
3308 break;
3309 }
3310 }
3311
3312 return (0);
3313}
3314
90b7ba34
MO
3315/**
3316 * Compat_Run
5f530f85
MO
3317 * Start making again, given a list of target nodes.
3318 *
3319 * Results:
3320 * None.
3321 *
3322 * Side Effects:
3323 * Guess what?
5f530f85
MO
3324 */
3325void
3326Compat_Run(Lst *targs)
3327{
3328 GNode *gn = NULL; /* Current root target */
90b7ba34 3329 int error_cnt; /* Number of targets not remade due to errors */
5f530f85
MO
3330 LstNode *ln;
3331
5f530f85
MO
3332 if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
3333 signal(SIGINT, CompatCatchSig);
3334 }
3335 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
3336 signal(SIGTERM, CompatCatchSig);
3337 }
3338 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
3339 signal(SIGHUP, CompatCatchSig);
3340 }
3341 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
3342 signal(SIGQUIT, CompatCatchSig);
3343 }
3344
3345 ENDNode = Targ_FindNode(".END", TARG_CREATE);
3346 /*
3347 * If the user has defined a .BEGIN target, execute the commands
3348 * attached to it.
3349 */
3350 if (!queryFlag) {
3351 gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
3352 if (gn != NULL) {
3353 LST_FOREACH(ln, &gn->commands) {
3354 if (Compat_RunCommand(Lst_Datum(ln), gn))
3355 break;
3356 }
3357 if (gn->made == ERROR) {
3358 printf("\n\nStop.\n");
3359 exit(1);
3360 }
3361 }
3362 }
3363
3364 /*
3365 * For each entry in the list of targets to create, call CompatMake on
3366 * it to create the thing. CompatMake will leave the 'made' field of gn
3367 * in one of several states:
3368 * UPTODATE gn was already up-to-date
3369 * MADE gn was recreated successfully
3370 * ERROR An error occurred while gn was being created
3371 * ABORTED gn was not remade because one of its inferiors
3372 * could not be made due to errors.
3373 */
3374 error_cnt = 0;
3375 while (!Lst_IsEmpty(targs)) {
3376 gn = Lst_DeQueue(targs);
3377 CompatMake(gn, gn);
3378
3379 if (gn->made == UPTODATE) {
3380 printf("`%s' is up to date.\n", gn->name);
3381 } else if (gn->made == ABORTED) {
3382 printf("`%s' not remade because of errors.\n",
3383 gn->name);
3384 error_cnt += 1;
3385 }
3386 }
3387
3388 /*
3389 * If the user has defined a .END target, run its commands.
3390 */
3391 if (error_cnt == 0) {
3392 LST_FOREACH(ln, &ENDNode->commands) {
3393 if (Compat_RunCommand(Lst_Datum(ln), gn))
3394 break;
3395 }
3396 }
3397}
140bd23a 3398