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

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

1.40      espie       1: /*     $OpenPackages$ */
1.93      espie       2: /*     $OpenBSD$       */
1.6       millert     3: /*     $NetBSD: job.c,v 1.16 1996/11/06 17:59:08 christos Exp $        */
1.1       deraadt     4:
                      5: /*
                      6:  * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
                      7:  * Copyright (c) 1988, 1989 by Adam de Boor
                      8:  * Copyright (c) 1989 by Berkeley Softworks
                      9:  * All rights reserved.
                     10:  *
                     11:  * This code is derived from software contributed to Berkeley by
                     12:  * Adam de Boor.
                     13:  *
                     14:  * Redistribution and use in source and binary forms, with or without
                     15:  * modification, are permitted provided that the following conditions
                     16:  * are met:
                     17:  * 1. Redistributions of source code must retain the above copyright
                     18:  *    notice, this list of conditions and the following disclaimer.
                     19:  * 2. Redistributions in binary form must reproduce the above copyright
                     20:  *    notice, this list of conditions and the following disclaimer in the
                     21:  *    documentation and/or other materials provided with the distribution.
1.55      millert    22:  * 3. Neither the name of the University nor the names of its contributors
1.1       deraadt    23:  *    may be used to endorse or promote products derived from this software
                     24:  *    without specific prior written permission.
                     25:  *
                     26:  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
                     27:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     28:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     29:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
                     30:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     31:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     32:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     33:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     34:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     35:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     36:  * SUCH DAMAGE.
                     37:  */
                     38:
                     39: /*-
                     40:  * job.c --
                     41:  *     handle the creation etc. of our child processes.
                     42:  *
                     43:  * Interface:
1.40      espie      44:  *     Job_Make                Start the creation of the given target.
1.1       deraadt    45:  *
1.40      espie      46:  *     Job_CatchChildren       Check for and handle the termination of any
                     47:  *                             children. This must be called reasonably
                     48:  *                             frequently to keep the whole make going at
                     49:  *                             a decent clip, since job table entries aren't
                     50:  *                             removed until their process is caught this way.
                     51:  *
                     52:  *     Job_CatchOutput         Print any output our children have produced.
                     53:  *                             Should also be called fairly frequently to
                     54:  *                             keep the user informed of what's going on.
                     55:  *                             If no output is waiting, it will block for
                     56:  *                             a time given by the SEL_* constants, below,
                     57:  *                             or until output is ready.
                     58:  *
1.53      jmc        59:  *     Job_Init                Called to initialize this module. in addition,
1.40      espie      60:  *                             any commands attached to the .BEGIN target
                     61:  *                             are executed before this function returns.
                     62:  *                             Hence, the makefile must have been parsed
                     63:  *                             before this function is called.
                     64:  *
                     65:  *     Job_End                 Cleanup any memory used.
                     66:  *
1.41      espie      67:  *     Job_Full                Return true if the job table is filled.
1.40      espie      68:  *
1.41      espie      69:  *     Job_Empty               Return true if the job table is completely
1.40      espie      70:  *                             empty.
                     71:  *
                     72:  *     Job_Finish              Perform any final processing which needs doing.
                     73:  *                             This includes the execution of any commands
                     74:  *                             which have been/were attached to the .END
                     75:  *                             target. It should only be called when the
                     76:  *                             job table is empty.
                     77:  *
                     78:  *     Job_AbortAll            Abort all currently running jobs. It doesn't
                     79:  *                             handle output or do anything for the jobs,
                     80:  *                             just kills them. It should only be called in
                     81:  *                             an emergency, as it were.
1.1       deraadt    82:  *
1.40      espie      83:  *     Job_Wait                Wait for all currently-running jobs to finish.
1.1       deraadt    84:  */
                     85:
                     86: #include <sys/types.h>
                     87: #include <sys/wait.h>
1.41      espie      88: #include <ctype.h>
                     89: #include <errno.h>
1.1       deraadt    90: #include <fcntl.h>
1.41      espie      91: #include <signal.h>
1.69      espie      92: #include <stdarg.h>
1.1       deraadt    93: #include <stdio.h>
1.42      espie      94: #include <stdlib.h>
1.1       deraadt    95: #include <string.h>
1.41      espie      96: #include <unistd.h>
                     97: #include "config.h"
                     98: #include "defines.h"
1.1       deraadt    99: #include "job.h"
1.63      espie     100: #include "engine.h"
1.1       deraadt   101: #include "pathnames.h"
1.41      espie     102: #include "var.h"
                    103: #include "targ.h"
                    104: #include "error.h"
                    105: #include "lst.h"
                    106: #include "extern.h"
                    107: #include "gnode.h"
                    108: #include "memory.h"
                    109: #include "make.h"
                    110:
1.50      espie     111: /*
                    112:  * The SEL_ constants determine the maximum amount of time spent in select
                    113:  * before coming out to see if a child has finished. SEL_SEC is the number of
                    114:  * seconds and SEL_USEC is the number of micro-seconds
                    115:  */
                    116: #define SEL_SEC        0
                    117: #define SEL_USEC       500000
                    118:
                    119:
                    120: /*-
                    121:  * Job Table definitions.
                    122:  *
                    123:  * Each job has several things associated with it:
                    124:  *     1) The process id of the child shell
                    125:  *     2) The graph node describing the target being made by this job
1.93      espie     126:  *     3) An FILE* for writing out the commands. This is only
1.50      espie     127:  *        used before the job is actually started.
1.93      espie     128:  *     4) Things used for handling the shell's output.
1.76      espie     129:  *        the output is being caught via a pipe and
1.50      espie     130:  *        the descriptors of our pipe, an array in which output is line
                    131:  *        buffered and the current position in that buffer are all
1.78      espie     132:  *        maintained for each job.
1.93      espie     133:  *     5) A word of flags which determine how the module handles errors,
1.50      espie     134:  *        echoing, etc. for the job
                    135:  *
                    136:  * The job "table" is kept as a linked Lst in 'jobs', with the number of
                    137:  * active jobs maintained in the 'nJobs' variable. At no time will this
                    138:  * exceed the value of 'maxJobs', initialized by the Job_Init function.
                    139:  *
                    140:  * When a job is finished, the Make_Update function is called on each of the
                    141:  * parents of the node which was just remade. This takes care of the upward
                    142:  * traversal of the dependency graph.
                    143:  */
                    144: #define JOB_BUFSIZE    1024
                    145: typedef struct Job_ {
1.51      mpech     146:     pid_t      pid;        /* The child's process ID */
1.50      espie     147:     GNode      *node;      /* The target the child is making */
                    148:     LstNode    tailCmds;   /* The node of the first command to be
                    149:                             * saved when the job has been run */
                    150:     FILE       *cmdFILE;   /* When creating the shell script, this is
                    151:                             * where the commands go */
                    152:     int        rmtID;     /* ID returned from Rmt module */
                    153:     short      flags;      /* Flags to control treatment of job */
                    154: #define JOB_IGNERR     0x001   /* Ignore non-zero exits */
                    155: #define JOB_SILENT     0x002   /* no output */
1.83      espie     156: #define JOB_SPECIAL    0x004   /* Target is a special one. */
1.79      espie     157: #define JOB_IGNDOTS    0x008   /* Ignore "..." lines when processing
                    158:                                 * commands */
1.50      espie     159: #define JOB_RESTART    0x080   /* Job needs to be completely restarted */
1.79      espie     160: #define JOB_RESUME     0x100   /* Job needs to be resumed b/c it stopped,
                    161:                                 * for some reason */
                    162: #define JOB_CONTINUING 0x200   /* We are in the process of resuming this job.
                    163:                                 * Used to avoid infinite recursion between
                    164:                                 * JobFinish and JobRestart */
1.76      espie     165:     int        inPipe;         /* Input side of pipe associated
                    166:                                 * with job's output channel */
                    167:     int        outPipe;        /* Output side of pipe associated with
                    168:                                 * job's output channel */
                    169:     char       outBuf[JOB_BUFSIZE + 1];
                    170:                                /* Buffer for storing the output of the
                    171:                                 * job, line by line */
                    172:     int        curPos;         /* Current position in op_outBuf */
1.50      espie     173: } Job;
                    174:
1.78      espie     175:
1.1       deraadt   176: /*
1.6       millert   177:  * error handling variables
1.1       deraadt   178:  */
1.40      espie     179: static int     errors = 0;         /* number of errors reported */
                    180: static int     aborting = 0;       /* why is the make aborting? */
                    181: #define ABORT_ERROR    1           /* Because of an error */
                    182: #define ABORT_INTERRUPT 2          /* Because it was interrupted */
                    183: #define ABORT_WAIT     3           /* Waiting for jobs to finish */
1.1       deraadt   184:
1.40      espie     185: static int       numCommands;      /* The number of commands actually printed
1.1       deraadt   186:                                     * for a target. Should this number be
                    187:                                     * 0, no shell will be executed. */
                    188:
                    189: /*
                    190:  * Return values from JobStart.
                    191:  */
1.40      espie     192: #define JOB_RUNNING    0       /* Job is running */
                    193: #define JOB_ERROR      1       /* Error in starting the job */
                    194: #define JOB_FINISHED   2       /* The job is already finished */
                    195: #define JOB_STOPPED    3       /* The job is stopped */
1.1       deraadt   196:
1.70      espie     197: #define SHELL_ECHO_OFF "set -"
                    198: #define SHELL_ECHO_ON  "set -v"
                    199: #define SHELL_ERROR_ON "set -e"
                    200: #define SHELL_ERROR_OFF        "set +e"
                    201: #define SHELL_ECHO_FLAG "v"
                    202: #define SHELL_ERROR_FLAG "e"
1.1       deraadt   203:
1.70      espie     204: static const char *shellPath = _PATH_BSHELL;
                    205: static const char *shellName = "sh";
1.1       deraadt   206:
1.78      espie     207:
1.40      espie     208: static int     maxJobs;        /* The most children we can run at once */
1.83      espie     209: static int     nJobs;          /* The number of children currently running */
1.48      espie     210: static LIST    jobs;           /* The structures that describe them */
1.79      espie     211: static bool    jobFull;        /* Flag to tell when the job table is full. It
1.83      espie     212:                                 * is set true when nJobs equals maxJobs */
1.40      espie     213: static fd_set  *outputsp;      /* Set of descriptors of pipes connected to
1.1       deraadt   214:                                 * the output channels of children */
1.8       deraadt   215: static int     outputsn;
1.48      espie     216: static GNode   *lastNode;      /* The node for which output was most recently
1.1       deraadt   217:                                 * produced. */
1.48      espie     218: static char    *targFmt;       /* Format string to use to head output from a
1.1       deraadt   219:                                 * job when it's not the most-recent job heard
                    220:                                 * from */
1.2       deraadt   221:
                    222: # define TARG_FMT  "--- %s ---\n" /* Default format */
                    223: # define MESSAGE(fp, gn) \
1.40      espie     224:        (void)fprintf(fp, targFmt, gn->name);
1.1       deraadt   225:
                    226: /*
1.50      espie     227:  * When JobStart attempts to run a job but isn't allowed to,
                    228:  * the job is placed on the stoppedJobs queue to be run
1.6       millert   229:  * when the next job finishes.
1.1       deraadt   230:  */
1.48      espie     231: static LIST    stoppedJobs;    /* Lst of Job structures describing
1.1       deraadt   232:                                 * jobs that were stopped due to concurrency
                    233:                                 * limits or migration home */
                    234:
                    235:
                    236: #if defined(USE_PGRP) && defined(SYSV)
1.40      espie     237: # define KILL(pid, sig)        killpg(-(pid), (sig))
1.1       deraadt   238: #else
                    239: # if defined(USE_PGRP)
1.2       deraadt   240: #  define KILL(pid, sig)       killpg((pid), (sig))
1.1       deraadt   241: # else
1.2       deraadt   242: #  define KILL(pid, sig)       kill((pid), (sig))
1.1       deraadt   243: # endif
                    244: #endif
                    245:
1.6       millert   246: /*
1.2       deraadt   247:  * Grmpf... There is no way to set bits of the wait structure
                    248:  * anymore with the stupid W*() macros. I liked the union wait
                    249:  * stuff much more. So, we devise our own macros... This is
                    250:  * really ugly, use dramamine sparingly. You have been warned.
                    251:  */
                    252: #define W_SETMASKED(st, val, fun)                              \
                    253:        {                                                       \
                    254:                int sh = (int) ~0;                              \
                    255:                int mask = fun(sh);                             \
                    256:                                                                \
                    257:                for (sh = 0; ((mask >> sh) & 1) == 0; sh++)     \
                    258:                        continue;                               \
                    259:                *(st) = (*(st) & ~mask) | ((val) << sh);        \
                    260:        }
                    261:
                    262: #define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
                    263: #define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
                    264:
                    265:
1.93      espie     266: static void pass_signal_to_job(void *, void *);
1.57      espie     267: static void SigHandler(int);
1.93      espie     268: static void handle_all_signals(void);
                    269: static void handle_signal(int);
1.40      espie     270: static int JobCmpPid(void *, void *);
1.60      espie     271: static int JobPrintCommand(LstNode, void *);
1.40      espie     272: static void JobSaveCommand(void *, void *);
                    273: static void JobClose(Job *);
                    274: static void JobFinish(Job *, int *);
                    275: static void JobExec(Job *, char **);
                    276: static void JobMakeArgv(Job *, char **);
                    277: static void JobRestart(Job *);
1.86      espie     278: static int JobStart(GNode *, int);
1.40      espie     279: static char *JobOutput(Job *, char *, char *, int);
1.41      espie     280: static void JobDoOutput(Job *, bool);
1.40      espie     281: static void JobInterrupt(int, int);
                    282: static void JobRestartJobs(void);
1.69      espie     283: static void DBPRINTF(Job *, const char *, ...);
1.84      espie     284: static void debug_printf(const char *, ...);
1.88      espie     285: static FILE *new_command_file(void);
1.93      espie     286: static void setup_signal(int);
1.94    ! espie     287: static void setup_all_signals(void);
1.93      espie     288:
                    289: static volatile sig_atomic_t got_signal;
1.1       deraadt   290:
1.57      espie     291: static volatile sig_atomic_t got_SIGINT, got_SIGHUP, got_SIGQUIT,
1.93      espie     292:     got_SIGTERM, got_SIGTSTP, got_SIGTTOU, got_SIGTTIN, got_SIGWINCH;
                    293:
1.57      espie     294:
1.88      espie     295: #define TMPPAT "/tmp/makeXXXXXXXXXX"
                    296:
                    297: static FILE *
                    298: new_command_file()
                    299: {
                    300:        int fd;
                    301:        FILE *f;
                    302:        char tmp[] = TMPPAT;
                    303:
                    304:        fd = mkstemp(tmp);
                    305:        if (fd == -1)
                    306:                return NULL;
                    307:        f = fdopen(fd, "w");
                    308:        if (f == NULL)
                    309:                close(fd);
                    310:        eunlink(tmp);
                    311:        return f;
                    312: }
                    313:
1.57      espie     314: static void
                    315: SigHandler(int sig)
                    316: {
                    317:        switch(sig) {
                    318:        case SIGINT:
                    319:                got_SIGINT++;
1.93      espie     320:                got_signal = 1;
1.57      espie     321:                break;
                    322:        case SIGHUP:
                    323:                got_SIGHUP++;
1.93      espie     324:                got_signal = 1;
1.57      espie     325:                break;
                    326:        case SIGQUIT:
                    327:                got_SIGQUIT++;
1.93      espie     328:                got_signal = 1;
1.57      espie     329:                break;
                    330:        case SIGTERM:
                    331:                got_SIGTERM++;
1.93      espie     332:                got_signal = 1;
1.57      espie     333:                break;
1.93      espie     334: #ifdef USE_PGRP
1.57      espie     335:        case SIGTSTP:
                    336:                got_SIGTSTP++;
1.93      espie     337:                got_signal = 1;
1.57      espie     338:                break;
                    339:        case SIGTTOU:
                    340:                got_SIGTTOU++;
1.93      espie     341:                got_signal = 1;
1.57      espie     342:                break;
                    343:        case SIGTTIN:
                    344:                got_SIGTTIN++;
1.93      espie     345:                got_signal = 1;
1.57      espie     346:                break;
                    347:        case SIGWINCH:
                    348:                got_SIGWINCH++;
1.93      espie     349:                got_signal = 1;
1.57      espie     350:                break;
                    351: #endif
                    352:        }
                    353: }
                    354:
                    355: static void
1.93      espie     356: handle_all_signals()
1.57      espie     357: {
1.93      espie     358:        if (got_signal)
                    359:                got_signal = 0;
                    360:        else
                    361:                return;
                    362:
1.57      espie     363:        if (got_SIGINT) {
                    364:                got_SIGINT=0;
1.93      espie     365:                handle_signal(SIGINT);
1.57      espie     366:        }
                    367:        if (got_SIGHUP) {
                    368:                got_SIGHUP=0;
1.93      espie     369:                handle_signal(SIGHUP);
1.57      espie     370:        }
                    371:        if (got_SIGQUIT) {
                    372:                got_SIGQUIT=0;
1.93      espie     373:                handle_signal(SIGQUIT);
1.57      espie     374:        }
                    375:        if (got_SIGTERM) {
                    376:                got_SIGTERM=0;
1.93      espie     377:                handle_signal(SIGTERM);
1.57      espie     378:        }
                    379:        if (got_SIGTSTP) {
                    380:                got_SIGTSTP=0;
1.93      espie     381:                handle_signal(SIGTSTP);
1.57      espie     382:        }
                    383:        if (got_SIGTTOU) {
                    384:                got_SIGTTOU=0;
1.93      espie     385:                handle_signal(SIGTTOU);
1.57      espie     386:        }
                    387:        if (got_SIGTTIN) {
                    388:                got_SIGTTIN=0;
1.93      espie     389:                handle_signal(SIGTTIN);
1.57      espie     390:        }
                    391:        if (got_SIGWINCH) {
                    392:                got_SIGWINCH=0;
1.93      espie     393:                handle_signal(SIGWINCH);
1.57      espie     394:        }
                    395: }
                    396:
1.1       deraadt   397: /*-
                    398:  *-----------------------------------------------------------------------
                    399:  * JobCondPassSig --
1.50      espie     400:  *     Pass a signal to a job if USE_PGRP
1.1       deraadt   401:  *     is defined.
                    402:  *
                    403:  * Side Effects:
                    404:  *     None, except the job may bite it.
                    405:  *-----------------------------------------------------------------------
                    406:  */
1.27      espie     407: static void
1.93      espie     408: pass_signal_to_job(void *jobp, /* Job to biff */
1.56      espie     409:     void *signop)              /* Signal to send it */
1.1       deraadt   410: {
1.66      espie     411:        Job *job = (Job *)jobp;
                    412:        int signo = *(int *)signop;
                    413:        if (DEBUG(JOB)) {
                    414:                (void)fprintf(stdout,
1.93      espie     415:                    "pass_signal_to_job passing signal %d to child %ld.\n",
1.66      espie     416:                    signo, (long)job->pid);
                    417:                (void)fflush(stdout);
                    418:        }
                    419:        KILL(job->pid, signo);
1.1       deraadt   420: }
                    421:
                    422: /*-
                    423:  *-----------------------------------------------------------------------
1.94    ! espie     424:  * handle_signal --
1.68      espie     425:  *     Pass a signal to all local jobs if USE_PGRP is defined,
1.50      espie     426:  *     then die ourselves.
1.1       deraadt   427:  *
                    428:  * Side Effects:
                    429:  *     We die by the same signal.
                    430:  *-----------------------------------------------------------------------
                    431:  */
                    432: static void
1.93      espie     433: handle_signal(int signo) /* The signal number we've received */
1.1       deraadt   434: {
1.66      espie     435:        sigset_t nmask, omask;
                    436:        struct sigaction act;
1.6       millert   437:
1.66      espie     438:        if (DEBUG(JOB)) {
1.93      espie     439:                (void)fprintf(stdout, "handle_signal(%d) called.\n", signo);
1.66      espie     440:                (void)fflush(stdout);
                    441:        }
1.93      espie     442:        Lst_ForEach(&jobs, pass_signal_to_job, &signo);
1.66      espie     443:
                    444:        /*
                    445:         * Deal with proper cleanup based on the signal received. We only run
                    446:         * the .INTERRUPT target if the signal was in fact an interrupt. The
                    447:         * other three termination signals are more of a "get out *now*"
                    448:         * command.
                    449:         */
                    450:        if (signo == SIGINT) {
                    451:                JobInterrupt(true, signo);
                    452:        } else if (signo == SIGHUP || signo == SIGTERM || signo == SIGQUIT) {
                    453:                JobInterrupt(false, signo);
                    454:        }
1.1       deraadt   455:
1.66      espie     456:        /*
                    457:         * Leave gracefully if SIGQUIT, rather than core dumping.
                    458:         */
                    459:        if (signo == SIGQUIT) {
                    460:                Finish(0);
                    461:        }
1.6       millert   462:
1.66      espie     463:        /*
                    464:         * Send ourselves the signal now we've given the message to everyone
                    465:         * else.  Note we block everything else possible while we're getting
                    466:         * the signal.  This ensures that all our jobs get continued when we
                    467:         * wake up before we take any other signal.
                    468:         */
                    469:        sigemptyset(&nmask);
                    470:        sigaddset(&nmask, signo);
                    471:        sigprocmask(SIG_SETMASK, &nmask, &omask);
                    472:        memset(&act, 0, sizeof act);
                    473:        act.sa_handler = SIG_DFL;
                    474:        sigemptyset(&act.sa_mask);
                    475:        act.sa_flags = 0;
                    476:        sigaction(signo, &act, NULL);
1.6       millert   477:
1.66      espie     478:        if (DEBUG(JOB)) {
                    479:                (void)fprintf(stdout,
1.93      espie     480:                    "handle_signal passing signal to self, mask = %x.\n",
1.66      espie     481:                    ~0 & ~(1 << (signo-1)));
                    482:                (void)fflush(stdout);
                    483:        }
                    484:        (void)signal(signo, SIG_DFL);
1.1       deraadt   485:
1.66      espie     486:        (void)KILL(getpid(), signo);
1.1       deraadt   487:
1.66      espie     488:        signo = SIGCONT;
1.93      espie     489:        Lst_ForEach(&jobs, pass_signal_to_job, &signo);
1.1       deraadt   490:
1.66      espie     491:        (void)sigprocmask(SIG_SETMASK, &omask, NULL);
                    492:        sigprocmask(SIG_SETMASK, &omask, NULL);
                    493:        act.sa_handler = SigHandler;
                    494:        sigaction(signo, &act, NULL);
1.1       deraadt   495: }
                    496:
                    497: /*-
                    498:  *-----------------------------------------------------------------------
                    499:  * JobCmpPid  --
                    500:  *     Compare the pid of the job with the given pid and return 0 if they
                    501:  *     are equal. This function is called from Job_CatchChildren via
                    502:  *     Lst_Find to find the job descriptor of the finished job.
                    503:  *
                    504:  * Results:
                    505:  *     0 if the pid's match
                    506:  *-----------------------------------------------------------------------
                    507:  */
                    508: static int
1.56      espie     509: JobCmpPid(void *job,   /* job to examine */
                    510:     void *pid)         /* process id desired */
1.1       deraadt   511: {
1.66      espie     512:        return *(pid_t *)pid - ((Job *)job)->pid;
1.1       deraadt   513: }
                    514:
1.69      espie     515: static void
                    516: DBPRINTF(Job *job, const char *fmt, ...)
                    517: {
                    518:        va_list va;
                    519:        va_start(va, fmt);
                    520:        if (DEBUG(JOB)) {
                    521:                (void)vfprintf(stdout, fmt, va);
                    522:                fflush(stdout);
                    523:        }
                    524:        vfprintf(job->cmdFILE, fmt, va);
                    525:        va_end(va);
                    526: }
                    527:
1.84      espie     528: static void
                    529: debug_printf(const char *fmt, ...)
                    530: {
                    531:        if (DEBUG(JOB)) {
                    532:                va_list va;
                    533:
                    534:                va_start(va, fmt);
                    535:                (void)vfprintf(stdout, fmt, va);
                    536:                fflush(stdout);
                    537:                va_end(va);
                    538:        }
                    539: }
                    540:
1.1       deraadt   541: /*-
                    542:  *-----------------------------------------------------------------------
                    543:  * JobPrintCommand  --
                    544:  *     Put out another command for the given job. If the command starts
                    545:  *     with an @ or a - we process it specially. In the former case,
                    546:  *     so long as the -s and -n flags weren't given to make, we stick
                    547:  *     a shell-specific echoOff command in the script. In the latter,
                    548:  *     we ignore errors for the entire job, unless the shell has error
                    549:  *     control.
                    550:  *     If the command is just "..." we take all future commands for this
                    551:  *     job to be commands to be executed once the entire graph has been
                    552:  *     made and return non-zero to signal that the end of the commands
1.78      espie     553:  *     was reached. These commands are later attached to the end_node
1.1       deraadt   554:  *     node and executed by Job_End when all things are done.
1.40      espie     555:  *     This function is called from JobStart via Lst_Find
1.1       deraadt   556:  *
                    557:  * Results:
1.26      espie     558:  *     Always 1, unless the command was "..."
1.1       deraadt   559:  *
                    560:  * Side Effects:
                    561:  *     If the command begins with a '-' and the shell has no error control,
                    562:  *     the JOB_IGNERR flag is set in the job descriptor.
                    563:  *     If the command is "..." and we're not ignoring such things,
                    564:  *     tailCmds is set to the successor node of the cmd.
                    565:  *     numCommands is incremented if the command is actually printed.
                    566:  *-----------------------------------------------------------------------
                    567:  */
                    568: static int
1.78      espie     569: JobPrintCommand(LstNode cmdNode,       /* command string to print */
                    570:     void *jobp)                                /* job for which to print it */
1.1       deraadt   571: {
1.78      espie     572:        bool noSpecials;                /* true if we shouldn't worry about
                    573:                                         * inserting special commands into
                    574:                                         * the input stream. */
                    575:        bool shutUp = false;            /* true if we put a no echo command
                    576:                                         * into the command file */
                    577:        bool errOff = false;            /* true if we turned error checking
                    578:                                         * off before printing the command
                    579:                                         * and need to turn it back on */
                    580:        char *cmdTemplate;              /* Template to use when printing the
                    581:                                         * command */
                    582:        char *cmdStart;                 /* Start of expanded command */
1.66      espie     583:        char *cmd = (char *)Lst_Datum(cmdNode);
                    584:        Job *job = (Job *)jobp;
                    585:
                    586:        noSpecials = (noExecute && !(job->node->type & OP_MAKE));
                    587:
                    588:        if (strcmp(cmd, "...") == 0) {
                    589:                job->node->type |= OP_SAVE_CMDS;
                    590:                if ((job->flags & JOB_IGNDOTS) == 0) {
                    591:                        job->tailCmds = Lst_Succ(cmdNode);
                    592:                        return 0;
                    593:                }
                    594:                return 1;
1.2       deraadt   595:        }
1.1       deraadt   596:
1.78      espie     597:
1.67      espie     598:        numCommands++;
1.1       deraadt   599:
1.66      espie     600:        /* For debugging, we replace each command with the result of expanding
                    601:         * the variables in the command.  */
                    602:        cmdStart = cmd = Var_Subst(cmd, &job->node->context, false);
                    603:        Lst_Replace(cmdNode, cmdStart);
1.1       deraadt   604:
1.66      espie     605:        cmdTemplate = "%s\n";
1.1       deraadt   606:
1.66      espie     607:        /*
                    608:         * Check for leading @' and -'s to control echoing and error checking.
                    609:         */
                    610:        for (;; cmd++) {
                    611:                if (*cmd == '@')
                    612:                        shutUp = DEBUG(LOUD) ? false : true;
                    613:                else if (*cmd == '-')
                    614:                        errOff = true;
                    615:                else if (*cmd != '+')
                    616:                        break;
1.1       deraadt   617:        }
                    618:
1.66      espie     619:        while (isspace(*cmd))
                    620:                cmd++;
                    621:
                    622:        if (shutUp) {
1.72      espie     623:                if (!(job->flags & JOB_SILENT) && !noSpecials) {
1.71      espie     624:                        DBPRINTF(job, "%s\n", SHELL_ECHO_OFF);
1.1       deraadt   625:                } else {
1.66      espie     626:                        shutUp = false;
                    627:                }
                    628:        }
                    629:
                    630:        if (errOff) {
                    631:                if ( !(job->flags & JOB_IGNERR) && !noSpecials) {
1.72      espie     632:                        /*
1.78      espie     633:                         * we don't want the error-control commands showing
                    634:                         * up either, so we turn off echoing while executing
                    635:                         * them. We could put another field in the shell
                    636:                         * structure to tell JobDoOutput to look for this
                    637:                         * string too, but why make it any more complex than
                    638:                         * it already is?
1.72      espie     639:                         */
                    640:                        if (!(job->flags & JOB_SILENT) && !shutUp) {
1.75      espie     641:                                DBPRINTF(job, "%s; %s; %s\n", SHELL_ECHO_OFF,
                    642:                                    SHELL_ERROR_OFF, SHELL_ECHO_ON);
1.66      espie     643:                        } else {
1.72      espie     644:                                DBPRINTF(job, "%s\n", SHELL_ERROR_OFF);
1.66      espie     645:                        }
                    646:                } else {
                    647:                        errOff = false;
1.1       deraadt   648:                }
1.66      espie     649:        }
                    650:
1.69      espie     651:        DBPRINTF(job, cmdTemplate, cmd);
1.66      espie     652:
                    653:        if (errOff) {
                    654:                /*
                    655:                 * If echoing is already off, there's no point in issuing the
                    656:                 * echoOff command. Otherwise we issue it and pretend it was on
                    657:                 * for the whole command...
1.1       deraadt   658:                 */
1.72      espie     659:                if (!shutUp && !(job->flags & JOB_SILENT)) {
1.71      espie     660:                        DBPRINTF(job, "%s\n", SHELL_ECHO_OFF);
1.41      espie     661:                        shutUp = true;
1.1       deraadt   662:                }
1.71      espie     663:                DBPRINTF(job, "%s\n", SHELL_ERROR_ON);
1.66      espie     664:        }
                    665:        if (shutUp) {
1.71      espie     666:                DBPRINTF(job, "%s\n", SHELL_ECHO_ON);
1.1       deraadt   667:        }
1.66      espie     668:        return 1;
1.1       deraadt   669: }
                    670:
                    671: /*-
                    672:  *-----------------------------------------------------------------------
                    673:  * JobSaveCommand --
                    674:  *     Save a command to be executed when everything else is done.
                    675:  *     Callback function for JobFinish...
                    676:  *
                    677:  * Side Effects:
1.78      espie     678:  *     The command is tacked onto the end of end_node's commands list.
1.1       deraadt   679:  *-----------------------------------------------------------------------
                    680:  */
1.27      espie     681: static void
1.56      espie     682: JobSaveCommand(void *cmd, void *gn)
1.1       deraadt   683: {
1.66      espie     684:        GNode *g = (GNode *)gn;
                    685:        char *result;
1.28      espie     686:
1.66      espie     687:        result = Var_Subst((char *)cmd, &g->context, false);
1.78      espie     688:        Lst_AtEnd(&end_node->commands, result);
1.2       deraadt   689: }
                    690:
                    691:
                    692: /*-
                    693:  *-----------------------------------------------------------------------
                    694:  * JobClose --
                    695:  *     Called to close both input and output pipes when a job is finished.
                    696:  *
                    697:  * Side Effects:
                    698:  *     The file descriptors associated with the job are closed.
                    699:  *-----------------------------------------------------------------------
                    700:  */
                    701: static void
1.56      espie     702: JobClose(Job *job)
1.2       deraadt   703: {
1.76      espie     704:        FD_CLR(job->inPipe, outputsp);
                    705:        if (job->outPipe != job->inPipe) {
                    706:               (void)close(job->outPipe);
1.66      espie     707:        }
1.76      espie     708:        JobDoOutput(job, true);
                    709:        (void)close(job->inPipe);
1.1       deraadt   710: }
                    711:
                    712: /*-
                    713:  *-----------------------------------------------------------------------
                    714:  * JobFinish  --
                    715:  *     Do final processing for the given job including updating
                    716:  *     parents and starting new jobs as available/necessary. Note
                    717:  *     that we pay no attention to the JOB_IGNERR flag here.
                    718:  *     This is because when we're called because of a noexecute flag
                    719:  *     or something, jstat.w_status is 0 and when called from
                    720:  *     Job_CatchChildren, the status is zeroed if it s/b ignored.
                    721:  *
                    722:  * Side Effects:
                    723:  *     Some nodes may be put on the toBeMade queue.
1.78      espie     724:  *     Final commands for the job are placed on end_node.
1.1       deraadt   725:  *
1.6       millert   726:  *     If we got an error and are aborting (aborting == ABORT_ERROR) and
1.1       deraadt   727:  *     the job list is now empty, we are done for the day.
1.6       millert   728:  *     If we recognized an error (errors !=0), we set the aborting flag
1.1       deraadt   729:  *     to ABORT_ERROR so no more jobs will be started.
                    730:  *-----------------------------------------------------------------------
                    731:  */
                    732: /*ARGSUSED*/
                    733: static void
1.56      espie     734: JobFinish(Job *job,            /* job to finish */
                    735:     int *status)               /* sub-why job went away */
1.2       deraadt   736: {
1.78      espie     737:        bool     done;
1.2       deraadt   738:
1.66      espie     739:        if ((WIFEXITED(*status) &&
                    740:             WEXITSTATUS(*status) != 0 && !(job->flags & JOB_IGNERR)) ||
                    741:            (WIFSIGNALED(*status) && WTERMSIG(*status) != SIGCONT)) {
                    742:                /*
                    743:                 * If it exited non-zero and either we're doing things our
                    744:                 * way or we're not ignoring errors, the job is finished.
                    745:                 * Similarly, if the shell died because of a signal
                    746:                 * the job is also finished. In these
                    747:                 * cases, finish out the job's output before printing the exit
                    748:                 * status...
                    749:                 */
                    750:                JobClose(job);
                    751:                if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
                    752:                       (void)fclose(job->cmdFILE);
                    753:                }
                    754:                done = true;
                    755:        } else if (WIFEXITED(*status)) {
                    756:                /*
                    757:                 * Deal with ignored errors in -B mode. We need to print a
                    758:                 * message telling of the ignored error as well as setting
                    759:                 * status.w_status to 0 so the next command gets run. To do
                    760:                 * this, we set done to be true if in -B mode and the job
                    761:                 * exited non-zero.
                    762:                 */
                    763:                done = WEXITSTATUS(*status) != 0;
                    764:                /*
                    765:                 * Old comment said: "Note we don't want to close down any of
                    766:                 * the streams until we know we're at the end." But we do.
                    767:                 * Otherwise when are we going to print the rest of the stuff?
                    768:                 */
                    769:                JobClose(job);
                    770:        } else {
                    771:                /*
                    772:                 * No need to close things down or anything.
                    773:                 */
                    774:                done = false;
1.1       deraadt   775:        }
1.6       millert   776:
1.66      espie     777:        if (done ||
                    778:            WIFSTOPPED(*status) ||
                    779:            (WIFSIGNALED(*status) && WTERMSIG(*status) == SIGCONT) ||
                    780:            DEBUG(JOB)) {
                    781:                FILE *out;
                    782:
1.76      espie     783:                out = stdout;
1.1       deraadt   784:
1.66      espie     785:                if (WIFEXITED(*status)) {
1.84      espie     786:                        debug_printf("Process %ld exited.\n", (long)job->pid);
1.66      espie     787:                        if (WEXITSTATUS(*status) != 0) {
1.76      espie     788:                                if (job->node != lastNode) {
1.66      espie     789:                                        MESSAGE(out, job->node);
                    790:                                        lastNode = job->node;
                    791:                                }
                    792:                                (void)fprintf(out, "*** Error code %d%s\n",
                    793:                                    WEXITSTATUS(*status),
1.68      espie     794:                                    (job->flags & JOB_IGNERR) ? "(ignored)" :
1.66      espie     795:                                    "");
                    796:
                    797:                                if (job->flags & JOB_IGNERR) {
                    798:                                        *status = 0;
                    799:                                }
                    800:                        } else if (DEBUG(JOB)) {
1.76      espie     801:                                if (job->node != lastNode) {
1.66      espie     802:                                        MESSAGE(out, job->node);
                    803:                                        lastNode = job->node;
                    804:                                }
1.68      espie     805:                                (void)fprintf(out,
1.66      espie     806:                                    "*** Completed successfully\n");
                    807:                        }
                    808:                } else if (WIFSTOPPED(*status)) {
1.84      espie     809:                        debug_printf("Process %ld stopped.\n", (long)job->pid);
1.76      espie     810:                        if (job->node != lastNode) {
1.66      espie     811:                                MESSAGE(out, job->node);
                    812:                                lastNode = job->node;
                    813:                        }
                    814:                        (void)fprintf(out, "*** Stopped -- signal %d\n",
                    815:                            WSTOPSIG(*status));
                    816:                        job->flags |= JOB_RESUME;
                    817:                        Lst_AtEnd(&stoppedJobs, job);
                    818:                        (void)fflush(out);
                    819:                        return;
                    820:                } else if (WTERMSIG(*status) == SIGCONT) {
                    821:                        /*
                    822:                         * If the beastie has continued, shift the Job from the
                    823:                         * stopped list to the running one (or re-stop it if
                    824:                         * concurrency is exceeded) and go and get another
                    825:                         * child.
                    826:                         */
                    827:                        if (job->flags & (JOB_RESUME|JOB_RESTART)) {
1.76      espie     828:                                if (job->node != lastNode) {
1.66      espie     829:                                        MESSAGE(out, job->node);
                    830:                                        lastNode = job->node;
                    831:                                }
                    832:                                (void)fprintf(out, "*** Continued\n");
                    833:                        }
                    834:                        if (!(job->flags & JOB_CONTINUING)) {
1.84      espie     835:                                debug_printf(
                    836:                                    "Warning: "
                    837:                                    "process %ld was not continuing.\n",
                    838:                                    (long)job->pid);
1.66      espie     839: #if 0
                    840:                                /*
                    841:                                 * We don't really want to restart a job from
                    842:                                 * scratch just because it continued,
                    843:                                 * especially not without killing the
                    844:                                 * continuing process!  That's why this is
                    845:                                 * ifdef'ed out.  FD - 9/17/90
                    846:                                 */
                    847:                                JobRestart(job);
1.2       deraadt   848: #endif
1.66      espie     849:                        }
                    850:                        job->flags &= ~JOB_CONTINUING;
                    851:                        Lst_AtEnd(&jobs, job);
1.67      espie     852:                        nJobs++;
1.84      espie     853:                        debug_printf("Process %ld is continuing locally.\n",
                    854:                            (long)job->pid);
1.66      espie     855:                        if (nJobs == maxJobs) {
                    856:                                jobFull = true;
1.84      espie     857:                                debug_printf("Job queue is full.\n");
1.66      espie     858:                        }
                    859:                        (void)fflush(out);
                    860:                        return;
                    861:                } else {
1.76      espie     862:                        if (job->node != lastNode) {
1.66      espie     863:                                MESSAGE(out, job->node);
                    864:                                lastNode = job->node;
                    865:                        }
1.68      espie     866:                        (void)fprintf(out, "*** Signal %d\n",
1.66      espie     867:                            WTERMSIG(*status));
1.40      espie     868:                }
1.66      espie     869:
                    870:                (void)fflush(out);
1.1       deraadt   871:        }
                    872:
1.85      espie     873:        done = true;
1.1       deraadt   874:
1.66      espie     875:        if (done &&
                    876:            aborting != ABORT_ERROR &&
                    877:            aborting != ABORT_INTERRUPT &&
                    878:            *status == 0) {
                    879:                /* As long as we aren't aborting and the job didn't return a
                    880:                 * non-zero status that we shouldn't ignore, we call
                    881:                 * Make_Update to update the parents. In addition, any saved
                    882:                 * commands for the node are placed on the .END target. */
                    883:                Lst_ForEachFrom(job->tailCmds, JobSaveCommand, job->node);
                    884:                job->node->made = MADE;
                    885:                Make_Update(job->node);
                    886:                free(job);
                    887:        } else if (*status != 0) {
1.67      espie     888:                errors++;
1.66      espie     889:                free(job);
                    890:        }
1.1       deraadt   891:
1.66      espie     892:        JobRestartJobs();
1.1       deraadt   893:
                    894:        /*
1.66      espie     895:         * Set aborting if any error.
1.1       deraadt   896:         */
1.66      espie     897:        if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
                    898:                /*
                    899:                 * If we found any errors in this batch of children and the -k
                    900:                 * flag wasn't given, we set the aborting flag so no more jobs
                    901:                 * get started.
                    902:                 */
                    903:                aborting = ABORT_ERROR;
                    904:        }
1.6       millert   905:
1.66      espie     906:        if (aborting == ABORT_ERROR && Job_Empty()) {
                    907:                /*
                    908:                 * If we are aborting and the job table is now empty, we finish.
                    909:                 */
                    910:                Finish(errors);
                    911:        }
1.1       deraadt   912: }
                    913:
                    914: /*-
                    915:  *-----------------------------------------------------------------------
                    916:  * JobExec --
                    917:  *     Execute the shell for the given job. Called from JobStart and
                    918:  *     JobRestart.
                    919:  *
                    920:  * Side Effects:
                    921:  *     A shell is executed, outputs is altered and the Job structure added
                    922:  *     to the job table.
                    923:  *-----------------------------------------------------------------------
                    924:  */
                    925: static void
1.56      espie     926: JobExec(Job *job, char **argv)
1.1       deraadt   927: {
1.66      espie     928:        pid_t cpid;     /* ID of new child */
1.94    ! espie     929:        static int signals_caught = 0;
1.6       millert   930:
1.66      espie     931:        if (DEBUG(JOB)) {
1.78      espie     932:                int i;
1.6       millert   933:
1.66      espie     934:                (void)fprintf(stdout, "Running %s\n", job->node->name);
                    935:                (void)fprintf(stdout, "\tCommand: ");
                    936:                for (i = 0; argv[i] != NULL; i++) {
                    937:                        (void)fprintf(stdout, "%s ", argv[i]);
                    938:                }
                    939:                (void)fprintf(stdout, "\n");
                    940:                (void)fflush(stdout);
1.1       deraadt   941:        }
1.6       millert   942:
1.66      espie     943:        /*
                    944:         * Some jobs produce no output and it's disconcerting to have
                    945:         * no feedback of their running (since they produce no output, the
                    946:         * banner with their name in it never appears). This is an attempt to
                    947:         * provide that feedback, even if nothing follows it.
                    948:         */
1.87      espie     949:        if (lastNode != job->node && !(job->flags & JOB_SILENT)) {
1.66      espie     950:                MESSAGE(stdout, job->node);
                    951:                lastNode = job->node;
                    952:        }
1.1       deraadt   953:
1.94    ! espie     954:        if (!signals_caught) {
        !           955:                signals_caught = 1;
        !           956:                setup_all_signals();
        !           957:        }
        !           958:
1.66      espie     959:        if ((cpid = fork()) == -1) {
                    960:                Punt("Cannot fork");
                    961:        } else if (cpid == 0) {
1.6       millert   962:
1.66      espie     963:                /*
                    964:                 * Must duplicate the input stream down to the child's input
                    965:                 * and reset it to the beginning (again). Since the stream was
                    966:                 * marked close-on-exec, we must clear that bit in the new
                    967:                 * input.
                    968:                 */
1.81      espie     969:                if (dup2(fileno(job->cmdFILE), 0) == -1)
1.82      espie     970:                        Punt("Cannot dup2(job->cmdFile): %s", strerror(errno));
1.66      espie     971:                (void)fcntl(0, F_SETFD, 0);
                    972:                (void)lseek(0, 0, SEEK_SET);
                    973:
1.76      espie     974:                /*
1.78      espie     975:                 * Set up the child's output to be routed through the pipe
                    976:                 * we've created for it.
1.76      espie     977:                 */
                    978:                if (dup2(job->outPipe, 1) == -1)
1.82      espie     979:                        Punt("Cannot dup2(job->outPipe): %s", strerror(errno));
1.66      espie     980:                /*
                    981:                 * The output channels are marked close on exec. This bit was
                    982:                 * duplicated by the dup2 (on some systems), so we have to
                    983:                 * clear it before routing the shell's error output to the same
                    984:                 * place as its standard output.
                    985:                 */
                    986:                (void)fcntl(1, F_SETFD, 0);
                    987:                if (dup2(1, 2) == -1)
1.82      espie     988:                        Punt("Cannot dup2(stdout): %s", strerror(errno));
1.1       deraadt   989:
                    990: #ifdef USE_PGRP
1.66      espie     991:                /*
                    992:                 * We want to switch the child into a different process family
                    993:                 * so we can kill it and all its descendants in one fell swoop,
                    994:                 * by killing its process family, but not commit suicide.
                    995:                 */
1.2       deraadt   996: # if defined(SYSV)
1.66      espie     997:                (void)setsid();
1.2       deraadt   998: # else
1.66      espie     999:                (void)setpgid(0, getpid());
1.2       deraadt  1000: # endif
                   1001: #endif /* USE_PGRP */
1.1       deraadt  1002:
1.66      espie    1003:                (void)execv(shellPath, argv);
                   1004:
                   1005:                (void)write(STDERR_FILENO, "Could not execute shell\n",
                   1006:                    sizeof("Could not execute shell"));
                   1007:                _exit(1);
                   1008:        } else {
                   1009:                job->pid = cpid;
                   1010:
1.87      espie    1011:                /* we set the current position in the buffer to the beginning
                   1012:                 * and mark another stream to watch in the outputs mask
                   1013:                 */
                   1014:                job->curPos = 0;
1.66      espie    1015:
1.87      espie    1016:                if (outputsp == NULL || job->inPipe > outputsn) {
1.92      cnst     1017:                        int fdn, ofdn;
                   1018:                        fd_set *tmp;
1.87      espie    1019:
1.92      cnst     1020:                        fdn = howmany(job->inPipe+1, NFDBITS);
                   1021:                        ofdn = outputsn ? howmany(outputsn+1, NFDBITS) : 0;
1.87      espie    1022:
1.92      cnst     1023:                        if (fdn != ofdn) {
                   1024:                                tmp = recalloc(outputsp, fdn, sizeof(fd_mask));
1.87      espie    1025:                                if (tmp == NULL)
                   1026:                                        return;
1.92      cnst     1027:                                outputsp = tmp;
1.66      espie    1028:                        }
1.87      espie    1029:                        outputsn = job->inPipe;
1.66      espie    1030:                }
1.87      espie    1031:                FD_SET(job->inPipe, outputsp);
1.2       deraadt  1032:
1.66      espie    1033:                /*
                   1034:                 * XXX: Used to not happen if REMOTE. Why?
                   1035:                 */
                   1036:                if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
                   1037:                        (void)fclose(job->cmdFILE);
                   1038:                        job->cmdFILE = NULL;
                   1039:                }
1.1       deraadt  1040:        }
                   1041:
1.48      espie    1042:        /*
1.66      espie    1043:         * Now the job is actually running, add it to the table.
1.48      espie    1044:         */
1.67      espie    1045:        nJobs++;
1.66      espie    1046:        Lst_AtEnd(&jobs, job);
                   1047:        if (nJobs == maxJobs) {
                   1048:                jobFull = true;
1.1       deraadt  1049:        }
                   1050: }
                   1051:
                   1052: /*-
                   1053:  *-----------------------------------------------------------------------
                   1054:  * JobMakeArgv --
                   1055:  *     Create the argv needed to execute the shell for a given job.
                   1056:  *-----------------------------------------------------------------------
                   1057:  */
                   1058: static void
1.56      espie    1059: JobMakeArgv(Job *job, char **argv)
1.1       deraadt  1060: {
1.66      espie    1061:        int argc;
                   1062:        static char args[10];   /* For merged arguments */
1.6       millert  1063:
1.70      espie    1064:        argv[0] = (char *)shellName;
1.66      espie    1065:        argc = 1;
1.1       deraadt  1066:
1.73      espie    1067:        (void)snprintf(args, sizeof(args), "-%s%s",
                   1068:            (job->flags & JOB_IGNERR) ? "" : SHELL_ERROR_FLAG,
                   1069:            (job->flags & JOB_SILENT) ? "" : SHELL_ECHO_FLAG);
                   1070:
                   1071:        if (args[1]) {
                   1072:                argv[argc] = args;
                   1073:                argc++;
1.78      espie    1074:        }
1.66      espie    1075:        argv[argc] = NULL;
1.1       deraadt  1076: }
                   1077:
                   1078: /*-
                   1079:  *-----------------------------------------------------------------------
                   1080:  * JobRestart --
1.6       millert  1081:  *     Restart a job that stopped for some reason.
1.1       deraadt  1082:  *
                   1083:  * Side Effects:
                   1084:  *     jobFull will be set if the job couldn't be run.
                   1085:  *-----------------------------------------------------------------------
                   1086:  */
                   1087: static void
1.56      espie    1088: JobRestart(Job *job)
1.1       deraadt  1089: {
1.66      espie    1090:        if (job->flags & JOB_RESTART) {
                   1091:                /*
                   1092:                 * Set up the control arguments to the shell. This is based on
                   1093:                 * the flags set earlier for this job. If the JOB_IGNERR flag
                   1094:                 * is clear, the 'exit' flag of the commandShell is used to
                   1095:                 * cause it to exit upon receiving an error. If the JOB_SILENT
                   1096:                 * flag is clear, the 'echo' flag of the commandShell is used
                   1097:                 * to get it to start echoing as soon as it starts processing
                   1098:                 * commands.
                   1099:                 */
                   1100:                char *argv[4];
1.6       millert  1101:
1.66      espie    1102:                JobMakeArgv(job, argv);
1.2       deraadt  1103:
1.1       deraadt  1104:                if (DEBUG(JOB)) {
1.68      espie    1105:                        (void)fprintf(stdout, "Restarting %s...",
1.66      espie    1106:                            job->node->name);
                   1107:                        (void)fflush(stdout);
1.1       deraadt  1108:                }
1.83      espie    1109:                if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL)) {
1.80      espie    1110:                        /*
                   1111:                         * Can't be exported and not allowed to run locally --
                   1112:                         * put it back on the hold queue and mark the table
                   1113:                         * full
                   1114:                         */
1.84      espie    1115:                        debug_printf("holding\n");
1.80      espie    1116:                        Lst_AtFront(&stoppedJobs, job);
                   1117:                        jobFull = true;
1.84      espie    1118:                        debug_printf("Job queue is full.\n");
1.80      espie    1119:                        return;
1.66      espie    1120:                } else {
1.80      espie    1121:                        /*
                   1122:                         * Job may be run locally.
                   1123:                         */
1.84      espie    1124:                        debug_printf("running locally\n");
1.1       deraadt  1125:                }
1.66      espie    1126:                JobExec(job, argv);
                   1127:        } else {
1.1       deraadt  1128:                /*
1.66      espie    1129:                 * The job has stopped and needs to be restarted. Why it
                   1130:                 * stopped, we don't know...
1.1       deraadt  1131:                 */
1.84      espie    1132:                debug_printf("Resuming %s...", job->node->name);
1.83      espie    1133:                if ((nJobs < maxJobs || ((job->flags & JOB_SPECIAL) &&
                   1134:                    maxJobs == 0)) && nJobs != maxJobs) {
1.66      espie    1135:                        /*
1.79      espie    1136:                         * If we haven't reached the concurrency limit already
1.83      espie    1137:                         * (or maxJobs is 0), it's ok to resume the job.
1.66      espie    1138:                         */
                   1139:                        bool error;
                   1140:                        int status;
                   1141:
                   1142:                        error = KILL(job->pid, SIGCONT) != 0;
                   1143:
                   1144:                        if (!error) {
                   1145:                                /*
                   1146:                                 * Make sure the user knows we've continued the
                   1147:                                 * beast and actually put the thing in the job
                   1148:                                 * table.
                   1149:                                 */
                   1150:                                job->flags |= JOB_CONTINUING;
                   1151:                                W_SETTERMSIG(&status, SIGCONT);
                   1152:                                JobFinish(job, &status);
                   1153:
                   1154:                                job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1.84      espie    1155:                                debug_printf("done\n");
1.66      espie    1156:                        } else {
                   1157:                                Error("couldn't resume %s: %s",
                   1158:                                    job->node->name, strerror(errno));
                   1159:                                status = 0;
                   1160:                                W_SETEXITSTATUS(&status, 1);
                   1161:                                JobFinish(job, &status);
                   1162:                        }
                   1163:                } else {
                   1164:                        /*
                   1165:                         * Job cannot be restarted. Mark the table as full and
                   1166:                         * place the job back on the list of stopped jobs.
                   1167:                         */
1.84      espie    1168:                        debug_printf("table full\n");
1.66      espie    1169:                        Lst_AtFront(&stoppedJobs, job);
                   1170:                        jobFull = true;
1.84      espie    1171:                        debug_printf("Job queue is full.\n");
1.1       deraadt  1172:                }
                   1173:        }
                   1174: }
                   1175:
                   1176: /*-
                   1177:  *-----------------------------------------------------------------------
                   1178:  * JobStart  --
                   1179:  *     Start a target-creation process going for the target described
1.6       millert  1180:  *     by the graph node gn.
1.1       deraadt  1181:  *
                   1182:  * Results:
                   1183:  *     JOB_ERROR if there was an error in the commands, JOB_FINISHED
                   1184:  *     if there isn't actually anything left to do for the job and
                   1185:  *     JOB_RUNNING if the job has been started.
                   1186:  *
                   1187:  * Side Effects:
                   1188:  *     A new Job node is created and added to the list of running
                   1189:  *     jobs. PMake is forked and a child shell created.
                   1190:  *-----------------------------------------------------------------------
                   1191:  */
                   1192: static int
1.78      espie    1193: JobStart(GNode *gn,            /* target to create */
1.86      espie    1194:     int flags)                 /* flags for the job to override normal ones.
                   1195:                                 * e.g. JOB_SPECIAL */
1.78      espie    1196: {
                   1197:        Job *job;               /* new job descriptor */
                   1198:        char *argv[4];          /* Argument vector to shell */
                   1199:        bool cmdsOK;            /* true if the nodes commands were all right */
                   1200:        bool noExec;            /* Set true if we decide not to run the job */
1.87      espie    1201:        int fd[2];
1.66      espie    1202:
1.86      espie    1203:        job = emalloc(sizeof(Job));
                   1204:        if (job == NULL) {
                   1205:                Punt("JobStart out of memory");
1.1       deraadt  1206:        }
                   1207:
1.66      espie    1208:        job->node = gn;
                   1209:        job->tailCmds = NULL;
1.1       deraadt  1210:
                   1211:        /*
1.66      espie    1212:         * Set the initial value of the flags for this job based on the global
                   1213:         * ones and the node's attributes... Any flags supplied by the caller
                   1214:         * are also added to the field.
1.1       deraadt  1215:         */
1.87      espie    1216:        job->flags = flags;
1.66      espie    1217:        if (Targ_Ignore(gn)) {
                   1218:                job->flags |= JOB_IGNERR;
                   1219:        }
                   1220:        if (Targ_Silent(gn)) {
                   1221:                job->flags |= JOB_SILENT;
1.1       deraadt  1222:        }
1.6       millert  1223:
1.1       deraadt  1224:        /*
1.66      espie    1225:         * Check the commands now so any attributes from .DEFAULT have a chance
                   1226:         * to migrate to the node
1.1       deraadt  1227:         */
1.87      espie    1228:        cmdsOK = Job_CheckCommands(gn, Error);
1.1       deraadt  1229:
                   1230:        /*
1.66      espie    1231:         * If the -n flag wasn't given, we open up OUR (not the child's)
                   1232:         * temporary file to stuff commands in it. The thing is rd/wr so we
                   1233:         * don't need to reopen it to feed it to the shell. If the -n flag
                   1234:         * *was* given, we just set the file to be stdout. Cute, huh?
1.1       deraadt  1235:         */
1.66      espie    1236:        if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
                   1237:                /*
                   1238:                 * We're serious here, but if the commands were bogus, we're
                   1239:                 * also dead...
                   1240:                 */
                   1241:                if (!cmdsOK) {
                   1242:                        DieHorribly();
                   1243:                }
1.6       millert  1244:
1.88      espie    1245:                job->cmdFILE = new_command_file();
1.66      espie    1246:                if (job->cmdFILE == NULL) {
1.88      espie    1247:                        Punt("Error creating command file");
1.66      espie    1248:                }
1.90      espie    1249:                (void)fcntl(fileno(job->cmdFILE), F_SETFD, FD_CLOEXEC);
1.66      espie    1250:                /*
                   1251:                 * Send the commands to the command file, flush all its buffers
                   1252:                 * then rewind and remove the thing.
                   1253:                 */
                   1254:                noExec = false;
                   1255:
                   1256:                /*
1.85      espie    1257:                 * We can do all the commands at once. hooray for
                   1258:                 * sanity
1.66      espie    1259:                 */
1.85      espie    1260:                numCommands = 0;
                   1261:                Lst_ForEachNodeWhile(&gn->commands, JobPrintCommand,
                   1262:                    job);
1.66      espie    1263:
1.85      espie    1264:                /*
                   1265:                 * If we didn't print out any commands to the shell
                   1266:                 * script, there's not much point in executing the
                   1267:                 * shell, is there?
                   1268:                 */
                   1269:                if (numCommands == 0) {
                   1270:                        noExec = true;
1.66      espie    1271:                }
                   1272:        } else if (noExecute) {
                   1273:                /*
                   1274:                 * Not executing anything -- just print all the commands to
                   1275:                 * stdout in one fell swoop. This will still set up
                   1276:                 * job->tailCmds correctly.
                   1277:                 */
                   1278:                if (lastNode != gn) {
                   1279:                        MESSAGE(stdout, gn);
                   1280:                        lastNode = gn;
                   1281:                }
                   1282:                job->cmdFILE = stdout;
                   1283:                /*
                   1284:                 * Only print the commands if they're ok, but don't die if
                   1285:                 * they're not -- just let the user know they're bad and keep
                   1286:                 * going. It doesn't do any harm in this case and may do some
                   1287:                 * good.
                   1288:                 */
                   1289:                if (cmdsOK) {
1.68      espie    1290:                        Lst_ForEachNodeWhile(&gn->commands, JobPrintCommand,
1.66      espie    1291:                            job);
                   1292:                }
                   1293:                /*
                   1294:                 * Don't execute the shell, thank you.
                   1295:                 */
1.41      espie    1296:                noExec = true;
1.66      espie    1297:        } else {
                   1298:                /*
                   1299:                 * Just touch the target and note that no shell should be
                   1300:                 * executed.  Set cmdFILE to stdout to make life easier. Check
                   1301:                 * the commands, too, but don't die if they're no good -- it
                   1302:                 * does no harm to keep working up the graph.
1.30      espie    1303:                 */
1.66      espie    1304:                job->cmdFILE = stdout;
1.87      espie    1305:                Job_Touch(gn, job->flags & JOB_SILENT);
1.41      espie    1306:                noExec = true;
1.1       deraadt  1307:        }
1.66      espie    1308:
1.1       deraadt  1309:        /*
1.66      espie    1310:         * If we're not supposed to execute a shell, don't.
1.1       deraadt  1311:         */
1.66      espie    1312:        if (noExec) {
                   1313:                /*
                   1314:                 * Unlink and close the command file if we opened one
                   1315:                 */
                   1316:                if (job->cmdFILE != stdout) {
                   1317:                        if (job->cmdFILE != NULL)
                   1318:                                (void)fclose(job->cmdFILE);
                   1319:                } else {
                   1320:                         (void)fflush(stdout);
                   1321:                }
1.1       deraadt  1322:
1.66      espie    1323:                /*
                   1324:                 * We only want to work our way up the graph if we aren't here
                   1325:                 * because the commands for the job were no good.
                   1326:                 */
                   1327:                if (cmdsOK) {
                   1328:                        if (aborting == 0) {
1.68      espie    1329:                                Lst_ForEachFrom(job->tailCmds, JobSaveCommand,
1.66      espie    1330:                                    job->node);
                   1331:                                Make_Update(job->node);
                   1332:                        }
                   1333:                        free(job);
                   1334:                        return JOB_FINISHED;
                   1335:                } else {
                   1336:                        free(job);
                   1337:                        return JOB_ERROR;
                   1338:                }
1.1       deraadt  1339:        } else {
1.66      espie    1340:                (void)fflush(job->cmdFILE);
1.1       deraadt  1341:        }
                   1342:
                   1343:        /*
1.66      espie    1344:         * Set up the control arguments to the shell. This is based on the flags
                   1345:         * set earlier for this job.
1.1       deraadt  1346:         */
1.66      espie    1347:        JobMakeArgv(job, argv);
1.1       deraadt  1348:
1.90      espie    1349:        /* Create the pipe by which we'll get the shell's output.
1.66      espie    1350:         */
1.87      espie    1351:        if (pipe(fd) == -1)
                   1352:                Punt("Cannot create pipe: %s", strerror(errno));
                   1353:        job->inPipe = fd[0];
                   1354:        job->outPipe = fd[1];
1.90      espie    1355:        (void)fcntl(job->inPipe, F_SETFD, FD_CLOEXEC);
                   1356:        (void)fcntl(job->outPipe, F_SETFD, FD_CLOEXEC);
1.1       deraadt  1357:
1.83      espie    1358:        if (nJobs >= maxJobs && !(job->flags & JOB_SPECIAL) &&
                   1359:            maxJobs != 0) {
1.79      espie    1360:                /*
                   1361:                 * The job can only be run locally, but we've hit the limit of
                   1362:                 * local concurrency, so put the job on hold until some other
                   1363:                 * job finishes. Note that the special jobs (.BEGIN, .INTERRUPT
                   1364:                 * and .END) may be run locally even when the local limit has
1.83      espie    1365:                 * been reached (e.g. when maxJobs == 0), though they will be
1.79      espie    1366:                 * exported if at all possible. In addition, any target marked
1.83      espie    1367:                 * with .NOEXPORT will be run locally if maxJobs is 0.
1.66      espie    1368:                 */
                   1369:                jobFull = true;
1.6       millert  1370:
1.84      espie    1371:                debug_printf("Can only run job locally.\n");
1.66      espie    1372:                job->flags |= JOB_RESTART;
                   1373:                Lst_AtEnd(&stoppedJobs, job);
1.79      espie    1374:        } else {
1.83      espie    1375:                if (nJobs >= maxJobs) {
1.79      espie    1376:                        /*
                   1377:                         * If we're running this job locally as a special case
                   1378:                         * (see above), at least say the table is full.
                   1379:                         */
                   1380:                        jobFull = true;
1.84      espie    1381:                        debug_printf("Local job queue is full.\n");
1.79      espie    1382:                }
                   1383:                JobExec(job, argv);
1.1       deraadt  1384:        }
1.66      espie    1385:        return JOB_RUNNING;
1.1       deraadt  1386: }
                   1387:
1.6       millert  1388: static char *
1.56      espie    1389: JobOutput(Job *job, char *cp, char *endp, int msg)
1.2       deraadt  1390: {
1.66      espie    1391:        char *ecp;
1.2       deraadt  1392:
1.74      espie    1393:        ecp = strstr(cp, SHELL_ECHO_OFF);
                   1394:        while (ecp != NULL) {
                   1395:                if (cp != ecp) {
                   1396:                        *ecp = '\0';
                   1397:                        if (msg && job->node != lastNode) {
                   1398:                                MESSAGE(stdout, job->node);
                   1399:                                lastNode = job->node;
1.66      espie    1400:                        }
1.74      espie    1401:                        /*
1.78      espie    1402:                         * The only way there wouldn't be a newline after
                   1403:                         * this line is if it were the last in the buffer.
                   1404:                         * however, since the non-printable comes after it,
                   1405:                         * there must be a newline, so we don't print one.
1.74      espie    1406:                         */
                   1407:                        (void)fprintf(stdout, "%s", cp);
                   1408:                        (void)fflush(stdout);
                   1409:                }
                   1410:                cp = ecp + strlen(SHELL_ECHO_OFF);
                   1411:                if (cp != endp) {
                   1412:                        /*
1.78      espie    1413:                         * Still more to print, look again after skipping
                   1414:                         * the whitespace following the non-printable
                   1415:                         * command....
1.74      espie    1416:                         */
                   1417:                        cp++;
1.78      espie    1418:                        while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
1.66      espie    1419:                                cp++;
                   1420:                        }
1.74      espie    1421:                        ecp = strstr(cp, SHELL_ECHO_OFF);
                   1422:                } else {
                   1423:                        return cp;
1.2       deraadt  1424:                }
                   1425:        }
1.66      espie    1426:        return cp;
1.2       deraadt  1427: }
                   1428:
1.1       deraadt  1429: /*-
                   1430:  *-----------------------------------------------------------------------
1.40      espie    1431:  * JobDoOutput --
1.89      espie    1432:  *     This functions is called whenever there is something to read on the
                   1433:  *     pipe. We collect more output from the given job and store it in the
                   1434:  *     job's outBuf. If this makes up a line, we print it tagged by the job's
                   1435:  *     identifier, as necessary.
                   1436:  *     We also keep our figurative eye out for the
1.1       deraadt  1437:  *     'noPrint' line for the shell from which the output came. If
                   1438:  *     we recognize a line, we don't print it. If the command is not
1.6       millert  1439:  *     alone on the line (the character after it is not \0 or \n), we
1.1       deraadt  1440:  *     do print whatever follows it.
                   1441:  *
                   1442:  * Side Effects:
                   1443:  *     curPos may be shifted as may the contents of outBuf.
                   1444:  *-----------------------------------------------------------------------
                   1445:  */
1.48      espie    1446: static void
1.66      espie    1447: JobDoOutput(Job *job,          /* the job whose output needs printing */
                   1448:     bool finish)               /* true if this is the last time we'll be
                   1449:                                 * called for this job */
                   1450: {
1.78      espie    1451:        bool gotNL = false;     /* true if got a newline */
1.66      espie    1452:        bool fbuf;              /* true if our buffer filled up */
                   1453:        int nr;                 /* number of bytes read */
                   1454:        int i;                  /* auxiliary index into outBuf */
1.78      espie    1455:        int max;                /* limit for i (end of current data) */
                   1456:        int nRead;              /* (Temporary) number of bytes read */
1.1       deraadt  1457:
1.76      espie    1458:        /*
                   1459:         * Read as many bytes as will fit in the buffer.
                   1460:         */
1.1       deraadt  1461: end_loop:
1.76      espie    1462:        gotNL = false;
                   1463:        fbuf = false;
1.6       millert  1464:
1.76      espie    1465:        nRead = read(job->inPipe, &job->outBuf[job->curPos],
                   1466:            JOB_BUFSIZE - job->curPos);
                   1467:        if (nRead == -1) {
                   1468:                if (DEBUG(JOB)) {
                   1469:                        perror("JobDoOutput(piperead)");
1.66      espie    1470:                }
1.76      espie    1471:                nr = 0;
                   1472:        } else {
                   1473:                nr = nRead;
                   1474:        }
1.1       deraadt  1475:
1.76      espie    1476:        /*
1.78      espie    1477:         * If we hit the end-of-file (the job is dead), we must flush its
                   1478:         * remaining output, so pretend we read a newline if there's any
                   1479:         * output remaining in the buffer.
                   1480:         * Also clear the 'finish' flag so we stop looping.
1.76      espie    1481:         */
                   1482:        if (nr == 0 && job->curPos != 0) {
                   1483:                job->outBuf[job->curPos] = '\n';
                   1484:                nr = 1;
                   1485:                finish = false;
                   1486:        } else if (nr == 0) {
                   1487:                finish = false;
                   1488:        }
1.6       millert  1489:
1.76      espie    1490:        /*
1.78      espie    1491:         * Look for the last newline in the bytes we just got. If there is
                   1492:         * one, break out of the loop with 'i' as its index and gotNL set
                   1493:         * true.
1.76      espie    1494:         */
                   1495:        max = job->curPos + nr;
                   1496:        for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
                   1497:                if (job->outBuf[i] == '\n') {
                   1498:                        gotNL = true;
                   1499:                        break;
                   1500:                } else if (job->outBuf[i] == '\0') {
                   1501:                        /*
1.89      espie    1502:                         * To be fixed: don't use printf, it stops at NUL bytes.
1.76      espie    1503:                         */
                   1504:                        job->outBuf[i] = ' ';
1.66      espie    1505:                }
1.76      espie    1506:        }
1.6       millert  1507:
1.76      espie    1508:        if (!gotNL) {
                   1509:                job->curPos += nr;
                   1510:                if (job->curPos == JOB_BUFSIZE) {
1.66      espie    1511:                        /*
1.78      espie    1512:                         * If we've run out of buffer space, we have no choice
                   1513:                         * but to print the stuff. sigh.
1.66      espie    1514:                         */
1.76      espie    1515:                        fbuf = true;
                   1516:                        i = job->curPos;
                   1517:                }
                   1518:        }
                   1519:        if (gotNL || fbuf) {
                   1520:                /*
1.78      espie    1521:                 * Need to send the output to the screen. Null terminate it
                   1522:                 * first, overwriting the newline character if there was one.
                   1523:                 * So long as the line isn't one we should filter (according
                   1524:                 * to the shell description), we print the line, preceded
                   1525:                 * by a target banner if this target isn't the same as the
                   1526:                 * one for which we last printed something.
                   1527:                 * The rest of the data in the buffer are then shifted down
                   1528:                 * to the start of the buffer and curPos is set accordingly.
1.76      espie    1529:                 */
                   1530:                job->outBuf[i] = '\0';
                   1531:                if (i >= job->curPos) {
                   1532:                        char *cp;
1.66      espie    1533:
1.78      espie    1534:                        cp = JobOutput(job, job->outBuf, &job->outBuf[i],
                   1535:                            false);
1.66      espie    1536:
1.76      espie    1537:                        /*
1.78      espie    1538:                         * There's still more in that thar buffer. This time,
                   1539:                         * though, we know there's no newline at the end, so we
                   1540:                         * add one of our own free will.
1.76      espie    1541:                         */
                   1542:                        if (*cp != '\0') {
                   1543:                                if (job->node != lastNode) {
                   1544:                                        MESSAGE(stdout, job->node);
                   1545:                                        lastNode = job->node;
1.66      espie    1546:                                }
1.76      espie    1547:                                (void)fprintf(stdout, "%s%s", cp,
                   1548:                                    gotNL ? "\n" : "");
                   1549:                                (void)fflush(stdout);
1.66      espie    1550:                        }
1.76      espie    1551:                }
                   1552:                if (i < max - 1) {
                   1553:                        /* shift the remaining characters down */
                   1554:                        (void)memcpy(job->outBuf, &job->outBuf[i + 1],
                   1555:                            max - (i + 1));
                   1556:                        job->curPos = max - (i + 1);
1.66      espie    1557:
1.76      espie    1558:                } else {
1.66      espie    1559:                        /*
1.78      espie    1560:                         * We have written everything out, so we just start over
                   1561:                         * from the start of the buffer. No copying. No nothing.
1.66      espie    1562:                         */
1.76      espie    1563:                        job->curPos = 0;
1.66      espie    1564:                }
1.76      espie    1565:        }
                   1566:        if (finish) {
1.66      espie    1567:                /*
1.78      espie    1568:                 * If the finish flag is true, we must loop until we hit
                   1569:                 * end-of-file on the pipe. This is guaranteed to happen
                   1570:                 * eventually since the other end of the pipe is now closed
                   1571:                 * (we closed it explicitly and the child has exited). When
                   1572:                 * we do get an EOF, finish will be set false and we'll fall
                   1573:                 * through and out.
1.76      espie    1574:                 */
                   1575:                goto end_loop;
1.1       deraadt  1576:        }
                   1577: }
                   1578:
                   1579: /*-
                   1580:  *-----------------------------------------------------------------------
                   1581:  * Job_CatchChildren --
                   1582:  *     Handle the exit of a child. Called from Make_Make.
                   1583:  *
                   1584:  * Side Effects:
                   1585:  *     The job descriptor is removed from the list of children.
                   1586:  *
                   1587:  * Notes:
                   1588:  *     We do waits, blocking or not, according to the wisdom of our
                   1589:  *     caller, until there are no more children to report. For each
                   1590:  *     job, call JobFinish to finish things off. This will take care of
                   1591:  *     putting jobs on the stoppedJobs queue.
                   1592:  *-----------------------------------------------------------------------
                   1593:  */
                   1594: void
1.76      espie    1595: Job_CatchChildren()
1.1       deraadt  1596: {
1.78      espie    1597:        pid_t pid;      /* pid of dead child */
                   1598:        Job *job;       /* job descriptor for dead child */
                   1599:        LstNode jnode;  /* list element for finding job */
                   1600:        int status;     /* Exit/termination status */
1.1       deraadt  1601:
1.66      espie    1602:        /*
                   1603:         * Don't even bother if we know there's no one around.
                   1604:         */
1.83      espie    1605:        if (nJobs == 0) {
1.66      espie    1606:                return;
1.2       deraadt  1607:        }
1.6       millert  1608:
1.76      espie    1609:        while ((pid = waitpid((pid_t) -1, &status, WNOHANG|WUNTRACED)) > 0) {
1.93      espie    1610:                handle_all_signals();
1.84      espie    1611:                debug_printf("Process %ld exited or stopped.\n", (long)pid);
1.1       deraadt  1612:
1.66      espie    1613:                jnode = Lst_Find(&jobs, JobCmpPid, &pid);
1.1       deraadt  1614:
1.18      espie    1615:                if (jnode == NULL) {
1.68      espie    1616:                        if (WIFSIGNALED(status) &&
1.66      espie    1617:                            (WTERMSIG(status) == SIGCONT)) {
                   1618:                                jnode = Lst_Find(&stoppedJobs, JobCmpPid, &pid);
                   1619:                                if (jnode == NULL) {
                   1620:                                        Error("Resumed child (%ld) not in table", (long)pid);
                   1621:                                        continue;
                   1622:                                }
                   1623:                                job = (Job *)Lst_Datum(jnode);
                   1624:                                Lst_Remove(&stoppedJobs, jnode);
                   1625:                        } else {
                   1626:                                Error("Child (%ld) not in table?", (long)pid);
                   1627:                                continue;
                   1628:                        }
                   1629:                } else {
                   1630:                        job = (Job *)Lst_Datum(jnode);
                   1631:                        Lst_Remove(&jobs, jnode);
1.67      espie    1632:                        nJobs--;
1.84      espie    1633:                        if (jobFull)
                   1634:                                debug_printf("Job queue is no longer full.\n");
1.66      espie    1635:                        jobFull = false;
1.1       deraadt  1636:                }
1.66      espie    1637:
                   1638:                JobFinish(job, &status);
1.1       deraadt  1639:        }
                   1640: }
                   1641:
                   1642: /*-
                   1643:  *-----------------------------------------------------------------------
                   1644:  * Job_CatchOutput --
                   1645:  *     Catch the output from our children, if we're using
                   1646:  *     pipes do so. Otherwise just block time until we get a
1.6       millert  1647:  *     signal (most likely a SIGCHLD) since there's no point in
1.1       deraadt  1648:  *     just spinning when there's nothing to do and the reaping
1.6       millert  1649:  *     of a child can wait for a while.
1.1       deraadt  1650:  *
                   1651:  * Side Effects:
                   1652:  *     Output is read from pipes if we're piping.
                   1653:  * -----------------------------------------------------------------------
                   1654:  */
                   1655: void
1.56      espie    1656: Job_CatchOutput(void)
1.1       deraadt  1657: {
1.66      espie    1658:        int nfds;
                   1659:        struct timeval timeout;
                   1660:        LstNode ln;
                   1661:        Job *job;
                   1662:
1.76      espie    1663:        int count = howmany(outputsn+1, NFDBITS) * sizeof(fd_mask);
                   1664:        fd_set *readfdsp = malloc(count);
1.91      espie    1665:
1.77      espie    1666:        (void)fflush(stdout);
1.76      espie    1667:        if (readfdsp == NULL)
                   1668:                return;
                   1669:
                   1670:        memcpy(readfdsp, outputsp, count);
                   1671:        timeout.tv_sec = SEL_SEC;
                   1672:        timeout.tv_usec = SEL_USEC;
1.66      espie    1673:
1.91      espie    1674:        nfds = select(outputsn+1, readfdsp, NULL, NULL, &timeout);
1.93      espie    1675:        handle_all_signals();
1.91      espie    1676:        if (nfds > 0) {
1.76      espie    1677:                for (ln = Lst_First(&jobs); nfds && ln != NULL;
                   1678:                    ln = Lst_Adv(ln)) {
                   1679:                        job = (Job *)Lst_Datum(ln);
                   1680:                        if (FD_ISSET(job->inPipe, readfdsp)) {
                   1681:                                JobDoOutput(job, false);
                   1682:                                nfds--;
1.66      espie    1683:                        }
1.1       deraadt  1684:                }
                   1685:        }
1.76      espie    1686:        free(readfdsp);
1.1       deraadt  1687: }
                   1688:
                   1689: /*-
                   1690:  *-----------------------------------------------------------------------
                   1691:  * Job_Make --
                   1692:  *     Start the creation of a target. Basically a front-end for
                   1693:  *     JobStart used by the Make module.
                   1694:  *
                   1695:  * Side Effects:
                   1696:  *     Another job is started.
                   1697:  *-----------------------------------------------------------------------
                   1698:  */
                   1699: void
1.56      espie    1700: Job_Make(GNode *gn)
1.1       deraadt  1701: {
1.86      espie    1702:        (void)JobStart(gn, 0);
1.1       deraadt  1703: }
                   1704:
1.93      espie    1705: static void
                   1706: setup_signal(int sig)
                   1707: {
                   1708:        if (signal(sig, SIG_IGN) != SIG_IGN) {
                   1709:                (void)signal(sig, SigHandler);
                   1710:        }
                   1711: }
                   1712:
1.94    ! espie    1713: static void
        !          1714: setup_all_signals()
        !          1715: {
        !          1716:        /*
        !          1717:         * Catch the four signals that POSIX specifies if they aren't ignored.
        !          1718:         * handle_signal will take care of calling JobInterrupt if appropriate.
        !          1719:         */
        !          1720:        setup_signal(SIGINT);
        !          1721:        setup_signal(SIGHUP);
        !          1722:        setup_signal(SIGQUIT);
        !          1723:        setup_signal(SIGTERM);
        !          1724:        /*
        !          1725:         * There are additional signals that need to be caught and passed if
        !          1726:         * either the export system wants to be told directly of signals or if
        !          1727:         * we're giving each job its own process group (since then it won't get
        !          1728:         * signals from the terminal driver as we own the terminal)
        !          1729:         */
        !          1730: #if defined(USE_PGRP)
        !          1731:        setup_signal(SIGTSTP);
        !          1732:        setup_signal(SIGTTOU);
        !          1733:        setup_signal(SIGTTIN);
        !          1734:        setup_signal(SIGWINCH);
        !          1735: #endif
        !          1736: }
        !          1737:
1.1       deraadt  1738: /*-
                   1739:  *-----------------------------------------------------------------------
                   1740:  * Job_Init --
                   1741:  *     Initialize the process module
                   1742:  *
                   1743:  * Side Effects:
                   1744:  *     lists and counters are initialized
                   1745:  *-----------------------------------------------------------------------
                   1746:  */
                   1747: void
1.83      espie    1748: Job_Init(int maxproc)
1.1       deraadt  1749: {
1.66      espie    1750:        Static_Lst_Init(&jobs);
                   1751:        Static_Lst_Init(&stoppedJobs);
                   1752:        maxJobs =         maxproc;
1.79      espie    1753:        nJobs =           0;
1.66      espie    1754:        jobFull =         false;
                   1755:
                   1756:        aborting =        0;
                   1757:        errors =          0;
1.40      espie    1758:
1.66      espie    1759:        lastNode =        NULL;
1.1       deraadt  1760:
1.66      espie    1761:        if (maxJobs == 1) {
                   1762:                /*
                   1763:                 * If only one job can run at a time, there's no need for a
                   1764:                 * banner, no is there?
                   1765:                 */
                   1766:                targFmt = "";
                   1767:        } else {
                   1768:                targFmt = TARG_FMT;
                   1769:        }
1.6       millert  1770:
1.78      espie    1771:        if ((begin_node->type & OP_DUMMY) == 0) {
1.86      espie    1772:                JobStart(begin_node, JOB_SPECIAL);
1.66      espie    1773:                while (nJobs) {
                   1774:                        Job_CatchOutput();
1.76      espie    1775:                        Job_CatchChildren();
1.66      espie    1776:                }
1.1       deraadt  1777:        }
                   1778: }
                   1779:
                   1780: /*-
                   1781:  *-----------------------------------------------------------------------
                   1782:  * Job_Full --
                   1783:  *     See if the job table is full. It is considered full if it is OR
                   1784:  *     if we are in the process of aborting OR if we have
                   1785:  *     reached/exceeded our local quota. This prevents any more jobs
                   1786:  *     from starting up.
                   1787:  *
                   1788:  * Results:
1.41      espie    1789:  *     true if the job table is full, false otherwise
1.1       deraadt  1790:  *-----------------------------------------------------------------------
                   1791:  */
1.41      espie    1792: bool
1.56      espie    1793: Job_Full(void)
1.1       deraadt  1794: {
1.66      espie    1795:        return aborting || jobFull;
1.1       deraadt  1796: }
                   1797:
                   1798: /*-
                   1799:  *-----------------------------------------------------------------------
                   1800:  * Job_Empty --
1.40      espie    1801:  *     See if the job table is empty.  Because the local concurrency may
1.1       deraadt  1802:  *     be set to 0, it is possible for the job table to become empty,
                   1803:  *     while the list of stoppedJobs remains non-empty. In such a case,
                   1804:  *     we want to restart as many jobs as we can.
                   1805:  *
                   1806:  * Results:
1.41      espie    1807:  *     true if it is. false if it ain't.
1.1       deraadt  1808:  * -----------------------------------------------------------------------
                   1809:  */
1.41      espie    1810: bool
1.56      espie    1811: Job_Empty(void)
1.1       deraadt  1812: {
1.66      espie    1813:        if (nJobs == 0) {
                   1814:                if (!Lst_IsEmpty(&stoppedJobs) && !aborting) {
                   1815:                        /*
                   1816:                         * The job table is obviously not full if it has no
                   1817:                         * jobs in it...Try and restart the stopped jobs.
                   1818:                         */
                   1819:                        jobFull = false;
                   1820:                        JobRestartJobs();
                   1821:                        return false;
                   1822:                } else {
                   1823:                        return true;
                   1824:                }
1.1       deraadt  1825:        } else {
1.66      espie    1826:                return false;
1.1       deraadt  1827:        }
                   1828: }
                   1829:
                   1830: /*-
                   1831:  *-----------------------------------------------------------------------
                   1832:  * JobInterrupt --
                   1833:  *     Handle the receipt of an interrupt.
                   1834:  *
                   1835:  * Side Effects:
                   1836:  *     All children are killed. Another job will be started if the
                   1837:  *     .INTERRUPT target was given.
                   1838:  *-----------------------------------------------------------------------
                   1839:  */
                   1840: static void
1.56      espie    1841: JobInterrupt(int runINTERRUPT, /* Non-zero if commands for the .INTERRUPT
1.1       deraadt  1842:                                 * target should be executed */
1.66      espie    1843:     int signo)                 /* signal received */
1.1       deraadt  1844: {
1.66      espie    1845:        LstNode ln;             /* element in job table */
1.78      espie    1846:        Job *job;               /* job descriptor in that element */
1.66      espie    1847:
                   1848:        aborting = ABORT_INTERRUPT;
                   1849:
                   1850:        for (ln = Lst_First(&jobs); ln != NULL; ln = Lst_Adv(ln)) {
                   1851:                job = (Job *)Lst_Datum(ln);
                   1852:
                   1853:                if (!Targ_Precious(job->node)) {
                   1854:                        const char *file = job->node->path == NULL ?
                   1855:                            job->node->name : job->node->path;
                   1856:                        if (!noExecute && eunlink(file) != -1) {
                   1857:                                Error("*** %s removed", file);
                   1858:                        }
                   1859:                }
                   1860:                if (job->pid) {
1.84      espie    1861:                        debug_printf("JobInterrupt passing signal to "
                   1862:                            "child %ld.\n", (long)job->pid);
1.66      espie    1863:                        KILL(job->pid, signo);
                   1864:                }
1.2       deraadt  1865:        }
1.1       deraadt  1866:
1.66      espie    1867:        if (runINTERRUPT && !touchFlag) {
1.78      espie    1868:                if ((interrupt_node->type & OP_DUMMY) == 0) {
1.66      espie    1869:                        ignoreErrors = false;
                   1870:
1.86      espie    1871:                        JobStart(interrupt_node, JOB_IGNDOTS);
1.66      espie    1872:                        while (nJobs) {
                   1873:                                Job_CatchOutput();
1.76      espie    1874:                                Job_CatchChildren();
1.66      espie    1875:                        }
                   1876:                }
1.1       deraadt  1877:        }
1.66      espie    1878:        exit(signo);
1.1       deraadt  1879: }
                   1880:
                   1881: /*
                   1882:  *-----------------------------------------------------------------------
1.12      espie    1883:  * Job_Finish --
1.1       deraadt  1884:  *     Do final processing such as the running of the commands
1.6       millert  1885:  *     attached to the .END target.
1.1       deraadt  1886:  *
                   1887:  * Results:
                   1888:  *     Number of errors reported.
1.40      espie    1889:  *
1.1       deraadt  1890:  *-----------------------------------------------------------------------
                   1891:  */
                   1892: int
1.56      espie    1893: Job_Finish(void)
1.1       deraadt  1894: {
1.78      espie    1895:        if (end_node != NULL && !Lst_IsEmpty(&end_node->commands)) {
1.66      espie    1896:                if (errors) {
                   1897:                        Error("Errors reported so .END ignored");
                   1898:                } else {
1.86      espie    1899:                        JobStart(end_node, JOB_SPECIAL | JOB_IGNDOTS);
1.1       deraadt  1900:
1.66      espie    1901:                        while (nJobs) {
                   1902:                                Job_CatchOutput();
1.76      espie    1903:                                Job_CatchChildren();
1.66      espie    1904:                        }
                   1905:                }
1.1       deraadt  1906:        }
1.66      espie    1907:        return errors;
1.1       deraadt  1908: }
                   1909:
1.41      espie    1910: #ifdef CLEANUP
1.12      espie    1911: void
1.56      espie    1912: Job_End(void)
1.12      espie    1913: {
1.41      espie    1914: }
1.13      espie    1915: #endif
1.40      espie    1916:
1.1       deraadt  1917: /*-
                   1918:  *-----------------------------------------------------------------------
                   1919:  * Job_Wait --
                   1920:  *     Waits for all running jobs to finish and returns. Sets 'aborting'
                   1921:  *     to ABORT_WAIT to prevent other jobs from starting.
                   1922:  *
                   1923:  * Side Effects:
                   1924:  *     Currently running jobs finish.
                   1925:  *
                   1926:  *-----------------------------------------------------------------------
                   1927:  */
                   1928: void
1.56      espie    1929: Job_Wait(void)
1.1       deraadt  1930: {
1.66      espie    1931:        aborting = ABORT_WAIT;
                   1932:        while (nJobs != 0) {
                   1933:                Job_CatchOutput();
1.76      espie    1934:                Job_CatchChildren();
1.66      espie    1935:        }
                   1936:        aborting = 0;
1.1       deraadt  1937: }
                   1938:
                   1939: /*-
                   1940:  *-----------------------------------------------------------------------
                   1941:  * Job_AbortAll --
                   1942:  *     Abort all currently running jobs without handling output or anything.
                   1943:  *     This function is to be called only in the event of a major
                   1944:  *     error. Most definitely NOT to be called from JobInterrupt.
                   1945:  *
                   1946:  * Side Effects:
                   1947:  *     All children are killed, not just the firstborn
                   1948:  *-----------------------------------------------------------------------
                   1949:  */
                   1950: void
1.56      espie    1951: Job_AbortAll(void)
1.1       deraadt  1952: {
1.66      espie    1953:        LstNode ln;     /* element in job table */
                   1954:        Job *job;       /* the job descriptor in that element */
                   1955:        int foo;
1.6       millert  1956:
1.66      espie    1957:        aborting = ABORT_ERROR;
1.6       millert  1958:
1.66      espie    1959:        if (nJobs) {
                   1960:                for (ln = Lst_First(&jobs); ln != NULL; ln = Lst_Adv(ln)) {
                   1961:                        job = (Job *)Lst_Datum(ln);
                   1962:
                   1963:                        /*
                   1964:                         * kill the child process with increasingly drastic
                   1965:                         * signals to make darn sure it's dead.
                   1966:                         */
                   1967:                        KILL(job->pid, SIGINT);
                   1968:                        KILL(job->pid, SIGKILL);
                   1969:                }
1.1       deraadt  1970:        }
1.6       millert  1971:
1.66      espie    1972:        /*
                   1973:         * Catch as many children as want to report in at first, then give up
                   1974:         */
                   1975:        while (waitpid(-1, &foo, WNOHANG) > 0)
                   1976:                continue;
1.2       deraadt  1977: }
1.40      espie    1978:
1.2       deraadt  1979: /*-
                   1980:  *-----------------------------------------------------------------------
                   1981:  * JobRestartJobs --
                   1982:  *     Tries to restart stopped jobs if there are slots available.
                   1983:  *     Note that this tries to restart them regardless of pending errors.
                   1984:  *     It's not good to leave stopped jobs lying around!
                   1985:  *
                   1986:  * Side Effects:
                   1987:  *     Resumes(and possibly migrates) jobs.
                   1988:  *-----------------------------------------------------------------------
                   1989:  */
                   1990: static void
1.56      espie    1991: JobRestartJobs(void)
1.2       deraadt  1992: {
1.66      espie    1993:        Job *job;
1.19      espie    1994:
1.66      espie    1995:        while (!jobFull && (job = (Job *)Lst_DeQueue(&stoppedJobs)) != NULL) {
1.84      espie    1996:                debug_printf("Job queue is not full. "
                   1997:                    "Restarting a stopped job.\n");
1.66      espie    1998:                JobRestart(job);
1.2       deraadt  1999:        }
1.1       deraadt  2000: }