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