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