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