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