Home | History | Annotate | Line # | Download | only in make
job.c revision 1.272
      1 /*	$NetBSD: job.c,v 1.272 2020/10/23 15:19:51 rillig Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Adam de Boor.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 /*
     36  * Copyright (c) 1988, 1989 by Adam de Boor
     37  * Copyright (c) 1989 by Berkeley Softworks
     38  * All rights reserved.
     39  *
     40  * This code is derived from software contributed to Berkeley by
     41  * Adam de Boor.
     42  *
     43  * Redistribution and use in source and binary forms, with or without
     44  * modification, are permitted provided that the following conditions
     45  * are met:
     46  * 1. Redistributions of source code must retain the above copyright
     47  *    notice, this list of conditions and the following disclaimer.
     48  * 2. Redistributions in binary form must reproduce the above copyright
     49  *    notice, this list of conditions and the following disclaimer in the
     50  *    documentation and/or other materials provided with the distribution.
     51  * 3. All advertising materials mentioning features or use of this software
     52  *    must display the following acknowledgement:
     53  *	This product includes software developed by the University of
     54  *	California, Berkeley and its contributors.
     55  * 4. Neither the name of the University nor the names of its contributors
     56  *    may be used to endorse or promote products derived from this software
     57  *    without specific prior written permission.
     58  *
     59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     69  * SUCH DAMAGE.
     70  */
     71 
     72 /*-
     73  * job.c --
     74  *	handle the creation etc. of our child processes.
     75  *
     76  * Interface:
     77  *	Job_Make	Start the creation of the given target.
     78  *
     79  *	Job_CatchChildren
     80  *			Check for and handle the termination of any
     81  *			children. This must be called reasonably
     82  *			frequently to keep the whole make going at
     83  *			a decent clip, since job table entries aren't
     84  *			removed until their process is caught this way.
     85  *
     86  *	Job_CatchOutput
     87  *			Print any output our children have produced.
     88  *			Should also be called fairly frequently to
     89  *			keep the user informed of what's going on.
     90  *			If no output is waiting, it will block for
     91  *			a time given by the SEL_* constants, below,
     92  *			or until output is ready.
     93  *
     94  *	Job_Init	Called to initialize this module. in addition,
     95  *			any commands attached to the .BEGIN target
     96  *			are executed before this function returns.
     97  *			Hence, the makefile must have been parsed
     98  *			before this function is called.
     99  *
    100  *	Job_End		Clean up any memory used.
    101  *
    102  *	Job_ParseShell	Given the line following a .SHELL target, parse
    103  *			the line as a shell specification. Returns
    104  *			FALSE if the spec was incorrect.
    105  *
    106  *	Job_Finish	Perform any final processing which needs doing.
    107  *			This includes the execution of any commands
    108  *			which have been/were attached to the .END
    109  *			target. It should only be called when the
    110  *			job table is empty.
    111  *
    112  *	Job_AbortAll	Abort all currently running jobs. It doesn't
    113  *			handle output or do anything for the jobs,
    114  *			just kills them. It should only be called in
    115  *			an emergency, as it were.
    116  *
    117  *	Job_CheckCommands
    118  *			Verify that the commands for a target are
    119  *			ok. Provide them if necessary and possible.
    120  *
    121  *	Job_Touch	Update a target without really updating it.
    122  *
    123  *	Job_Wait	Wait for all currently-running jobs to finish.
    124  */
    125 
    126 #include <sys/types.h>
    127 #include <sys/stat.h>
    128 #include <sys/file.h>
    129 #include <sys/time.h>
    130 #include <sys/wait.h>
    131 
    132 #include <errno.h>
    133 #ifndef USE_SELECT
    134 #include <poll.h>
    135 #endif
    136 #include <signal.h>
    137 #include <utime.h>
    138 
    139 #include "make.h"
    140 #include "dir.h"
    141 #include "job.h"
    142 #include "pathnames.h"
    143 #include "trace.h"
    144 
    145 /*	"@(#)job.c	8.2 (Berkeley) 3/19/94"	*/
    146 MAKE_RCSID("$NetBSD: job.c,v 1.272 2020/10/23 15:19:51 rillig Exp $");
    147 
    148 # define STATIC static
    149 
    150 /*-
    151  * Shell Specifications:
    152  * Each shell type has associated with it the following information:
    153  *	1) The string which must match the last character of the shell name
    154  *	   for the shell to be considered of this type. The longest match
    155  *	   wins.
    156  *	2) A command to issue to turn off echoing of command lines
    157  *	3) A command to issue to turn echoing back on again
    158  *	4) What the shell prints, and its length, when given the echo-off
    159  *	   command. This line will not be printed when received from the shell
    160  *	5) A boolean to tell if the shell has the ability to control
    161  *	   error checking for individual commands.
    162  *	6) The string to turn this checking on.
    163  *	7) The string to turn it off.
    164  *	8) The command-flag to give to cause the shell to start echoing
    165  *	   commands right away.
    166  *	9) The command-flag to cause the shell to Lib_Exit when an error is
    167  *	   detected in one of the commands.
    168  *
    169  * Some special stuff goes on if a shell doesn't have error control. In such
    170  * a case, errCheck becomes a printf template for echoing the command,
    171  * should echoing be on and ignErr becomes another printf template for
    172  * executing the command while ignoring the return status. Finally errOut
    173  * is a printf template for running the command and causing the shell to
    174  * exit on error. If any of these strings are empty when hasErrCtl is FALSE,
    175  * the command will be executed anyway as is and if it causes an error, so be
    176  * it. Any templates setup to echo the command will escape any '$ ` \ "'i
    177  * characters in the command string to avoid common problems with
    178  * echo "%s\n" as a template.
    179  */
    180 typedef struct Shell {
    181 
    182     /* The name of the shell. For Bourne and C shells, this is used only to
    183      * find the shell description when used as the single source of a .SHELL
    184      * target. For user-defined shells, this is the full path of the shell. */
    185     const char *name;
    186 
    187     Boolean hasEchoCtl;		/* True if both echoOff and echoOn defined */
    188     const char *echoOff;	/* command to turn off echo */
    189     const char *echoOn;		/* command to turn it back on again */
    190     const char *noPrint;	/* text to skip when printing output from
    191 				 * shell. This is usually the same as echoOff */
    192     size_t noPrintLen;		/* length of noPrint command */
    193 
    194     Boolean hasErrCtl;		/* set if can control error checking for
    195 				 * individual commands */
    196     const char *errCheck;	/* string to turn on error checking */
    197     const char *ignErr;		/* string to turn off error checking */
    198     const char *errOut;		/* string to use for testing exit code */
    199 
    200     const char *newline;	/* string literal that results in a newline
    201 				 * character when it appears outside of any
    202 				 * 'quote' or "quote" characters */
    203     char commentChar;		/* character used by shell for comment lines */
    204 
    205     /*
    206      * command-line flags
    207      */
    208     const char *echo;		/* echo commands */
    209     const char *exit;		/* exit on error */
    210 } Shell;
    211 
    212 /*
    213  * error handling variables
    214  */
    215 static int errors = 0;		/* number of errors reported */
    216 static int aborting = 0;	/* why is the make aborting? */
    217 #define ABORT_ERROR	1	/* Because of an error */
    218 #define ABORT_INTERRUPT	2	/* Because it was interrupted */
    219 #define ABORT_WAIT	3	/* Waiting for jobs to finish */
    220 #define JOB_TOKENS	"+EI+"	/* Token to requeue for each abort state */
    221 
    222 /*
    223  * this tracks the number of tokens currently "out" to build jobs.
    224  */
    225 int jobTokensRunning = 0;
    226 
    227 /* The number of commands actually printed for a target.
    228  * XXX: Why printed? Shouldn't that be run/printed instead, depending on the
    229  * command line options?
    230  * Should this number be 0, no shell will be executed. */
    231 static int numCommands;
    232 
    233 /*
    234  * Return values from JobStart.
    235  */
    236 #define JOB_RUNNING	0	/* Job is running */
    237 #define JOB_ERROR	1	/* Error in starting the job */
    238 #define JOB_FINISHED	2	/* The job is already finished */
    239 
    240 /*
    241  * Descriptions for various shells.
    242  *
    243  * The build environment may set DEFSHELL_INDEX to one of
    244  * DEFSHELL_INDEX_SH, DEFSHELL_INDEX_KSH, or DEFSHELL_INDEX_CSH, to
    245  * select one of the predefined shells as the default shell.
    246  *
    247  * Alternatively, the build environment may set DEFSHELL_CUSTOM to the
    248  * name or the full path of a sh-compatible shell, which will be used as
    249  * the default shell.
    250  *
    251  * ".SHELL" lines in Makefiles can choose the default shell from the
    252  # set defined here, or add additional shells.
    253  */
    254 
    255 #ifdef DEFSHELL_CUSTOM
    256 #define DEFSHELL_INDEX_CUSTOM 0
    257 #define DEFSHELL_INDEX_SH     1
    258 #define DEFSHELL_INDEX_KSH    2
    259 #define DEFSHELL_INDEX_CSH    3
    260 #else /* !DEFSHELL_CUSTOM */
    261 #define DEFSHELL_INDEX_SH     0
    262 #define DEFSHELL_INDEX_KSH    1
    263 #define DEFSHELL_INDEX_CSH    2
    264 #endif /* !DEFSHELL_CUSTOM */
    265 
    266 #ifndef DEFSHELL_INDEX
    267 #define DEFSHELL_INDEX 0	/* DEFSHELL_INDEX_CUSTOM or DEFSHELL_INDEX_SH */
    268 #endif /* !DEFSHELL_INDEX */
    269 
    270 static Shell    shells[] = {
    271 #ifdef DEFSHELL_CUSTOM
    272     /*
    273      * An sh-compatible shell with a non-standard name.
    274      *
    275      * Keep this in sync with the "sh" description below, but avoid
    276      * non-portable features that might not be supplied by all
    277      * sh-compatible shells.
    278      */
    279 {
    280     DEFSHELL_CUSTOM,
    281     FALSE, "", "", "", 0,
    282     FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
    283     "",
    284     "",
    285 },
    286 #endif /* DEFSHELL_CUSTOM */
    287     /*
    288      * SH description. Echo control is also possible and, under
    289      * sun UNIX anyway, one can even control error checking.
    290      */
    291 {
    292     "sh",			/* .name */
    293     FALSE,			/* .hasEchoCtl */
    294     "",				/* .echoOff */
    295     "",				/* .echoOn */
    296     "",				/* .noPrint */
    297     0,				/* .noPrintLen */
    298     FALSE,			/* .hasErrCtl */
    299     "echo \"%s\"\n", 		/* .errCheck */
    300     "%s\n",			/* .ignErr */
    301     "{ %s \n} || exit $?\n",	/* .errOut */
    302     "'\n'",			/* .newline */
    303     '#',			/* .commentChar*/
    304 #if defined(MAKE_NATIVE) && defined(__NetBSD__)
    305     "q",			/* .echo */
    306 #else
    307     "",				/* .echo */
    308 #endif
    309     "",				/* .exit */
    310 },
    311     /*
    312      * KSH description.
    313      */
    314 {
    315     "ksh",			/* .name */
    316     TRUE,			/* .hasEchoCtl */
    317     "set +v",			/* .echoOff */
    318     "set -v",			/* .echoOn */
    319     "set +v",			/* .noPrint */
    320     6,				/* .noPrintLen */
    321     FALSE,			/* .hasErrCtl */
    322     "echo \"%s\"\n",		/* .errCheck */
    323     "%s\n",			/* .ignErr */
    324     "{ %s \n} || exit $?\n",	/* .errOut */
    325     "'\n'",			/* .newline */
    326     '#',			/* .commentChar */
    327     "v",			/* .echo */
    328     "",				/* .exit */
    329 },
    330     /*
    331      * CSH description. The csh can do echo control by playing
    332      * with the setting of the 'echo' shell variable. Sadly,
    333      * however, it is unable to do error control nicely.
    334      */
    335 {
    336     "csh",			/* .name */
    337     TRUE,			/* .hasEchoCtl */
    338     "unset verbose",		/* .echoOff */
    339     "set verbose",		/* .echoOn */
    340     "unset verbose", 		/* .noPrint */
    341     13,				/* .noPrintLen */
    342     FALSE, 			/* .hasErrCtl */
    343     "echo \"%s\"\n", 		/* .errCheck */
    344     "csh -c \"%s || exit 0\"\n", /* .ignErr */
    345     "", 			/* .errOut */
    346     "'\\\n'",			/* .newline */
    347     '#',			/* .commentChar */
    348     "v", 			/* .echo */
    349     "e",			/* .exit */
    350 },
    351     /*
    352      * UNKNOWN.
    353      */
    354 {
    355     NULL,
    356     FALSE, NULL, NULL, NULL, 0,
    357     FALSE, NULL, NULL, NULL, NULL, '\0',
    358     NULL, NULL,
    359 }
    360 };
    361 
    362 /* This is the shell to which we pass all commands in the Makefile.
    363  * It is set by the Job_ParseShell function. */
    364 static Shell *commandShell = &shells[DEFSHELL_INDEX];
    365 const char *shellPath = NULL;	/* full pathname of executable image */
    366 const char *shellName = NULL;	/* last component of shellPath */
    367 char *shellErrFlag = NULL;
    368 static char *shellArgv = NULL;	/* Custom shell args */
    369 
    370 
    371 STATIC Job	*job_table;	/* The structures that describe them */
    372 STATIC Job	*job_table_end;	/* job_table + maxJobs */
    373 static unsigned int wantToken;	/* we want a token */
    374 static int lurking_children = 0;
    375 static int make_suspended = 0;	/* non-zero if we've seen a SIGTSTP (etc) */
    376 
    377 /*
    378  * Set of descriptors of pipes connected to
    379  * the output channels of children
    380  */
    381 static struct pollfd *fds = NULL;
    382 static Job **jobfds = NULL;
    383 static nfds_t nfds = 0;
    384 static void watchfd(Job *);
    385 static void clearfd(Job *);
    386 static int readyfd(Job *);
    387 
    388 STATIC GNode *lastNode;		/* The node for which output was most recently
    389 				 * produced. */
    390 static char *targPrefix = NULL; /* What we print at the start of TARG_FMT */
    391 static Job tokenWaitJob;	/* token wait pseudo-job */
    392 
    393 static Job childExitJob;	/* child exit pseudo-job */
    394 #define	CHILD_EXIT	"."
    395 #define	DO_JOB_RESUME	"R"
    396 
    397 enum { npseudojobs = 2 };	/* number of pseudo-jobs */
    398 
    399 #define TARG_FMT  "%s %s ---\n" /* Default format */
    400 #define MESSAGE(fp, gn) \
    401 	if (maxJobs != 1 && targPrefix && *targPrefix) \
    402 	    (void)fprintf(fp, TARG_FMT, targPrefix, gn->name)
    403 
    404 static sigset_t caught_signals;	/* Set of signals we handle */
    405 
    406 static void JobDoOutput(Job *, Boolean);
    407 static void JobInterrupt(int, int) MAKE_ATTR_DEAD;
    408 static void JobRestartJobs(void);
    409 static void JobSigReset(void);
    410 
    411 static unsigned
    412 nfds_per_job(void)
    413 {
    414 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
    415     if (useMeta)
    416 	return 2;
    417 #endif
    418     return 1;
    419 }
    420 
    421 static void
    422 job_table_dump(const char *where)
    423 {
    424     Job *job;
    425 
    426     debug_printf("job table @ %s\n", where);
    427     for (job = job_table; job < job_table_end; job++) {
    428 	debug_printf("job %d, status %d, flags %d, pid %d\n",
    429 	    (int)(job - job_table), job->job_state, job->flags, job->pid);
    430     }
    431 }
    432 
    433 /*
    434  * Delete the target of a failed, interrupted, or otherwise
    435  * unsuccessful job unless inhibited by .PRECIOUS.
    436  */
    437 static void
    438 JobDeleteTarget(GNode *gn)
    439 {
    440 	if ((gn->type & (OP_JOIN|OP_PHONY)) == 0 && !Targ_Precious(gn)) {
    441 	    char *file = (gn->path == NULL ? gn->name : gn->path);
    442 	    if (!noExecute && eunlink(file) != -1) {
    443 		Error("*** %s removed", file);
    444 	    }
    445 	}
    446 }
    447 
    448 /*
    449  * JobSigLock/JobSigUnlock
    450  *
    451  * Signal lock routines to get exclusive access. Currently used to
    452  * protect `jobs' and `stoppedJobs' list manipulations.
    453  */
    454 static void JobSigLock(sigset_t *omaskp)
    455 {
    456 	if (sigprocmask(SIG_BLOCK, &caught_signals, omaskp) != 0) {
    457 		Punt("JobSigLock: sigprocmask: %s", strerror(errno));
    458 		sigemptyset(omaskp);
    459 	}
    460 }
    461 
    462 static void JobSigUnlock(sigset_t *omaskp)
    463 {
    464 	(void)sigprocmask(SIG_SETMASK, omaskp, NULL);
    465 }
    466 
    467 static void
    468 JobCreatePipe(Job *job, int minfd)
    469 {
    470     int i, fd, flags;
    471     int pipe_fds[2];
    472 
    473     if (pipe(pipe_fds) == -1)
    474 	Punt("Cannot create pipe: %s", strerror(errno));
    475 
    476     for (i = 0; i < 2; i++) {
    477 	/* Avoid using low numbered fds */
    478 	fd = fcntl(pipe_fds[i], F_DUPFD, minfd);
    479 	if (fd != -1) {
    480 	    close(pipe_fds[i]);
    481 	    pipe_fds[i] = fd;
    482 	}
    483     }
    484 
    485     job->inPipe = pipe_fds[0];
    486     job->outPipe = pipe_fds[1];
    487 
    488     /* Set close-on-exec flag for both */
    489     if (fcntl(job->inPipe, F_SETFD, FD_CLOEXEC) == -1)
    490 	Punt("Cannot set close-on-exec: %s", strerror(errno));
    491     if (fcntl(job->outPipe, F_SETFD, FD_CLOEXEC) == -1)
    492 	Punt("Cannot set close-on-exec: %s", strerror(errno));
    493 
    494     /*
    495      * We mark the input side of the pipe non-blocking; we poll(2) the
    496      * pipe when we're waiting for a job token, but we might lose the
    497      * race for the token when a new one becomes available, so the read
    498      * from the pipe should not block.
    499      */
    500     flags = fcntl(job->inPipe, F_GETFL, 0);
    501     if (flags == -1)
    502 	Punt("Cannot get flags: %s", strerror(errno));
    503     flags |= O_NONBLOCK;
    504     if (fcntl(job->inPipe, F_SETFL, flags) == -1)
    505 	Punt("Cannot set flags: %s", strerror(errno));
    506 }
    507 
    508 /* Pass the signal to each running job. */
    509 static void
    510 JobCondPassSig(int signo)
    511 {
    512     Job *job;
    513 
    514     DEBUG1(JOB, "JobCondPassSig(%d) called.\n", signo);
    515 
    516     for (job = job_table; job < job_table_end; job++) {
    517 	if (job->job_state != JOB_ST_RUNNING)
    518 	    continue;
    519 	DEBUG2(JOB, "JobCondPassSig passing signal %d to child %d.\n",
    520 	       signo, job->pid);
    521 	KILLPG(job->pid, signo);
    522     }
    523 }
    524 
    525 /* SIGCHLD handler.
    526  *
    527  * Sends a token on the child exit pipe to wake us up from select()/poll(). */
    528 static void
    529 JobChildSig(int signo MAKE_ATTR_UNUSED)
    530 {
    531     while (write(childExitJob.outPipe, CHILD_EXIT, 1) == -1 && errno == EAGAIN)
    532 	continue;
    533 }
    534 
    535 
    536 /* Resume all stopped jobs. */
    537 static void
    538 JobContinueSig(int signo MAKE_ATTR_UNUSED)
    539 {
    540     /*
    541      * Defer sending to SIGCONT to our stopped children until we return
    542      * from the signal handler.
    543      */
    544     while (write(childExitJob.outPipe, DO_JOB_RESUME, 1) == -1 &&
    545 	errno == EAGAIN)
    546 	continue;
    547 }
    548 
    549 /* Pass a signal on to all jobs, then resend to ourselves.
    550  * We die by the same signal. */
    551 MAKE_ATTR_DEAD static void
    552 JobPassSig_int(int signo)
    553 {
    554     /* Run .INTERRUPT target then exit */
    555     JobInterrupt(TRUE, signo);
    556 }
    557 
    558 /* Pass a signal on to all jobs, then resend to ourselves.
    559  * We die by the same signal. */
    560 MAKE_ATTR_DEAD static void
    561 JobPassSig_term(int signo)
    562 {
    563     /* Dont run .INTERRUPT target then exit */
    564     JobInterrupt(FALSE, signo);
    565 }
    566 
    567 static void
    568 JobPassSig_suspend(int signo)
    569 {
    570     sigset_t nmask, omask;
    571     struct sigaction act;
    572 
    573     /* Suppress job started/continued messages */
    574     make_suspended = 1;
    575 
    576     /* Pass the signal onto every job */
    577     JobCondPassSig(signo);
    578 
    579     /*
    580      * Send ourselves the signal now we've given the message to everyone else.
    581      * Note we block everything else possible while we're getting the signal.
    582      * This ensures that all our jobs get continued when we wake up before
    583      * we take any other signal.
    584      */
    585     sigfillset(&nmask);
    586     sigdelset(&nmask, signo);
    587     (void)sigprocmask(SIG_SETMASK, &nmask, &omask);
    588 
    589     act.sa_handler = SIG_DFL;
    590     sigemptyset(&act.sa_mask);
    591     act.sa_flags = 0;
    592     (void)sigaction(signo, &act, NULL);
    593 
    594     if (DEBUG(JOB))
    595 	debug_printf("JobPassSig passing signal %d to self.\n", signo);
    596 
    597     (void)kill(getpid(), signo);
    598 
    599     /*
    600      * We've been continued.
    601      *
    602      * A whole host of signals continue to happen!
    603      * SIGCHLD for any processes that actually suspended themselves.
    604      * SIGCHLD for any processes that exited while we were alseep.
    605      * The SIGCONT that actually caused us to wakeup.
    606      *
    607      * Since we defer passing the SIGCONT on to our children until
    608      * the main processing loop, we can be sure that all the SIGCHLD
    609      * events will have happened by then - and that the waitpid() will
    610      * collect the child 'suspended' events.
    611      * For correct sequencing we just need to ensure we process the
    612      * waitpid() before passign on the SIGCONT.
    613      *
    614      * In any case nothing else is needed here.
    615      */
    616 
    617     /* Restore handler and signal mask */
    618     act.sa_handler = JobPassSig_suspend;
    619     (void)sigaction(signo, &act, NULL);
    620     (void)sigprocmask(SIG_SETMASK, &omask, NULL);
    621 }
    622 
    623 static Job *
    624 JobFindPid(int pid, JobState status, Boolean isJobs)
    625 {
    626     Job *job;
    627 
    628     for (job = job_table; job < job_table_end; job++) {
    629 	if ((job->job_state == status) && job->pid == pid)
    630 	    return job;
    631     }
    632     if (DEBUG(JOB) && isJobs)
    633 	job_table_dump("no pid");
    634     return NULL;
    635 }
    636 
    637 /*-
    638  *-----------------------------------------------------------------------
    639  * JobPrintCommand  --
    640  *	Put out another command for the given job. If the command starts
    641  *	with an @ or a - we process it specially. In the former case,
    642  *	so long as the -s and -n flags weren't given to make, we stick
    643  *	a shell-specific echoOff command in the script. In the latter,
    644  *	we ignore errors for the entire job, unless the shell has error
    645  *	control.
    646  *	If the command is just "..." we take all future commands for this
    647  *	job to be commands to be executed once the entire graph has been
    648  *	made and return non-zero to signal that the end of the commands
    649  *	was reached. These commands are later attached to the postCommands
    650  *	node and executed by Job_End when all things are done.
    651  *	This function is called from JobStart via Lst_ForEachUntil.
    652  *
    653  * Input:
    654  *	cmdp		command string to print
    655  *	jobp		job for which to print it
    656  *
    657  * Side Effects:
    658  *	If the command begins with a '-' and the shell has no error control,
    659  *	the JOB_IGNERR flag is set in the job descriptor.
    660  *	numCommands is incremented if the command is actually printed.
    661  *-----------------------------------------------------------------------
    662  */
    663 static void
    664 JobPrintCommand(Job *job, char *cmd)
    665 {
    666     const char *const cmdp = cmd;
    667     Boolean noSpecials;		/* true if we shouldn't worry about
    668 				 * inserting special commands into
    669 				 * the input stream. */
    670     Boolean shutUp = FALSE;	/* true if we put a no echo command
    671 				 * into the command file */
    672     Boolean errOff = FALSE;	/* true if we turned error checking
    673 				 * off before printing the command
    674 				 * and need to turn it back on */
    675     const char *cmdTemplate;	/* Template to use when printing the
    676 				 * command */
    677     char *cmdStart;		/* Start of expanded command */
    678     char *escCmd = NULL;	/* Command with quotes/backticks escaped */
    679 
    680     noSpecials = NoExecute(job->node);
    681 
    682 #define DBPRINTF(fmt, arg) if (DEBUG(JOB)) {	\
    683 	debug_printf(fmt, arg);			\
    684     }						\
    685    (void)fprintf(job->cmdFILE, fmt, arg);	\
    686    (void)fflush(job->cmdFILE);
    687 
    688     numCommands++;
    689 
    690     Var_Subst(cmd, job->node, VARE_WANTRES, &cmd);
    691     /* TODO: handle errors */
    692     cmdStart = cmd;
    693 
    694     cmdTemplate = "%s\n";
    695 
    696     /*
    697      * Check for leading @' and -'s to control echoing and error checking.
    698      */
    699     while (*cmd == '@' || *cmd == '-' || (*cmd == '+')) {
    700 	switch (*cmd) {
    701 	case '@':
    702 	    shutUp = DEBUG(LOUD) ? FALSE : TRUE;
    703 	    break;
    704 	case '-':
    705 	    errOff = TRUE;
    706 	    break;
    707 	case '+':
    708 	    if (noSpecials) {
    709 		/*
    710 		 * We're not actually executing anything...
    711 		 * but this one needs to be - use compat mode just for it.
    712 		 */
    713 		Compat_RunCommand(cmdp, job->node);
    714 		free(cmdStart);
    715 		return;
    716 	    }
    717 	    break;
    718 	}
    719 	cmd++;
    720     }
    721 
    722     pp_skip_whitespace(&cmd);
    723 
    724     /*
    725      * If the shell doesn't have error control the alternate echo'ing will
    726      * be done (to avoid showing additional error checking code)
    727      * and this will need the characters '$ ` \ "' escaped
    728      */
    729 
    730     if (!commandShell->hasErrCtl) {
    731 	int i, j;
    732 
    733 	/* Worst that could happen is every char needs escaping. */
    734 	escCmd = bmake_malloc((strlen(cmd) * 2) + 1);
    735 	for (i = 0, j = 0; cmd[i] != '\0'; i++, j++) {
    736 	    if (cmd[i] == '$' || cmd[i] == '`' || cmd[i] == '\\' ||
    737 		cmd[i] == '"')
    738 		escCmd[j++] = '\\';
    739 	    escCmd[j] = cmd[i];
    740 	}
    741 	escCmd[j] = '\0';
    742     }
    743 
    744     if (shutUp) {
    745 	if (!(job->flags & JOB_SILENT) && !noSpecials &&
    746 	    commandShell->hasEchoCtl) {
    747 		DBPRINTF("%s\n", commandShell->echoOff);
    748 	} else {
    749 	    if (commandShell->hasErrCtl)
    750 		shutUp = FALSE;
    751 	}
    752     }
    753 
    754     if (errOff) {
    755 	if (!noSpecials) {
    756 	    if (commandShell->hasErrCtl) {
    757 		/*
    758 		 * we don't want the error-control commands showing
    759 		 * up either, so we turn off echoing while executing
    760 		 * them. We could put another field in the shell
    761 		 * structure to tell JobDoOutput to look for this
    762 		 * string too, but why make it any more complex than
    763 		 * it already is?
    764 		 */
    765 		if (!(job->flags & JOB_SILENT) && !shutUp &&
    766 		    commandShell->hasEchoCtl) {
    767 			DBPRINTF("%s\n", commandShell->echoOff);
    768 			DBPRINTF("%s\n", commandShell->ignErr);
    769 			DBPRINTF("%s\n", commandShell->echoOn);
    770 		} else {
    771 			DBPRINTF("%s\n", commandShell->ignErr);
    772 		}
    773 	    } else if (commandShell->ignErr &&
    774 		       commandShell->ignErr[0] != '\0')
    775 	    {
    776 		/*
    777 		 * The shell has no error control, so we need to be
    778 		 * weird to get it to ignore any errors from the command.
    779 		 * If echoing is turned on, we turn it off and use the
    780 		 * errCheck template to echo the command. Leave echoing
    781 		 * off so the user doesn't see the weirdness we go through
    782 		 * to ignore errors. Set cmdTemplate to use the weirdness
    783 		 * instead of the simple "%s\n" template.
    784 		 */
    785 		job->flags |= JOB_IGNERR;
    786 		if (!(job->flags & JOB_SILENT) && !shutUp) {
    787 			if (commandShell->hasEchoCtl) {
    788 				DBPRINTF("%s\n", commandShell->echoOff);
    789 			}
    790 			DBPRINTF(commandShell->errCheck, escCmd);
    791 			shutUp = TRUE;
    792 		} else {
    793 			if (!shutUp) {
    794 				DBPRINTF(commandShell->errCheck, escCmd);
    795 			}
    796 		}
    797 		cmdTemplate = commandShell->ignErr;
    798 		/*
    799 		 * The error ignoration (hee hee) is already taken care
    800 		 * of by the ignErr template, so pretend error checking
    801 		 * is still on.
    802 		 */
    803 		errOff = FALSE;
    804 	    } else {
    805 		errOff = FALSE;
    806 	    }
    807 	} else {
    808 	    errOff = FALSE;
    809 	}
    810     } else {
    811 
    812 	/*
    813 	 * If errors are being checked and the shell doesn't have error control
    814 	 * but does supply an errOut template, then setup commands to run
    815 	 * through it.
    816 	 */
    817 
    818 	if (!commandShell->hasErrCtl && commandShell->errOut &&
    819 	    commandShell->errOut[0] != '\0') {
    820 		if (!(job->flags & JOB_SILENT) && !shutUp) {
    821 			if (commandShell->hasEchoCtl) {
    822 				DBPRINTF("%s\n", commandShell->echoOff);
    823 			}
    824 			DBPRINTF(commandShell->errCheck, escCmd);
    825 			shutUp = TRUE;
    826 		}
    827 		/* If it's a comment line or blank, treat as an ignored error */
    828 		if ((escCmd[0] == commandShell->commentChar) ||
    829 		    (escCmd[0] == 0))
    830 			cmdTemplate = commandShell->ignErr;
    831 		else
    832 			cmdTemplate = commandShell->errOut;
    833 		errOff = FALSE;
    834 	}
    835     }
    836 
    837     if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0 &&
    838 	(job->flags & JOB_TRACED) == 0) {
    839 	    DBPRINTF("set -%s\n", "x");
    840 	    job->flags |= JOB_TRACED;
    841     }
    842 
    843     DBPRINTF(cmdTemplate, cmd);
    844     free(cmdStart);
    845     free(escCmd);
    846     if (errOff) {
    847 	/*
    848 	 * If echoing is already off, there's no point in issuing the
    849 	 * echoOff command. Otherwise we issue it and pretend it was on
    850 	 * for the whole command...
    851 	 */
    852 	if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl){
    853 	    DBPRINTF("%s\n", commandShell->echoOff);
    854 	    shutUp = TRUE;
    855 	}
    856 	DBPRINTF("%s\n", commandShell->errCheck);
    857     }
    858     if (shutUp && commandShell->hasEchoCtl) {
    859 	DBPRINTF("%s\n", commandShell->echoOn);
    860     }
    861 }
    862 
    863 /* Print all commands to the shell file that is later executed.
    864  *
    865  * The special command "..." stops printing and saves the remaining commands
    866  * to be executed later. */
    867 static void
    868 JobPrintCommands(Job *job)
    869 {
    870     StringListNode *ln;
    871 
    872     for (ln = job->node->commands->first; ln != NULL; ln = ln->next) {
    873         const char *cmd = ln->datum;
    874 
    875 	if (strcmp(cmd, "...") == 0) {
    876 	    job->node->type |= OP_SAVE_CMDS;
    877 	    if ((job->flags & JOB_IGNDOTS) == 0) {
    878 		job->tailCmds = ln->next;
    879 		break;
    880 	    }
    881 	} else
    882 	    JobPrintCommand(job, ln->datum);
    883     }
    884 }
    885 
    886 /* Save the delayed commands, to be executed when everything else is done. */
    887 static void
    888 JobSaveCommands(Job *job)
    889 {
    890     StringListNode *node;
    891 
    892     for (node = job->tailCmds; node != NULL; node = node->next) {
    893 	const char *cmd = node->datum;
    894 	char *expanded_cmd;
    895 	/* XXX: This Var_Subst is only intended to expand the dynamic
    896 	 * variables such as .TARGET, .IMPSRC.  It is not intended to
    897 	 * expand the other variables as well; see deptgt-end.mk. */
    898 	(void)Var_Subst(cmd, job->node, VARE_WANTRES, &expanded_cmd);
    899 	/* TODO: handle errors */
    900 	Lst_Append(Targ_GetEndNode()->commands, expanded_cmd);
    901     }
    902 }
    903 
    904 
    905 /* Called to close both input and output pipes when a job is finished. */
    906 static void
    907 JobClose(Job *job)
    908 {
    909     clearfd(job);
    910     (void)close(job->outPipe);
    911     job->outPipe = -1;
    912 
    913     JobDoOutput(job, TRUE);
    914     (void)close(job->inPipe);
    915     job->inPipe = -1;
    916 }
    917 
    918 /*-
    919  *-----------------------------------------------------------------------
    920  * JobFinish  --
    921  *	Do final processing for the given job including updating
    922  *	parents and starting new jobs as available/necessary. Note
    923  *	that we pay no attention to the JOB_IGNERR flag here.
    924  *	This is because when we're called because of a noexecute flag
    925  *	or something, jstat.w_status is 0 and when called from
    926  *	Job_CatchChildren, the status is zeroed if it s/b ignored.
    927  *
    928  * Input:
    929  *	job		job to finish
    930  *	status		sub-why job went away
    931  *
    932  * Side Effects:
    933  *	Final commands for the job are placed on postCommands.
    934  *
    935  *	If we got an error and are aborting (aborting == ABORT_ERROR) and
    936  *	the job list is now empty, we are done for the day.
    937  *	If we recognized an error (errors !=0), we set the aborting flag
    938  *	to ABORT_ERROR so no more jobs will be started.
    939  *-----------------------------------------------------------------------
    940  */
    941 static void
    942 JobFinish(Job *job, int status)
    943 {
    944     Boolean done, return_job_token;
    945 
    946     DEBUG3(JOB, "JobFinish: %d [%s], status %d\n",
    947 	   job->pid, job->node->name, status);
    948 
    949     if ((WIFEXITED(status) &&
    950 	 (((WEXITSTATUS(status) != 0) && !(job->flags & JOB_IGNERR)))) ||
    951 	WIFSIGNALED(status))
    952     {
    953 	/*
    954 	 * If it exited non-zero and either we're doing things our
    955 	 * way or we're not ignoring errors, the job is finished.
    956 	 * Similarly, if the shell died because of a signal
    957 	 * the job is also finished. In these
    958 	 * cases, finish out the job's output before printing the exit
    959 	 * status...
    960 	 */
    961 	JobClose(job);
    962 	if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
    963 	   (void)fclose(job->cmdFILE);
    964 	   job->cmdFILE = NULL;
    965 	}
    966 	done = TRUE;
    967     } else if (WIFEXITED(status)) {
    968 	/*
    969 	 * Deal with ignored errors in -B mode. We need to print a message
    970 	 * telling of the ignored error as well as setting status.w_status
    971 	 * to 0 so the next command gets run. To do this, we set done to be
    972 	 * TRUE if in -B mode and the job exited non-zero.
    973 	 */
    974 	done = WEXITSTATUS(status) != 0;
    975 	/*
    976 	 * Old comment said: "Note we don't
    977 	 * want to close down any of the streams until we know we're at the
    978 	 * end."
    979 	 * But we do. Otherwise when are we going to print the rest of the
    980 	 * stuff?
    981 	 */
    982 	JobClose(job);
    983     } else {
    984 	/*
    985 	 * No need to close things down or anything.
    986 	 */
    987 	done = FALSE;
    988     }
    989 
    990     if (done) {
    991 	if (WIFEXITED(status)) {
    992 	    DEBUG2(JOB, "Process %d [%s] exited.\n",
    993 		   job->pid, job->node->name);
    994 	    if (WEXITSTATUS(status) != 0) {
    995 		if (job->node != lastNode) {
    996 		    MESSAGE(stdout, job->node);
    997 		    lastNode = job->node;
    998 		}
    999 #ifdef USE_META
   1000 		if (useMeta) {
   1001 		    meta_job_error(job, job->node, job->flags, WEXITSTATUS(status));
   1002 		}
   1003 #endif
   1004 		if (!dieQuietly(job->node, -1))
   1005 		    (void)printf("*** [%s] Error code %d%s\n",
   1006 				 job->node->name,
   1007 				 WEXITSTATUS(status),
   1008 				 (job->flags & JOB_IGNERR) ? " (ignored)" : "");
   1009 		if (job->flags & JOB_IGNERR) {
   1010 		    status = 0;
   1011 		} else {
   1012 		    if (deleteOnError) {
   1013 			JobDeleteTarget(job->node);
   1014 		    }
   1015 		    PrintOnError(job->node, NULL);
   1016 		}
   1017 	    } else if (DEBUG(JOB)) {
   1018 		if (job->node != lastNode) {
   1019 		    MESSAGE(stdout, job->node);
   1020 		    lastNode = job->node;
   1021 		}
   1022 		(void)printf("*** [%s] Completed successfully\n",
   1023 				job->node->name);
   1024 	    }
   1025 	} else {
   1026 	    if (job->node != lastNode) {
   1027 		MESSAGE(stdout, job->node);
   1028 		lastNode = job->node;
   1029 	    }
   1030 	    (void)printf("*** [%s] Signal %d\n",
   1031 			job->node->name, WTERMSIG(status));
   1032 	    if (deleteOnError) {
   1033 		JobDeleteTarget(job->node);
   1034 	    }
   1035 	}
   1036 	(void)fflush(stdout);
   1037     }
   1038 
   1039 #ifdef USE_META
   1040     if (useMeta) {
   1041 	int x;
   1042 
   1043 	if ((x = meta_job_finish(job)) != 0 && status == 0) {
   1044 	    status = x;
   1045 	}
   1046     }
   1047 #endif
   1048 
   1049     return_job_token = FALSE;
   1050 
   1051     Trace_Log(JOBEND, job);
   1052     if (!(job->flags & JOB_SPECIAL)) {
   1053 	if ((status != 0) ||
   1054 		(aborting == ABORT_ERROR) ||
   1055 		(aborting == ABORT_INTERRUPT))
   1056 	    return_job_token = TRUE;
   1057     }
   1058 
   1059     if ((aborting != ABORT_ERROR) && (aborting != ABORT_INTERRUPT) && (status == 0)) {
   1060 	/*
   1061 	 * As long as we aren't aborting and the job didn't return a non-zero
   1062 	 * status that we shouldn't ignore, we call Make_Update to update
   1063 	 * the parents.
   1064 	 */
   1065 	JobSaveCommands(job);
   1066 	job->node->made = MADE;
   1067 	if (!(job->flags & JOB_SPECIAL))
   1068 	    return_job_token = TRUE;
   1069 	Make_Update(job->node);
   1070 	job->job_state = JOB_ST_FREE;
   1071     } else if (status != 0) {
   1072 	errors++;
   1073 	job->job_state = JOB_ST_FREE;
   1074     }
   1075 
   1076     /*
   1077      * Set aborting if any error.
   1078      */
   1079     if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
   1080 	/*
   1081 	 * If we found any errors in this batch of children and the -k flag
   1082 	 * wasn't given, we set the aborting flag so no more jobs get
   1083 	 * started.
   1084 	 */
   1085 	aborting = ABORT_ERROR;
   1086     }
   1087 
   1088     if (return_job_token)
   1089 	Job_TokenReturn();
   1090 
   1091     if (aborting == ABORT_ERROR && jobTokensRunning == 0) {
   1092 	/*
   1093 	 * If we are aborting and the job table is now empty, we finish.
   1094 	 */
   1095 	Finish(errors);
   1096     }
   1097 }
   1098 
   1099 /* Touch the given target. Called by JobStart when the -t flag was given.
   1100  *
   1101  * The modification date of the file is changed.
   1102  * If the file did not exist, it is created. */
   1103 void
   1104 Job_Touch(GNode *gn, Boolean silent)
   1105 {
   1106     int streamID;		/* ID of stream opened to do the touch */
   1107     struct utimbuf times;	/* Times for utime() call */
   1108 
   1109     if (gn->type & (OP_JOIN|OP_USE|OP_USEBEFORE|OP_EXEC|OP_OPTIONAL|
   1110 	OP_SPECIAL|OP_PHONY)) {
   1111 	/*
   1112 	 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets
   1113 	 * and, as such, shouldn't really be created.
   1114 	 */
   1115 	return;
   1116     }
   1117 
   1118     if (!silent || NoExecute(gn)) {
   1119 	(void)fprintf(stdout, "touch %s\n", gn->name);
   1120 	(void)fflush(stdout);
   1121     }
   1122 
   1123     if (NoExecute(gn)) {
   1124 	return;
   1125     }
   1126 
   1127     if (gn->type & OP_ARCHV) {
   1128 	Arch_Touch(gn);
   1129     } else if (gn->type & OP_LIB) {
   1130 	Arch_TouchLib(gn);
   1131     } else {
   1132 	char	*file = gn->path ? gn->path : gn->name;
   1133 
   1134 	times.actime = times.modtime = now;
   1135 	if (utime(file, &times) < 0){
   1136 	    streamID = open(file, O_RDWR | O_CREAT, 0666);
   1137 
   1138 	    if (streamID >= 0) {
   1139 		char	c;
   1140 
   1141 		/*
   1142 		 * Read and write a byte to the file to change the
   1143 		 * modification time, then close the file.
   1144 		 */
   1145 		if (read(streamID, &c, 1) == 1) {
   1146 		    (void)lseek(streamID, (off_t)0, SEEK_SET);
   1147 		    while (write(streamID, &c, 1) == -1 && errno == EAGAIN)
   1148 			continue;
   1149 		}
   1150 
   1151 		(void)close(streamID);
   1152 	    } else {
   1153 		(void)fprintf(stdout, "*** couldn't touch %s: %s",
   1154 			       file, strerror(errno));
   1155 		(void)fflush(stdout);
   1156 	    }
   1157 	}
   1158     }
   1159 }
   1160 
   1161 /* Make sure the given node has all the commands it needs.
   1162  *
   1163  * The node will have commands from the .DEFAULT rule added to it if it
   1164  * needs them.
   1165  *
   1166  * Input:
   1167  *	gn		The target whose commands need verifying
   1168  *	abortProc	Function to abort with message
   1169  *
   1170  * Results:
   1171  *	TRUE if the commands list is/was ok.
   1172  */
   1173 Boolean
   1174 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
   1175 {
   1176     if (OP_NOP(gn->type) && Lst_IsEmpty(gn->commands) &&
   1177 	((gn->type & OP_LIB) == 0 || Lst_IsEmpty(gn->children))) {
   1178 	/*
   1179 	 * No commands. Look for .DEFAULT rule from which we might infer
   1180 	 * commands
   1181 	 */
   1182 	if ((DEFAULT != NULL) && !Lst_IsEmpty(DEFAULT->commands) &&
   1183 		(gn->type & OP_SPECIAL) == 0) {
   1184 	    char *p1;
   1185 	    /*
   1186 	     * Make only looks for a .DEFAULT if the node was never the
   1187 	     * target of an operator, so that's what we do too. If
   1188 	     * a .DEFAULT was given, we substitute its commands for gn's
   1189 	     * commands and set the IMPSRC variable to be the target's name
   1190 	     * The DEFAULT node acts like a transformation rule, in that
   1191 	     * gn also inherits any attributes or sources attached to
   1192 	     * .DEFAULT itself.
   1193 	     */
   1194 	    Make_HandleUse(DEFAULT, gn);
   1195 	    Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn);
   1196 	    bmake_free(p1);
   1197 	} else if (Dir_MTime(gn, 0) == 0 && (gn->type & OP_SPECIAL) == 0) {
   1198 	    /*
   1199 	     * The node wasn't the target of an operator.  We have no .DEFAULT
   1200 	     * rule to go on and the target doesn't already exist. There's
   1201 	     * nothing more we can do for this branch. If the -k flag wasn't
   1202 	     * given, we stop in our tracks, otherwise we just don't update
   1203 	     * this node's parents so they never get examined.
   1204 	     */
   1205 	    static const char msg[] = ": don't know how to make";
   1206 
   1207 	    if (gn->flags & FROM_DEPEND) {
   1208 		if (!Job_RunTarget(".STALE", gn->fname))
   1209 		    fprintf(stdout, "%s: %s, %d: ignoring stale %s for %s\n",
   1210 			progname, gn->fname, gn->lineno, makeDependfile,
   1211 			gn->name);
   1212 		return TRUE;
   1213 	    }
   1214 
   1215 	    if (gn->type & OP_OPTIONAL) {
   1216 		(void)fprintf(stdout, "%s%s %s (ignored)\n", progname,
   1217 		    msg, gn->name);
   1218 		(void)fflush(stdout);
   1219 	    } else if (keepgoing) {
   1220 		(void)fprintf(stdout, "%s%s %s (continuing)\n", progname,
   1221 		    msg, gn->name);
   1222 		(void)fflush(stdout);
   1223 		return FALSE;
   1224 	    } else {
   1225 		(*abortProc)("%s%s %s. Stop", progname, msg, gn->name);
   1226 		return FALSE;
   1227 	    }
   1228 	}
   1229     }
   1230     return TRUE;
   1231 }
   1232 
   1233 /* Execute the shell for the given job. Called from JobStart
   1234  *
   1235  * A shell is executed, its output is altered and the Job structure added
   1236  * to the job table.
   1237  */
   1238 static void
   1239 JobExec(Job *job, char **argv)
   1240 {
   1241     int cpid;			/* ID of new child */
   1242     sigset_t	  mask;
   1243 
   1244     job->flags &= ~JOB_TRACED;
   1245 
   1246     if (DEBUG(JOB)) {
   1247 	int i;
   1248 
   1249 	debug_printf("Running %s %sly\n", job->node->name, "local");
   1250 	debug_printf("\tCommand: ");
   1251 	for (i = 0; argv[i] != NULL; i++) {
   1252 	    debug_printf("%s ", argv[i]);
   1253 	}
   1254 	debug_printf("\n");
   1255     }
   1256 
   1257     /*
   1258      * Some jobs produce no output and it's disconcerting to have
   1259      * no feedback of their running (since they produce no output, the
   1260      * banner with their name in it never appears). This is an attempt to
   1261      * provide that feedback, even if nothing follows it.
   1262      */
   1263     if ((lastNode != job->node) && !(job->flags & JOB_SILENT)) {
   1264 	MESSAGE(stdout, job->node);
   1265 	lastNode = job->node;
   1266     }
   1267 
   1268     /* No interruptions until this job is on the `jobs' list */
   1269     JobSigLock(&mask);
   1270 
   1271     /* Pre-emptively mark job running, pid still zero though */
   1272     job->job_state = JOB_ST_RUNNING;
   1273 
   1274     cpid = vFork();
   1275     if (cpid == -1)
   1276 	Punt("Cannot vfork: %s", strerror(errno));
   1277 
   1278     if (cpid == 0) {
   1279 	/* Child */
   1280 	sigset_t tmask;
   1281 
   1282 #ifdef USE_META
   1283 	if (useMeta) {
   1284 	    meta_job_child(job);
   1285 	}
   1286 #endif
   1287 	/*
   1288 	 * Reset all signal handlers; this is necessary because we also
   1289 	 * need to unblock signals before we exec(2).
   1290 	 */
   1291 	JobSigReset();
   1292 
   1293 	/* Now unblock signals */
   1294 	sigemptyset(&tmask);
   1295 	JobSigUnlock(&tmask);
   1296 
   1297 	/*
   1298 	 * Must duplicate the input stream down to the child's input and
   1299 	 * reset it to the beginning (again). Since the stream was marked
   1300 	 * close-on-exec, we must clear that bit in the new input.
   1301 	 */
   1302 	if (dup2(fileno(job->cmdFILE), 0) == -1)
   1303 	    execDie("dup2", "job->cmdFILE");
   1304 	if (fcntl(0, F_SETFD, 0) == -1)
   1305 	    execDie("fcntl clear close-on-exec", "stdin");
   1306 	if (lseek(0, (off_t)0, SEEK_SET) == -1)
   1307 	    execDie("lseek to 0", "stdin");
   1308 
   1309 	if (job->node->type & (OP_MAKE | OP_SUBMAKE)) {
   1310 		/*
   1311 		 * Pass job token pipe to submakes.
   1312 		 */
   1313 		if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1)
   1314 		    execDie("clear close-on-exec", "tokenWaitJob.inPipe");
   1315 		if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1)
   1316 		    execDie("clear close-on-exec", "tokenWaitJob.outPipe");
   1317 	}
   1318 
   1319 	/*
   1320 	 * Set up the child's output to be routed through the pipe
   1321 	 * we've created for it.
   1322 	 */
   1323 	if (dup2(job->outPipe, 1) == -1)
   1324 	    execDie("dup2", "job->outPipe");
   1325 
   1326 	/*
   1327 	 * The output channels are marked close on exec. This bit was
   1328 	 * duplicated by the dup2(on some systems), so we have to clear
   1329 	 * it before routing the shell's error output to the same place as
   1330 	 * its standard output.
   1331 	 */
   1332 	if (fcntl(1, F_SETFD, 0) == -1)
   1333 	    execDie("clear close-on-exec", "stdout");
   1334 	if (dup2(1, 2) == -1)
   1335 	    execDie("dup2", "1, 2");
   1336 
   1337 	/*
   1338 	 * We want to switch the child into a different process family so
   1339 	 * we can kill it and all its descendants in one fell swoop,
   1340 	 * by killing its process family, but not commit suicide.
   1341 	 */
   1342 #if defined(MAKE_NATIVE) || defined(HAVE_SETPGID)
   1343 #if defined(SYSV)
   1344 	/* XXX: dsl - I'm sure this should be setpgrp()... */
   1345 	(void)setsid();
   1346 #else
   1347 	(void)setpgid(0, getpid());
   1348 #endif
   1349 #endif
   1350 
   1351 	Var_ExportVars();
   1352 
   1353 	(void)execv(shellPath, argv);
   1354 	execDie("exec", shellPath);
   1355     }
   1356 
   1357     /* Parent, continuing after the child exec */
   1358     job->pid = cpid;
   1359 
   1360     Trace_Log(JOBSTART, job);
   1361 
   1362 #ifdef USE_META
   1363     if (useMeta) {
   1364 	meta_job_parent(job, cpid);
   1365     }
   1366 #endif
   1367 
   1368     /*
   1369      * Set the current position in the buffer to the beginning
   1370      * and mark another stream to watch in the outputs mask
   1371      */
   1372     job->curPos = 0;
   1373 
   1374     watchfd(job);
   1375 
   1376     if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
   1377 	(void)fclose(job->cmdFILE);
   1378 	job->cmdFILE = NULL;
   1379     }
   1380 
   1381     /*
   1382      * Now the job is actually running, add it to the table.
   1383      */
   1384     if (DEBUG(JOB)) {
   1385 	debug_printf("JobExec(%s): pid %d added to jobs table\n",
   1386 		     job->node->name, job->pid);
   1387 	job_table_dump("job started");
   1388     }
   1389     JobSigUnlock(&mask);
   1390 }
   1391 
   1392 /* Create the argv needed to execute the shell for a given job. */
   1393 static void
   1394 JobMakeArgv(Job *job, char **argv)
   1395 {
   1396     int argc;
   1397     static char args[10];	/* For merged arguments */
   1398 
   1399     argv[0] = UNCONST(shellName);
   1400     argc = 1;
   1401 
   1402     if ((commandShell->exit && commandShell->exit[0] != '-') ||
   1403 	(commandShell->echo && commandShell->echo[0] != '-'))
   1404     {
   1405 	/*
   1406 	 * At least one of the flags doesn't have a minus before it, so
   1407 	 * merge them together. Have to do this because the *(&(@*#*&#$#
   1408 	 * Bourne shell thinks its second argument is a file to source.
   1409 	 * Grrrr. Note the ten-character limitation on the combined arguments.
   1410 	 */
   1411 	(void)snprintf(args, sizeof(args), "-%s%s",
   1412 		      ((job->flags & JOB_IGNERR) ? "" :
   1413 		       (commandShell->exit ? commandShell->exit : "")),
   1414 		      ((job->flags & JOB_SILENT) ? "" :
   1415 		       (commandShell->echo ? commandShell->echo : "")));
   1416 
   1417 	if (args[1]) {
   1418 	    argv[argc] = args;
   1419 	    argc++;
   1420 	}
   1421     } else {
   1422 	if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
   1423 	    argv[argc] = UNCONST(commandShell->exit);
   1424 	    argc++;
   1425 	}
   1426 	if (!(job->flags & JOB_SILENT) && commandShell->echo) {
   1427 	    argv[argc] = UNCONST(commandShell->echo);
   1428 	    argc++;
   1429 	}
   1430     }
   1431     argv[argc] = NULL;
   1432 }
   1433 
   1434 /*-
   1435  *-----------------------------------------------------------------------
   1436  * JobStart  --
   1437  *	Start a target-creation process going for the target described
   1438  *	by the graph node gn.
   1439  *
   1440  * Input:
   1441  *	gn		target to create
   1442  *	flags		flags for the job to override normal ones.
   1443  *			e.g. JOB_SPECIAL or JOB_IGNDOTS
   1444  *	previous	The previous Job structure for this node, if any.
   1445  *
   1446  * Results:
   1447  *	JOB_ERROR if there was an error in the commands, JOB_FINISHED
   1448  *	if there isn't actually anything left to do for the job and
   1449  *	JOB_RUNNING if the job has been started.
   1450  *
   1451  * Side Effects:
   1452  *	A new Job node is created and added to the list of running
   1453  *	jobs. PMake is forked and a child shell created.
   1454  *
   1455  * NB: I'm fairly sure that this code is never called with JOB_SPECIAL set
   1456  *     JOB_IGNDOTS is never set (dsl)
   1457  *     Also the return value is ignored by everyone.
   1458  *-----------------------------------------------------------------------
   1459  */
   1460 static int
   1461 JobStart(GNode *gn, int flags)
   1462 {
   1463     Job *job;			/* new job descriptor */
   1464     char *argv[10];		/* Argument vector to shell */
   1465     Boolean cmdsOK;		/* true if the nodes commands were all right */
   1466     Boolean noExec;		/* Set true if we decide not to run the job */
   1467     int tfd;			/* File descriptor to the temp file */
   1468 
   1469     for (job = job_table; job < job_table_end; job++) {
   1470 	if (job->job_state == JOB_ST_FREE)
   1471 	    break;
   1472     }
   1473     if (job >= job_table_end)
   1474 	Punt("JobStart no job slots vacant");
   1475 
   1476     memset(job, 0, sizeof *job);
   1477     job->job_state = JOB_ST_SETUP;
   1478     if (gn->type & OP_SPECIAL)
   1479 	flags |= JOB_SPECIAL;
   1480 
   1481     job->node = gn;
   1482     job->tailCmds = NULL;
   1483 
   1484     /*
   1485      * Set the initial value of the flags for this job based on the global
   1486      * ones and the node's attributes... Any flags supplied by the caller
   1487      * are also added to the field.
   1488      */
   1489     job->flags = 0;
   1490     if (Targ_Ignore(gn)) {
   1491 	job->flags |= JOB_IGNERR;
   1492     }
   1493     if (Targ_Silent(gn)) {
   1494 	job->flags |= JOB_SILENT;
   1495     }
   1496     job->flags |= flags;
   1497 
   1498     /*
   1499      * Check the commands now so any attributes from .DEFAULT have a chance
   1500      * to migrate to the node
   1501      */
   1502     cmdsOK = Job_CheckCommands(gn, Error);
   1503 
   1504     job->inPollfd = NULL;
   1505     /*
   1506      * If the -n flag wasn't given, we open up OUR (not the child's)
   1507      * temporary file to stuff commands in it. The thing is rd/wr so we don't
   1508      * need to reopen it to feed it to the shell. If the -n flag *was* given,
   1509      * we just set the file to be stdout. Cute, huh?
   1510      */
   1511     if (((gn->type & OP_MAKE) && !(noRecursiveExecute)) ||
   1512 	    (!noExecute && !touchFlag)) {
   1513 	/*
   1514 	 * tfile is the name of a file into which all shell commands are
   1515 	 * put. It is removed before the child shell is executed, unless
   1516 	 * DEBUG(SCRIPT) is set.
   1517 	 */
   1518 	char *tfile;
   1519 	sigset_t mask;
   1520 	/*
   1521 	 * We're serious here, but if the commands were bogus, we're
   1522 	 * also dead...
   1523 	 */
   1524 	if (!cmdsOK) {
   1525 	    PrintOnError(gn, NULL);	/* provide some clue */
   1526 	    DieHorribly();
   1527 	}
   1528 
   1529 	JobSigLock(&mask);
   1530 	tfd = mkTempFile(TMPPAT, &tfile);
   1531 	if (!DEBUG(SCRIPT))
   1532 		(void)eunlink(tfile);
   1533 	JobSigUnlock(&mask);
   1534 
   1535 	job->cmdFILE = fdopen(tfd, "w+");
   1536 	if (job->cmdFILE == NULL) {
   1537 	    Punt("Could not fdopen %s", tfile);
   1538 	}
   1539 	(void)fcntl(fileno(job->cmdFILE), F_SETFD, FD_CLOEXEC);
   1540 	/*
   1541 	 * Send the commands to the command file, flush all its buffers then
   1542 	 * rewind and remove the thing.
   1543 	 */
   1544 	noExec = FALSE;
   1545 
   1546 #ifdef USE_META
   1547 	if (useMeta) {
   1548 	    meta_job_start(job, gn);
   1549 	    if (Targ_Silent(gn)) {	/* might have changed */
   1550 		job->flags |= JOB_SILENT;
   1551 	    }
   1552 	}
   1553 #endif
   1554 	/*
   1555 	 * We can do all the commands at once. hooray for sanity
   1556 	 */
   1557 	numCommands = 0;
   1558 	JobPrintCommands(job);
   1559 
   1560 	/*
   1561 	 * If we didn't print out any commands to the shell script,
   1562 	 * there's not much point in executing the shell, is there?
   1563 	 */
   1564 	if (numCommands == 0) {
   1565 	    noExec = TRUE;
   1566 	}
   1567 
   1568 	free(tfile);
   1569     } else if (NoExecute(gn)) {
   1570 	/*
   1571 	 * Not executing anything -- just print all the commands to stdout
   1572 	 * in one fell swoop. This will still set up job->tailCmds correctly.
   1573 	 */
   1574 	if (lastNode != gn) {
   1575 	    MESSAGE(stdout, gn);
   1576 	    lastNode = gn;
   1577 	}
   1578 	job->cmdFILE = stdout;
   1579 	/*
   1580 	 * Only print the commands if they're ok, but don't die if they're
   1581 	 * not -- just let the user know they're bad and keep going. It
   1582 	 * doesn't do any harm in this case and may do some good.
   1583 	 */
   1584 	if (cmdsOK)
   1585 	    JobPrintCommands(job);
   1586 	/*
   1587 	 * Don't execute the shell, thank you.
   1588 	 */
   1589 	noExec = TRUE;
   1590     } else {
   1591 	/*
   1592 	 * Just touch the target and note that no shell should be executed.
   1593 	 * Set cmdFILE to stdout to make life easier. Check the commands, too,
   1594 	 * but don't die if they're no good -- it does no harm to keep working
   1595 	 * up the graph.
   1596 	 */
   1597 	job->cmdFILE = stdout;
   1598 	Job_Touch(gn, job->flags&JOB_SILENT);
   1599 	noExec = TRUE;
   1600     }
   1601     /* Just in case it isn't already... */
   1602     (void)fflush(job->cmdFILE);
   1603 
   1604     /*
   1605      * If we're not supposed to execute a shell, don't.
   1606      */
   1607     if (noExec) {
   1608 	if (!(job->flags & JOB_SPECIAL))
   1609 	    Job_TokenReturn();
   1610 	/*
   1611 	 * Unlink and close the command file if we opened one
   1612 	 */
   1613 	if (job->cmdFILE != stdout) {
   1614 	    if (job->cmdFILE != NULL) {
   1615 		(void)fclose(job->cmdFILE);
   1616 		job->cmdFILE = NULL;
   1617 	    }
   1618 	}
   1619 
   1620 	/*
   1621 	 * We only want to work our way up the graph if we aren't here because
   1622 	 * the commands for the job were no good.
   1623 	 */
   1624 	if (cmdsOK && aborting == 0) {
   1625 	    JobSaveCommands(job);
   1626 	    job->node->made = MADE;
   1627 	    Make_Update(job->node);
   1628 	}
   1629 	job->job_state = JOB_ST_FREE;
   1630 	return cmdsOK ? JOB_FINISHED : JOB_ERROR;
   1631     }
   1632 
   1633     /*
   1634      * Set up the control arguments to the shell. This is based on the flags
   1635      * set earlier for this job.
   1636      */
   1637     JobMakeArgv(job, argv);
   1638 
   1639     /* Create the pipe by which we'll get the shell's output.  */
   1640     JobCreatePipe(job, 3);
   1641 
   1642     JobExec(job, argv);
   1643     return JOB_RUNNING;
   1644 }
   1645 
   1646 static char *
   1647 JobOutput(Job *job, char *cp, char *endp)
   1648 {
   1649     char *ecp;
   1650 
   1651     if (commandShell->noPrint && commandShell->noPrint[0] != '\0') {
   1652 	while ((ecp = strstr(cp, commandShell->noPrint)) != NULL) {
   1653 	    if (cp != ecp) {
   1654 		*ecp = '\0';
   1655 		/*
   1656 		 * The only way there wouldn't be a newline after
   1657 		 * this line is if it were the last in the buffer.
   1658 		 * however, since the non-printable comes after it,
   1659 		 * there must be a newline, so we don't print one.
   1660 		 */
   1661 		(void)fprintf(stdout, "%s", cp);
   1662 		(void)fflush(stdout);
   1663 	    }
   1664 	    cp = ecp + commandShell->noPrintLen;
   1665 	    if (cp != endp) {
   1666 		/*
   1667 		 * Still more to print, look again after skipping
   1668 		 * the whitespace following the non-printable
   1669 		 * command....
   1670 		 */
   1671 		cp++;
   1672 		while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
   1673 		    cp++;
   1674 		}
   1675 	    } else {
   1676 		return cp;
   1677 	    }
   1678 	}
   1679     }
   1680     return cp;
   1681 }
   1682 
   1683 /*-
   1684  *-----------------------------------------------------------------------
   1685  * JobDoOutput  --
   1686  *	This function is called at different times depending on
   1687  *	whether the user has specified that output is to be collected
   1688  *	via pipes or temporary files. In the former case, we are called
   1689  *	whenever there is something to read on the pipe. We collect more
   1690  *	output from the given job and store it in the job's outBuf. If
   1691  *	this makes up a line, we print it tagged by the job's identifier,
   1692  *	as necessary.
   1693  *	If output has been collected in a temporary file, we open the
   1694  *	file and read it line by line, transferring it to our own
   1695  *	output channel until the file is empty. At which point we
   1696  *	remove the temporary file.
   1697  *	In both cases, however, we keep our figurative eye out for the
   1698  *	'noPrint' line for the shell from which the output came. If
   1699  *	we recognize a line, we don't print it. If the command is not
   1700  *	alone on the line (the character after it is not \0 or \n), we
   1701  *	do print whatever follows it.
   1702  *
   1703  * Input:
   1704  *	job		the job whose output needs printing
   1705  *	finish		TRUE if this is the last time we'll be called
   1706  *			for this job
   1707  *
   1708  * Results:
   1709  *	None
   1710  *
   1711  * Side Effects:
   1712  *	curPos may be shifted as may the contents of outBuf.
   1713  *-----------------------------------------------------------------------
   1714  */
   1715 STATIC void
   1716 JobDoOutput(Job *job, Boolean finish)
   1717 {
   1718     Boolean gotNL = FALSE;	/* true if got a newline */
   1719     Boolean fbuf;		/* true if our buffer filled up */
   1720     size_t nr;			/* number of bytes read */
   1721     size_t i;			/* auxiliary index into outBuf */
   1722     size_t max;			/* limit for i (end of current data) */
   1723     ssize_t nRead;		/* (Temporary) number of bytes read */
   1724 
   1725     /*
   1726      * Read as many bytes as will fit in the buffer.
   1727      */
   1728 end_loop:
   1729     gotNL = FALSE;
   1730     fbuf = FALSE;
   1731 
   1732     nRead = read(job->inPipe, &job->outBuf[job->curPos],
   1733 		     JOB_BUFSIZE - job->curPos);
   1734     if (nRead < 0) {
   1735 	if (errno == EAGAIN)
   1736 	    return;
   1737 	if (DEBUG(JOB)) {
   1738 	    perror("JobDoOutput(piperead)");
   1739 	}
   1740 	nr = 0;
   1741     } else {
   1742 	nr = (size_t)nRead;
   1743     }
   1744 
   1745     /*
   1746      * If we hit the end-of-file (the job is dead), we must flush its
   1747      * remaining output, so pretend we read a newline if there's any
   1748      * output remaining in the buffer.
   1749      * Also clear the 'finish' flag so we stop looping.
   1750      */
   1751     if ((nr == 0) && (job->curPos != 0)) {
   1752 	job->outBuf[job->curPos] = '\n';
   1753 	nr = 1;
   1754 	finish = FALSE;
   1755     } else if (nr == 0) {
   1756 	finish = FALSE;
   1757     }
   1758 
   1759     /*
   1760      * Look for the last newline in the bytes we just got. If there is
   1761      * one, break out of the loop with 'i' as its index and gotNL set
   1762      * TRUE.
   1763      */
   1764     max = job->curPos + nr;
   1765     for (i = job->curPos + nr - 1; i >= job->curPos && i != (size_t)-1; i--) {
   1766 	if (job->outBuf[i] == '\n') {
   1767 	    gotNL = TRUE;
   1768 	    break;
   1769 	} else if (job->outBuf[i] == '\0') {
   1770 	    /*
   1771 	     * Why?
   1772 	     */
   1773 	    job->outBuf[i] = ' ';
   1774 	}
   1775     }
   1776 
   1777     if (!gotNL) {
   1778 	job->curPos += nr;
   1779 	if (job->curPos == JOB_BUFSIZE) {
   1780 	    /*
   1781 	     * If we've run out of buffer space, we have no choice
   1782 	     * but to print the stuff. sigh.
   1783 	     */
   1784 	    fbuf = TRUE;
   1785 	    i = job->curPos;
   1786 	}
   1787     }
   1788     if (gotNL || fbuf) {
   1789 	/*
   1790 	 * Need to send the output to the screen. Null terminate it
   1791 	 * first, overwriting the newline character if there was one.
   1792 	 * So long as the line isn't one we should filter (according
   1793 	 * to the shell description), we print the line, preceded
   1794 	 * by a target banner if this target isn't the same as the
   1795 	 * one for which we last printed something.
   1796 	 * The rest of the data in the buffer are then shifted down
   1797 	 * to the start of the buffer and curPos is set accordingly.
   1798 	 */
   1799 	job->outBuf[i] = '\0';
   1800 	if (i >= job->curPos) {
   1801 	    char *cp;
   1802 
   1803 	    cp = JobOutput(job, job->outBuf, &job->outBuf[i]);
   1804 
   1805 	    /*
   1806 	     * There's still more in that thar buffer. This time, though,
   1807 	     * we know there's no newline at the end, so we add one of
   1808 	     * our own free will.
   1809 	     */
   1810 	    if (*cp != '\0') {
   1811 		if (!beSilent && job->node != lastNode) {
   1812 		    MESSAGE(stdout, job->node);
   1813 		    lastNode = job->node;
   1814 		}
   1815 #ifdef USE_META
   1816 		if (useMeta) {
   1817 		    meta_job_output(job, cp, gotNL ? "\n" : "");
   1818 		}
   1819 #endif
   1820 		(void)fprintf(stdout, "%s%s", cp, gotNL ? "\n" : "");
   1821 		(void)fflush(stdout);
   1822 	    }
   1823 	}
   1824 	/*
   1825 	 * max is the last offset still in the buffer. Move any remaining
   1826 	 * characters to the start of the buffer and update the end marker
   1827 	 * curPos.
   1828 	 */
   1829 	if (i < max) {
   1830 	    (void)memmove(job->outBuf, &job->outBuf[i + 1], max - (i + 1));
   1831 	    job->curPos = max - (i + 1);
   1832 	} else {
   1833 	    assert(i == max);
   1834 	    job->curPos = 0;
   1835 	}
   1836     }
   1837     if (finish) {
   1838 	/*
   1839 	 * If the finish flag is true, we must loop until we hit
   1840 	 * end-of-file on the pipe. This is guaranteed to happen
   1841 	 * eventually since the other end of the pipe is now closed
   1842 	 * (we closed it explicitly and the child has exited). When
   1843 	 * we do get an EOF, finish will be set FALSE and we'll fall
   1844 	 * through and out.
   1845 	 */
   1846 	goto end_loop;
   1847     }
   1848 }
   1849 
   1850 static void
   1851 JobRun(GNode *targ)
   1852 {
   1853 #if 0
   1854     /*
   1855      * Unfortunately it is too complicated to run .BEGIN, .END, and
   1856      * .INTERRUPT job in the parallel job module.  As of 2020-09-25,
   1857      * unit-tests/deptgt-end-jobs.mk hangs in an endless loop.
   1858      *
   1859      * Running these jobs in compat mode also guarantees that these
   1860      * jobs do not overlap with other unrelated jobs.
   1861      */
   1862     List *lst = Lst_New();
   1863     Lst_Append(lst, targ);
   1864     (void)Make_Run(lst);
   1865     Lst_Destroy(lst, NULL);
   1866     JobStart(targ, JOB_SPECIAL);
   1867     while (jobTokensRunning) {
   1868 	Job_CatchOutput();
   1869     }
   1870 #else
   1871     Compat_Make(targ, targ);
   1872     if (targ->made == ERROR) {
   1873 	PrintOnError(targ, "\n\nStop.");
   1874 	exit(1);
   1875     }
   1876 #endif
   1877 }
   1878 
   1879 /* Handle the exit of a child. Called from Make_Make.
   1880  *
   1881  * The job descriptor is removed from the list of children.
   1882  *
   1883  * Notes:
   1884  *	We do waits, blocking or not, according to the wisdom of our
   1885  *	caller, until there are no more children to report. For each
   1886  *	job, call JobFinish to finish things off.
   1887  */
   1888 void
   1889 Job_CatchChildren(void)
   1890 {
   1891     int pid;			/* pid of dead child */
   1892     int status;			/* Exit/termination status */
   1893 
   1894     /*
   1895      * Don't even bother if we know there's no one around.
   1896      */
   1897     if (jobTokensRunning == 0)
   1898 	return;
   1899 
   1900     while ((pid = waitpid((pid_t) -1, &status, WNOHANG | WUNTRACED)) > 0) {
   1901 	DEBUG2(JOB, "Process %d exited/stopped status %x.\n", pid, status);
   1902 	JobReapChild(pid, status, TRUE);
   1903     }
   1904 }
   1905 
   1906 /*
   1907  * It is possible that wait[pid]() was called from elsewhere,
   1908  * this lets us reap jobs regardless.
   1909  */
   1910 void
   1911 JobReapChild(pid_t pid, int status, Boolean isJobs)
   1912 {
   1913     Job *job;			/* job descriptor for dead child */
   1914 
   1915     /*
   1916      * Don't even bother if we know there's no one around.
   1917      */
   1918     if (jobTokensRunning == 0)
   1919 	return;
   1920 
   1921     job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
   1922     if (job == NULL) {
   1923 	if (isJobs) {
   1924 	    if (!lurking_children)
   1925 		Error("Child (%d) status %x not in table?", pid, status);
   1926 	}
   1927 	return;				/* not ours */
   1928     }
   1929     if (WIFSTOPPED(status)) {
   1930 	DEBUG2(JOB, "Process %d (%s) stopped.\n", job->pid, job->node->name);
   1931 	if (!make_suspended) {
   1932 	    switch (WSTOPSIG(status)) {
   1933 	    case SIGTSTP:
   1934 		(void)printf("*** [%s] Suspended\n", job->node->name);
   1935 		break;
   1936 	    case SIGSTOP:
   1937 		(void)printf("*** [%s] Stopped\n", job->node->name);
   1938 		break;
   1939 	    default:
   1940 		(void)printf("*** [%s] Stopped -- signal %d\n",
   1941 			     job->node->name, WSTOPSIG(status));
   1942 	    }
   1943 	    job->job_suspended = 1;
   1944 	}
   1945 	(void)fflush(stdout);
   1946 	return;
   1947     }
   1948 
   1949     job->job_state = JOB_ST_FINISHED;
   1950     job->exit_status = status;
   1951 
   1952     JobFinish(job, status);
   1953 }
   1954 
   1955 /* Catch the output from our children, if we're using pipes do so. Otherwise
   1956  * just block time until we get a signal(most likely a SIGCHLD) since there's
   1957  * no point in just spinning when there's nothing to do and the reaping of a
   1958  * child can wait for a while. */
   1959 void
   1960 Job_CatchOutput(void)
   1961 {
   1962     int nready;
   1963     Job *job;
   1964     unsigned int i;
   1965 
   1966     (void)fflush(stdout);
   1967 
   1968     /* The first fd in the list is the job token pipe */
   1969     do {
   1970 	nready = poll(fds + 1 - wantToken, nfds - 1 + wantToken, POLL_MSEC);
   1971     } while (nready < 0 && errno == EINTR);
   1972 
   1973     if (nready < 0)
   1974 	Punt("poll: %s", strerror(errno));
   1975 
   1976     if (nready > 0 && readyfd(&childExitJob)) {
   1977 	char token = 0;
   1978 	ssize_t count;
   1979 	count = read(childExitJob.inPipe, &token, 1);
   1980 	switch (count) {
   1981 	case 0:
   1982 	    Punt("unexpected eof on token pipe");
   1983 	case -1:
   1984 	    Punt("token pipe read: %s", strerror(errno));
   1985 	case 1:
   1986 	    if (token == DO_JOB_RESUME[0])
   1987 		/* Complete relay requested from our SIGCONT handler */
   1988 		JobRestartJobs();
   1989 	    break;
   1990 	default:
   1991 	    abort();
   1992 	}
   1993 	--nready;
   1994     }
   1995 
   1996     Job_CatchChildren();
   1997     if (nready == 0)
   1998 	return;
   1999 
   2000     for (i = npseudojobs * nfds_per_job(); i < nfds; i++) {
   2001 	if (!fds[i].revents)
   2002 	    continue;
   2003 	job = jobfds[i];
   2004 	if (job->job_state == JOB_ST_RUNNING)
   2005 	    JobDoOutput(job, FALSE);
   2006 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
   2007 	/*
   2008 	 * With meta mode, we may have activity on the job's filemon
   2009 	 * descriptor too, which at the moment is any pollfd other than
   2010 	 * job->inPollfd.
   2011 	 */
   2012 	if (useMeta && job->inPollfd != &fds[i]) {
   2013 	    if (meta_job_event(job) <= 0) {
   2014 		fds[i].events = 0; /* never mind */
   2015 	    }
   2016 	}
   2017 #endif
   2018 	if (--nready == 0)
   2019 	    return;
   2020     }
   2021 }
   2022 
   2023 /* Start the creation of a target. Basically a front-end for JobStart used by
   2024  * the Make module. */
   2025 void
   2026 Job_Make(GNode *gn)
   2027 {
   2028     (void)JobStart(gn, 0);
   2029 }
   2030 
   2031 void
   2032 Shell_Init(void)
   2033 {
   2034     if (shellPath == NULL) {
   2035 	/*
   2036 	 * We are using the default shell, which may be an absolute
   2037 	 * path if DEFSHELL_CUSTOM is defined.
   2038 	 */
   2039 	shellName = commandShell->name;
   2040 #ifdef DEFSHELL_CUSTOM
   2041 	if (*shellName == '/') {
   2042 	    shellPath = shellName;
   2043 	    shellName = strrchr(shellPath, '/');
   2044 	    shellName++;
   2045 	} else
   2046 #endif
   2047 	shellPath = str_concat3(_PATH_DEFSHELLDIR, "/", shellName);
   2048     }
   2049     Var_Set_with_flags(".SHELL", shellPath, VAR_CMD, VAR_SET_READONLY);
   2050     if (commandShell->exit == NULL) {
   2051 	commandShell->exit = "";
   2052     }
   2053     if (commandShell->echo == NULL) {
   2054 	commandShell->echo = "";
   2055     }
   2056     if (commandShell->hasErrCtl && commandShell->exit[0] != '\0') {
   2057 	if (shellErrFlag &&
   2058 	    strcmp(commandShell->exit, &shellErrFlag[1]) != 0) {
   2059 	    free(shellErrFlag);
   2060 	    shellErrFlag = NULL;
   2061 	}
   2062 	if (!shellErrFlag) {
   2063 	    size_t n = strlen(commandShell->exit) + 2;
   2064 
   2065 	    shellErrFlag = bmake_malloc(n);
   2066 	    if (shellErrFlag) {
   2067 		snprintf(shellErrFlag, n, "-%s", commandShell->exit);
   2068 	    }
   2069 	}
   2070     } else if (shellErrFlag) {
   2071 	free(shellErrFlag);
   2072 	shellErrFlag = NULL;
   2073     }
   2074 }
   2075 
   2076 /* Return the string literal that is used in the current command shell
   2077  * to produce a newline character. */
   2078 const char *
   2079 Shell_GetNewline(void)
   2080 {
   2081     return commandShell->newline;
   2082 }
   2083 
   2084 void
   2085 Job_SetPrefix(void)
   2086 {
   2087     if (targPrefix) {
   2088 	free(targPrefix);
   2089     } else if (!Var_Exists(MAKE_JOB_PREFIX, VAR_GLOBAL)) {
   2090 	Var_Set(MAKE_JOB_PREFIX, "---", VAR_GLOBAL);
   2091     }
   2092 
   2093     (void)Var_Subst("${" MAKE_JOB_PREFIX "}",
   2094 		    VAR_GLOBAL, VARE_WANTRES, &targPrefix);
   2095     /* TODO: handle errors */
   2096 }
   2097 
   2098 /* Initialize the process module. */
   2099 void
   2100 Job_Init(void)
   2101 {
   2102     Job_SetPrefix();
   2103     /* Allocate space for all the job info */
   2104     job_table = bmake_malloc((size_t)maxJobs * sizeof *job_table);
   2105     memset(job_table, 0, (size_t)maxJobs * sizeof *job_table);
   2106     job_table_end = job_table + maxJobs;
   2107     wantToken =	0;
   2108 
   2109     aborting = 0;
   2110     errors = 0;
   2111 
   2112     lastNode = NULL;
   2113 
   2114     /*
   2115      * There is a non-zero chance that we already have children.
   2116      * eg after 'make -f- <<EOF'
   2117      * Since their termination causes a 'Child (pid) not in table' message,
   2118      * Collect the status of any that are already dead, and suppress the
   2119      * error message if there are any undead ones.
   2120      */
   2121     for (;;) {
   2122 	int rval, status;
   2123 	rval = waitpid((pid_t) -1, &status, WNOHANG);
   2124 	if (rval > 0)
   2125 	    continue;
   2126 	if (rval == 0)
   2127 	    lurking_children = 1;
   2128 	break;
   2129     }
   2130 
   2131     Shell_Init();
   2132 
   2133     JobCreatePipe(&childExitJob, 3);
   2134 
   2135     /* Preallocate enough for the maximum number of jobs.  */
   2136     fds = bmake_malloc(sizeof(*fds) *
   2137 	(npseudojobs + (size_t)maxJobs) * nfds_per_job());
   2138     jobfds = bmake_malloc(sizeof(*jobfds) *
   2139 	(npseudojobs + (size_t)maxJobs) * nfds_per_job());
   2140 
   2141     /* These are permanent entries and take slots 0 and 1 */
   2142     watchfd(&tokenWaitJob);
   2143     watchfd(&childExitJob);
   2144 
   2145     sigemptyset(&caught_signals);
   2146     /*
   2147      * Install a SIGCHLD handler.
   2148      */
   2149     (void)bmake_signal(SIGCHLD, JobChildSig);
   2150     sigaddset(&caught_signals, SIGCHLD);
   2151 
   2152 #define ADDSIG(s,h)				\
   2153     if (bmake_signal(s, SIG_IGN) != SIG_IGN) {	\
   2154 	sigaddset(&caught_signals, s);		\
   2155 	(void)bmake_signal(s, h);			\
   2156     }
   2157 
   2158     /*
   2159      * Catch the four signals that POSIX specifies if they aren't ignored.
   2160      * JobPassSig will take care of calling JobInterrupt if appropriate.
   2161      */
   2162     ADDSIG(SIGINT, JobPassSig_int)
   2163     ADDSIG(SIGHUP, JobPassSig_term)
   2164     ADDSIG(SIGTERM, JobPassSig_term)
   2165     ADDSIG(SIGQUIT, JobPassSig_term)
   2166 
   2167     /*
   2168      * There are additional signals that need to be caught and passed if
   2169      * either the export system wants to be told directly of signals or if
   2170      * we're giving each job its own process group (since then it won't get
   2171      * signals from the terminal driver as we own the terminal)
   2172      */
   2173     ADDSIG(SIGTSTP, JobPassSig_suspend)
   2174     ADDSIG(SIGTTOU, JobPassSig_suspend)
   2175     ADDSIG(SIGTTIN, JobPassSig_suspend)
   2176     ADDSIG(SIGWINCH, JobCondPassSig)
   2177     ADDSIG(SIGCONT, JobContinueSig)
   2178 #undef ADDSIG
   2179 
   2180     (void)Job_RunTarget(".BEGIN", NULL);
   2181     /* Create the .END node now, even though no code in the unit tests
   2182      * depends on it.  See also Targ_GetEndNode in Compat_Run. */
   2183     (void)Targ_GetEndNode();
   2184 }
   2185 
   2186 static void JobSigReset(void)
   2187 {
   2188 #define DELSIG(s)					\
   2189     if (sigismember(&caught_signals, s)) {		\
   2190 	(void)bmake_signal(s, SIG_DFL);			\
   2191     }
   2192 
   2193     DELSIG(SIGINT)
   2194     DELSIG(SIGHUP)
   2195     DELSIG(SIGQUIT)
   2196     DELSIG(SIGTERM)
   2197     DELSIG(SIGTSTP)
   2198     DELSIG(SIGTTOU)
   2199     DELSIG(SIGTTIN)
   2200     DELSIG(SIGWINCH)
   2201     DELSIG(SIGCONT)
   2202 #undef DELSIG
   2203     (void)bmake_signal(SIGCHLD, SIG_DFL);
   2204 }
   2205 
   2206 /* Find a shell in 'shells' given its name, or return NULL. */
   2207 static Shell *
   2208 JobMatchShell(const char *name)
   2209 {
   2210     Shell	*sh;
   2211 
   2212     for (sh = shells; sh->name != NULL; sh++) {
   2213 	if (strcmp(name, sh->name) == 0)
   2214 		return sh;
   2215     }
   2216     return NULL;
   2217 }
   2218 
   2219 /*-
   2220  *-----------------------------------------------------------------------
   2221  * Job_ParseShell --
   2222  *	Parse a shell specification and set up commandShell, shellPath
   2223  *	and shellName appropriately.
   2224  *
   2225  * Input:
   2226  *	line		The shell spec
   2227  *
   2228  * Results:
   2229  *	FALSE if the specification was incorrect.
   2230  *
   2231  * Side Effects:
   2232  *	commandShell points to a Shell structure (either predefined or
   2233  *	created from the shell spec), shellPath is the full path of the
   2234  *	shell described by commandShell, while shellName is just the
   2235  *	final component of shellPath.
   2236  *
   2237  * Notes:
   2238  *	A shell specification consists of a .SHELL target, with dependency
   2239  *	operator, followed by a series of blank-separated words. Double
   2240  *	quotes can be used to use blanks in words. A backslash escapes
   2241  *	anything (most notably a double-quote and a space) and
   2242  *	provides the functionality it does in C. Each word consists of
   2243  *	keyword and value separated by an equal sign. There should be no
   2244  *	unnecessary spaces in the word. The keywords are as follows:
   2245  *	    name	Name of shell.
   2246  *	    path	Location of shell.
   2247  *	    quiet	Command to turn off echoing.
   2248  *	    echo	Command to turn echoing on
   2249  *	    filter	Result of turning off echoing that shouldn't be
   2250  *			printed.
   2251  *	    echoFlag	Flag to turn echoing on at the start
   2252  *	    errFlag	Flag to turn error checking on at the start
   2253  *	    hasErrCtl	True if shell has error checking control
   2254  *	    newline	String literal to represent a newline char
   2255  *	    check	Command to turn on error checking if hasErrCtl
   2256  *			is TRUE or template of command to echo a command
   2257  *			for which error checking is off if hasErrCtl is
   2258  *			FALSE.
   2259  *	    ignore	Command to turn off error checking if hasErrCtl
   2260  *			is TRUE or template of command to execute a
   2261  *			command so as to ignore any errors it returns if
   2262  *			hasErrCtl is FALSE.
   2263  *
   2264  *-----------------------------------------------------------------------
   2265  */
   2266 Boolean
   2267 Job_ParseShell(char *line)
   2268 {
   2269     Words	wordsList;
   2270     char	**words;
   2271     char	**argv;
   2272     size_t	argc;
   2273     char	*path;
   2274     Shell	newShell;
   2275     Boolean	fullSpec = FALSE;
   2276     Shell	*sh;
   2277 
   2278     pp_skip_whitespace(&line);
   2279 
   2280     free(shellArgv);
   2281 
   2282     memset(&newShell, 0, sizeof(newShell));
   2283 
   2284     /*
   2285      * Parse the specification by keyword
   2286      */
   2287     wordsList = Str_Words(line, TRUE);
   2288     words = wordsList.words;
   2289     argc = wordsList.len;
   2290     path = wordsList.freeIt;
   2291     if (words == NULL) {
   2292 	Error("Unterminated quoted string [%s]", line);
   2293 	return FALSE;
   2294     }
   2295     shellArgv = path;
   2296 
   2297     for (path = NULL, argv = words; argc != 0; argc--, argv++) {
   2298 	char *arg = *argv;
   2299 	if (strncmp(arg, "path=", 5) == 0) {
   2300 	    path = arg + 5;
   2301 	} else if (strncmp(arg, "name=", 5) == 0) {
   2302 	    newShell.name = arg + 5;
   2303 	} else {
   2304 	    if (strncmp(arg, "quiet=", 6) == 0) {
   2305 		newShell.echoOff = arg + 6;
   2306 	    } else if (strncmp(arg, "echo=", 5) == 0) {
   2307 		newShell.echoOn = arg + 5;
   2308 	    } else if (strncmp(arg, "filter=", 7) == 0) {
   2309 		newShell.noPrint = arg + 7;
   2310 		newShell.noPrintLen = strlen(newShell.noPrint);
   2311 	    } else if (strncmp(arg, "echoFlag=", 9) == 0) {
   2312 		newShell.echo = arg + 9;
   2313 	    } else if (strncmp(arg, "errFlag=", 8) == 0) {
   2314 		newShell.exit = arg + 8;
   2315 	    } else if (strncmp(arg, "hasErrCtl=", 10) == 0) {
   2316 		char c = arg[10];
   2317 		newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
   2318 				       (c != 'T') && (c != 't'));
   2319 	    } else if (strncmp(arg, "newline=", 8) == 0) {
   2320 		newShell.newline = arg + 8;
   2321 	    } else if (strncmp(arg, "check=", 6) == 0) {
   2322 		newShell.errCheck = arg + 6;
   2323 	    } else if (strncmp(arg, "ignore=", 7) == 0) {
   2324 		newShell.ignErr = arg + 7;
   2325 	    } else if (strncmp(arg, "errout=", 7) == 0) {
   2326 		newShell.errOut = arg + 7;
   2327 	    } else if (strncmp(arg, "comment=", 8) == 0) {
   2328 		newShell.commentChar = arg[8];
   2329 	    } else {
   2330 		Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"", arg);
   2331 		free(words);
   2332 		return FALSE;
   2333 	    }
   2334 	    fullSpec = TRUE;
   2335 	}
   2336     }
   2337 
   2338     if (path == NULL) {
   2339 	/*
   2340 	 * If no path was given, the user wants one of the pre-defined shells,
   2341 	 * yes? So we find the one s/he wants with the help of JobMatchShell
   2342 	 * and set things up the right way. shellPath will be set up by
   2343 	 * Shell_Init.
   2344 	 */
   2345 	if (newShell.name == NULL) {
   2346 	    Parse_Error(PARSE_FATAL, "Neither path nor name specified");
   2347 	    free(words);
   2348 	    return FALSE;
   2349 	} else {
   2350 	    if ((sh = JobMatchShell(newShell.name)) == NULL) {
   2351 		    Parse_Error(PARSE_WARNING, "%s: No matching shell",
   2352 				newShell.name);
   2353 		    free(words);
   2354 		    return FALSE;
   2355 	    }
   2356 	    commandShell = sh;
   2357 	    shellName = newShell.name;
   2358 	    if (shellPath) {
   2359 		/* Shell_Init has already been called!  Do it again. */
   2360 		free(UNCONST(shellPath));
   2361 		shellPath = NULL;
   2362 		Shell_Init();
   2363 	    }
   2364 	}
   2365     } else {
   2366 	/*
   2367 	 * The user provided a path. If s/he gave nothing else (fullSpec is
   2368 	 * FALSE), try and find a matching shell in the ones we know of.
   2369 	 * Else we just take the specification at its word and copy it
   2370 	 * to a new location. In either case, we need to record the
   2371 	 * path the user gave for the shell.
   2372 	 */
   2373 	shellPath = path;
   2374 	path = strrchr(path, '/');
   2375 	if (path == NULL) {
   2376 	    path = UNCONST(shellPath);
   2377 	} else {
   2378 	    path++;
   2379 	}
   2380 	if (newShell.name != NULL) {
   2381 	    shellName = newShell.name;
   2382 	} else {
   2383 	    shellName = path;
   2384 	}
   2385 	if (!fullSpec) {
   2386 	    if ((sh = JobMatchShell(shellName)) == NULL) {
   2387 		    Parse_Error(PARSE_WARNING, "%s: No matching shell",
   2388 				shellName);
   2389 		    free(words);
   2390 		    return FALSE;
   2391 	    }
   2392 	    commandShell = sh;
   2393 	} else {
   2394 	    commandShell = bmake_malloc(sizeof(Shell));
   2395 	    *commandShell = newShell;
   2396 	}
   2397 	/* this will take care of shellErrFlag */
   2398 	Shell_Init();
   2399     }
   2400 
   2401     if (commandShell->echoOn && commandShell->echoOff) {
   2402 	commandShell->hasEchoCtl = TRUE;
   2403     }
   2404 
   2405     if (!commandShell->hasErrCtl) {
   2406 	if (commandShell->errCheck == NULL) {
   2407 	    commandShell->errCheck = "";
   2408 	}
   2409 	if (commandShell->ignErr == NULL) {
   2410 	    commandShell->ignErr = "%s\n";
   2411 	}
   2412     }
   2413 
   2414     /*
   2415      * Do not free up the words themselves, since they might be in use by the
   2416      * shell specification.
   2417      */
   2418     free(words);
   2419     return TRUE;
   2420 }
   2421 
   2422 /* Handle the receipt of an interrupt.
   2423  *
   2424  * All children are killed. Another job will be started if the .INTERRUPT
   2425  * target is defined.
   2426  *
   2427  * Input:
   2428  *	runINTERRUPT	Non-zero if commands for the .INTERRUPT target
   2429  *			should be executed
   2430  *	signo		signal received
   2431  */
   2432 static void
   2433 JobInterrupt(int runINTERRUPT, int signo)
   2434 {
   2435     Job		*job;		/* job descriptor in that element */
   2436     GNode	*interrupt;	/* the node describing the .INTERRUPT target */
   2437     sigset_t	mask;
   2438     GNode	*gn;
   2439 
   2440     aborting = ABORT_INTERRUPT;
   2441 
   2442     JobSigLock(&mask);
   2443 
   2444     for (job = job_table; job < job_table_end; job++) {
   2445 	if (job->job_state != JOB_ST_RUNNING)
   2446 	    continue;
   2447 
   2448 	gn = job->node;
   2449 
   2450 	JobDeleteTarget(gn);
   2451 	if (job->pid) {
   2452 	    DEBUG2(JOB, "JobInterrupt passing signal %d to child %d.\n",
   2453 		   signo, job->pid);
   2454 	    KILLPG(job->pid, signo);
   2455 	}
   2456     }
   2457 
   2458     JobSigUnlock(&mask);
   2459 
   2460     if (runINTERRUPT && !touchFlag) {
   2461 	interrupt = Targ_FindNode(".INTERRUPT");
   2462 	if (interrupt != NULL) {
   2463 	    ignoreErrors = FALSE;
   2464 	    JobRun(interrupt);
   2465 	}
   2466     }
   2467     Trace_Log(MAKEINTR, 0);
   2468     exit(signo);
   2469 }
   2470 
   2471 /* Do the final processing, i.e. run the commands attached to the .END target.
   2472  *
   2473  * Return the number of errors reported. */
   2474 int
   2475 Job_Finish(void)
   2476 {
   2477     GNode *endNode = Targ_GetEndNode();
   2478     if (!Lst_IsEmpty(endNode->commands) || !Lst_IsEmpty(endNode->children)) {
   2479 	if (errors) {
   2480 	    Error("Errors reported so .END ignored");
   2481 	} else {
   2482 	    JobRun(endNode);
   2483 	}
   2484     }
   2485     return errors;
   2486 }
   2487 
   2488 /* Clean up any memory used by the jobs module. */
   2489 void
   2490 Job_End(void)
   2491 {
   2492 #ifdef CLEANUP
   2493     free(shellArgv);
   2494 #endif
   2495 }
   2496 
   2497 /* Waits for all running jobs to finish and returns.
   2498  * Sets 'aborting' to ABORT_WAIT to prevent other jobs from starting. */
   2499 void
   2500 Job_Wait(void)
   2501 {
   2502     aborting = ABORT_WAIT;
   2503     while (jobTokensRunning != 0) {
   2504 	Job_CatchOutput();
   2505     }
   2506     aborting = 0;
   2507 }
   2508 
   2509 /* Abort all currently running jobs without handling output or anything.
   2510  * This function is to be called only in the event of a major error.
   2511  * Most definitely NOT to be called from JobInterrupt.
   2512  *
   2513  * All children are killed, not just the firstborn. */
   2514 void
   2515 Job_AbortAll(void)
   2516 {
   2517     Job		*job;	/* the job descriptor in that element */
   2518     int		foo;
   2519 
   2520     aborting = ABORT_ERROR;
   2521 
   2522     if (jobTokensRunning) {
   2523 	for (job = job_table; job < job_table_end; job++) {
   2524 	    if (job->job_state != JOB_ST_RUNNING)
   2525 		continue;
   2526 	    /*
   2527 	     * kill the child process with increasingly drastic signals to make
   2528 	     * darn sure it's dead.
   2529 	     */
   2530 	    KILLPG(job->pid, SIGINT);
   2531 	    KILLPG(job->pid, SIGKILL);
   2532 	}
   2533     }
   2534 
   2535     /*
   2536      * Catch as many children as want to report in at first, then give up
   2537      */
   2538     while (waitpid((pid_t) -1, &foo, WNOHANG) > 0)
   2539 	continue;
   2540 }
   2541 
   2542 /* Tries to restart stopped jobs if there are slots available.
   2543  * Called in process context in response to a SIGCONT. */
   2544 static void
   2545 JobRestartJobs(void)
   2546 {
   2547     Job *job;
   2548 
   2549     for (job = job_table; job < job_table_end; job++) {
   2550 	if (job->job_state == JOB_ST_RUNNING &&
   2551 		(make_suspended || job->job_suspended)) {
   2552 	    DEBUG1(JOB, "Restarting stopped job pid %d.\n", job->pid);
   2553 	    if (job->job_suspended) {
   2554 		    (void)printf("*** [%s] Continued\n", job->node->name);
   2555 		    (void)fflush(stdout);
   2556 	    }
   2557 	    job->job_suspended = 0;
   2558 	    if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
   2559 		debug_printf("Failed to send SIGCONT to %d\n", job->pid);
   2560 	    }
   2561 	}
   2562 	if (job->job_state == JOB_ST_FINISHED)
   2563 	    /* Job exit deferred after calling waitpid() in a signal handler */
   2564 	    JobFinish(job, job->exit_status);
   2565     }
   2566     make_suspended = 0;
   2567 }
   2568 
   2569 static void
   2570 watchfd(Job *job)
   2571 {
   2572     if (job->inPollfd != NULL)
   2573 	Punt("Watching watched job");
   2574 
   2575     fds[nfds].fd = job->inPipe;
   2576     fds[nfds].events = POLLIN;
   2577     jobfds[nfds] = job;
   2578     job->inPollfd = &fds[nfds];
   2579     nfds++;
   2580 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
   2581     if (useMeta) {
   2582 	fds[nfds].fd = meta_job_fd(job);
   2583 	fds[nfds].events = fds[nfds].fd == -1 ? 0 : POLLIN;
   2584 	jobfds[nfds] = job;
   2585 	nfds++;
   2586     }
   2587 #endif
   2588 }
   2589 
   2590 static void
   2591 clearfd(Job *job)
   2592 {
   2593     size_t i;
   2594     if (job->inPollfd == NULL)
   2595 	Punt("Unwatching unwatched job");
   2596     i = (size_t)(job->inPollfd - fds);
   2597     nfds--;
   2598 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
   2599     if (useMeta) {
   2600 	/*
   2601 	 * Sanity check: there should be two fds per job, so the job's
   2602 	 * pollfd number should be even.
   2603 	 */
   2604 	assert(nfds_per_job() == 2);
   2605 	if (i % 2)
   2606 	    Punt("odd-numbered fd with meta");
   2607 	nfds--;
   2608     }
   2609 #endif
   2610     /*
   2611      * Move last job in table into hole made by dead job.
   2612      */
   2613     if (nfds != i) {
   2614 	fds[i] = fds[nfds];
   2615 	jobfds[i] = jobfds[nfds];
   2616 	jobfds[i]->inPollfd = &fds[i];
   2617 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
   2618 	if (useMeta) {
   2619 	    fds[i + 1] = fds[nfds + 1];
   2620 	    jobfds[i + 1] = jobfds[nfds + 1];
   2621 	}
   2622 #endif
   2623     }
   2624     job->inPollfd = NULL;
   2625 }
   2626 
   2627 static int
   2628 readyfd(Job *job)
   2629 {
   2630     if (job->inPollfd == NULL)
   2631 	Punt("Polling unwatched job");
   2632     return (job->inPollfd->revents & POLLIN) != 0;
   2633 }
   2634 
   2635 /* Put a token (back) into the job pipe.
   2636  * This allows a make process to start a build job. */
   2637 static void
   2638 JobTokenAdd(void)
   2639 {
   2640     char tok = JOB_TOKENS[aborting], tok1;
   2641 
   2642     /* If we are depositing an error token flush everything else */
   2643     while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
   2644 	continue;
   2645 
   2646     DEBUG3(JOB, "(%d) aborting %d, deposit token %c\n",
   2647 	   getpid(), aborting, JOB_TOKENS[aborting]);
   2648     while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
   2649 	continue;
   2650 }
   2651 
   2652 /* Prep the job token pipe in the root make process. */
   2653 void
   2654 Job_ServerStart(int max_tokens, int jp_0, int jp_1)
   2655 {
   2656     int i;
   2657     char jobarg[64];
   2658 
   2659     if (jp_0 >= 0 && jp_1 >= 0) {
   2660 	/* Pipe passed in from parent */
   2661 	tokenWaitJob.inPipe = jp_0;
   2662 	tokenWaitJob.outPipe = jp_1;
   2663 	(void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
   2664 	(void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
   2665 	return;
   2666     }
   2667 
   2668     JobCreatePipe(&tokenWaitJob, 15);
   2669 
   2670     snprintf(jobarg, sizeof(jobarg), "%d,%d",
   2671 	    tokenWaitJob.inPipe, tokenWaitJob.outPipe);
   2672 
   2673     Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
   2674     Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
   2675 
   2676     /*
   2677      * Preload the job pipe with one token per job, save the one
   2678      * "extra" token for the primary job.
   2679      *
   2680      * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
   2681      * larger than the write buffer size of the pipe, we will
   2682      * deadlock here.
   2683      */
   2684     for (i = 1; i < max_tokens; i++)
   2685 	JobTokenAdd();
   2686 }
   2687 
   2688 /* Return a withdrawn token to the pool. */
   2689 void
   2690 Job_TokenReturn(void)
   2691 {
   2692     jobTokensRunning--;
   2693     if (jobTokensRunning < 0)
   2694 	Punt("token botch");
   2695     if (jobTokensRunning || JOB_TOKENS[aborting] != '+')
   2696 	JobTokenAdd();
   2697 }
   2698 
   2699 /* Attempt to withdraw a token from the pool.
   2700  *
   2701  * If pool is empty, set wantToken so that we wake up when a token is
   2702  * released.
   2703  *
   2704  * Returns TRUE if a token was withdrawn, and FALSE if the pool is currently
   2705  * empty. */
   2706 Boolean
   2707 Job_TokenWithdraw(void)
   2708 {
   2709     char tok, tok1;
   2710     ssize_t count;
   2711 
   2712     wantToken = 0;
   2713     DEBUG3(JOB, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
   2714 	   getpid(), aborting, jobTokensRunning);
   2715 
   2716     if (aborting || (jobTokensRunning >= maxJobs))
   2717 	return FALSE;
   2718 
   2719     count = read(tokenWaitJob.inPipe, &tok, 1);
   2720     if (count == 0)
   2721 	Fatal("eof on job pipe!");
   2722     if (count < 0 && jobTokensRunning != 0) {
   2723 	if (errno != EAGAIN) {
   2724 	    Fatal("job pipe read: %s", strerror(errno));
   2725 	}
   2726 	DEBUG1(JOB, "(%d) blocked for token\n", getpid());
   2727 	return FALSE;
   2728     }
   2729 
   2730     if (count == 1 && tok != '+') {
   2731 	/* make being abvorted - remove any other job tokens */
   2732 	DEBUG2(JOB, "(%d) aborted by token %c\n", getpid(), tok);
   2733 	while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
   2734 	    continue;
   2735 	/* And put the stopper back */
   2736 	while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
   2737 	    continue;
   2738 	if (dieQuietly(NULL, 1))
   2739 	    exit(2);
   2740 	Fatal("A failure has been detected in another branch of the parallel make");
   2741     }
   2742 
   2743     if (count == 1 && jobTokensRunning == 0)
   2744 	/* We didn't want the token really */
   2745 	while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
   2746 	    continue;
   2747 
   2748     jobTokensRunning++;
   2749     DEBUG1(JOB, "(%d) withdrew token\n", getpid());
   2750     return TRUE;
   2751 }
   2752 
   2753 /* Run the named target if found. If a filename is specified, then set that
   2754  * to the sources.
   2755  *
   2756  * Exits if the target fails. */
   2757 Boolean
   2758 Job_RunTarget(const char *target, const char *fname) {
   2759     GNode *gn = Targ_FindNode(target);
   2760     if (gn == NULL)
   2761 	return FALSE;
   2762 
   2763     if (fname)
   2764 	Var_Set(ALLSRC, fname, gn);
   2765 
   2766     JobRun(gn);
   2767     if (gn->made == ERROR) {
   2768 	PrintOnError(gn, "\n\nStop.");
   2769 	exit(1);
   2770     }
   2771     return TRUE;
   2772 }
   2773 
   2774 #ifdef USE_SELECT
   2775 int
   2776 emul_poll(struct pollfd *fd, int nfd, int timeout)
   2777 {
   2778     fd_set rfds, wfds;
   2779     int i, maxfd, nselect, npoll;
   2780     struct timeval tv, *tvp;
   2781     long usecs;
   2782 
   2783     FD_ZERO(&rfds);
   2784     FD_ZERO(&wfds);
   2785 
   2786     maxfd = -1;
   2787     for (i = 0; i < nfd; i++) {
   2788 	fd[i].revents = 0;
   2789 
   2790 	if (fd[i].events & POLLIN)
   2791 	    FD_SET(fd[i].fd, &rfds);
   2792 
   2793 	if (fd[i].events & POLLOUT)
   2794 	    FD_SET(fd[i].fd, &wfds);
   2795 
   2796 	if (fd[i].fd > maxfd)
   2797 	    maxfd = fd[i].fd;
   2798     }
   2799 
   2800     if (maxfd >= FD_SETSIZE) {
   2801 	Punt("Ran out of fd_set slots; "
   2802 	     "recompile with a larger FD_SETSIZE.");
   2803     }
   2804 
   2805     if (timeout < 0) {
   2806 	tvp = NULL;
   2807     } else {
   2808 	usecs = timeout * 1000;
   2809 	tv.tv_sec = usecs / 1000000;
   2810 	tv.tv_usec = usecs % 1000000;
   2811 	tvp = &tv;
   2812     }
   2813 
   2814     nselect = select(maxfd + 1, &rfds, &wfds, 0, tvp);
   2815 
   2816     if (nselect <= 0)
   2817 	return nselect;
   2818 
   2819     npoll = 0;
   2820     for (i = 0; i < nfd; i++) {
   2821 	if (FD_ISSET(fd[i].fd, &rfds))
   2822 	    fd[i].revents |= POLLIN;
   2823 
   2824 	if (FD_ISSET(fd[i].fd, &wfds))
   2825 	    fd[i].revents |= POLLOUT;
   2826 
   2827 	if (fd[i].revents)
   2828 	    npoll++;
   2829     }
   2830 
   2831     return npoll;
   2832 }
   2833 #endif /* USE_SELECT */
   2834