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