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