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