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