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