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