[BACK]Return to job.c CVS log [TXT][DIR] Up to [cvs.NetBSD.org] / src / usr.bin / make

Annotation of src/usr.bin/make/job.c, Revision 1.155

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

CVSweb <webmaster@jp.NetBSD.org>