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