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