[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.72

1.40      espie       1: /*     $OpenPackages$ */
1.72    ! espie       2: /*     $OpenBSD: job.c,v 1.71 2007/09/17 10:28:48 espie Exp $  */
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.
1.41      espie      51:  *                             Its single argument is true if the function
1.40      espie      52:  *                             should block waiting for a child to terminate.
                     53:  *
                     54:  *     Job_CatchOutput         Print any output our children have produced.
                     55:  *                             Should also be called fairly frequently to
                     56:  *                             keep the user informed of what's going on.
                     57:  *                             If no output is waiting, it will block for
                     58:  *                             a time given by the SEL_* constants, below,
                     59:  *                             or until output is ready.
                     60:  *
1.53      jmc        61:  *     Job_Init                Called to initialize this module. in addition,
1.40      espie      62:  *                             any commands attached to the .BEGIN target
                     63:  *                             are executed before this function returns.
                     64:  *                             Hence, the makefile must have been parsed
                     65:  *                             before this function is called.
                     66:  *
                     67:  *     Job_End                 Cleanup any memory used.
                     68:  *
1.41      espie      69:  *     Job_Full                Return true if the job table is filled.
1.40      espie      70:  *
1.41      espie      71:  *     Job_Empty               Return true if the job table is completely
1.40      espie      72:  *                             empty.
                     73:  *
                     74:  *     Job_Finish              Perform any final processing which needs doing.
                     75:  *                             This includes the execution of any commands
                     76:  *                             which have been/were attached to the .END
                     77:  *                             target. It should only be called when the
                     78:  *                             job table is empty.
                     79:  *
                     80:  *     Job_AbortAll            Abort all currently running jobs. It doesn't
                     81:  *                             handle output or do anything for the jobs,
                     82:  *                             just kills them. It should only be called in
                     83:  *                             an emergency, as it were.
1.1       deraadt    84:  *
1.40      espie      85:  *     Job_Wait                Wait for all currently-running jobs to finish.
1.1       deraadt    86:  */
                     87:
                     88: #include <sys/types.h>
                     89: #include <sys/wait.h>
1.41      espie      90: #include <ctype.h>
                     91: #include <errno.h>
1.1       deraadt    92: #include <fcntl.h>
1.41      espie      93: #include <signal.h>
1.69      espie      94: #include <stdarg.h>
1.1       deraadt    95: #include <stdio.h>
1.42      espie      96: #include <stdlib.h>
1.1       deraadt    97: #include <string.h>
1.41      espie      98: #include <unistd.h>
                     99: #include "config.h"
                    100: #include "defines.h"
1.1       deraadt   101: #include "job.h"
1.63      espie     102: #include "engine.h"
1.1       deraadt   103: #include "pathnames.h"
1.41      espie     104: #include "var.h"
                    105: #include "targ.h"
                    106: #include "error.h"
                    107: #include "lst.h"
                    108: #include "extern.h"
                    109: #include "gnode.h"
                    110: #include "memory.h"
                    111: #include "make.h"
                    112:
1.50      espie     113: #define TMPPAT "/tmp/makeXXXXXXXXXX"
                    114:
                    115: /*
                    116:  * The SEL_ constants determine the maximum amount of time spent in select
                    117:  * before coming out to see if a child has finished. SEL_SEC is the number of
                    118:  * seconds and SEL_USEC is the number of micro-seconds
                    119:  */
                    120: #define SEL_SEC        0
                    121: #define SEL_USEC       500000
                    122:
                    123:
                    124: /*-
                    125:  * Job Table definitions.
                    126:  *
                    127:  * Each job has several things associated with it:
                    128:  *     1) The process id of the child shell
                    129:  *     2) The graph node describing the target being made by this job
                    130:  *     3) A LstNode for the first command to be saved after the job
                    131:  *        completes. This is NULL if there was no "..." in the job's
                    132:  *        commands.
                    133:  *     4) An FILE* for writing out the commands. This is only
                    134:  *        used before the job is actually started.
                    135:  *     5) A union of things used for handling the shell's output. Different
                    136:  *        parts of the union are used based on the value of the usePipes
                    137:  *        flag. If it is true, the output is being caught via a pipe and
                    138:  *        the descriptors of our pipe, an array in which output is line
                    139:  *        buffered and the current position in that buffer are all
                    140:  *        maintained for each job. If, on the other hand, usePipes is false,
                    141:  *        the output is routed to a temporary file and all that is kept
                    142:  *        is the name of the file and the descriptor open to the file.
                    143:  *     6) An identifier provided by and for the exclusive use of the
                    144:  *        Rmt module.
                    145:  *     7) A word of flags which determine how the module handles errors,
                    146:  *        echoing, etc. for the job
                    147:  *
                    148:  * The job "table" is kept as a linked Lst in 'jobs', with the number of
                    149:  * active jobs maintained in the 'nJobs' variable. At no time will this
                    150:  * exceed the value of 'maxJobs', initialized by the Job_Init function.
                    151:  *
                    152:  * When a job is finished, the Make_Update function is called on each of the
                    153:  * parents of the node which was just remade. This takes care of the upward
                    154:  * traversal of the dependency graph.
                    155:  */
                    156: #define JOB_BUFSIZE    1024
                    157: typedef struct Job_ {
1.51      mpech     158:     pid_t      pid;        /* The child's process ID */
1.50      espie     159:     GNode      *node;      /* The target the child is making */
                    160:     LstNode    tailCmds;   /* The node of the first command to be
                    161:                             * saved when the job has been run */
                    162:     FILE       *cmdFILE;   /* When creating the shell script, this is
                    163:                             * where the commands go */
                    164:     int        rmtID;     /* ID returned from Rmt module */
                    165:     short      flags;      /* Flags to control treatment of job */
                    166: #define JOB_IGNERR     0x001   /* Ignore non-zero exits */
                    167: #define JOB_SILENT     0x002   /* no output */
                    168: #define JOB_SPECIAL    0x004   /* Target is a special one. i.e. run it locally
                    169:                                 * if we can't export it and maxLocal is 0 */
                    170: #define JOB_IGNDOTS    0x008   /* Ignore "..." lines when processing
                    171:                                 * commands */
                    172: #define JOB_FIRST      0x020   /* Job is first job for the node */
                    173: #define JOB_RESTART    0x080   /* Job needs to be completely restarted */
                    174: #define JOB_RESUME     0x100   /* Job needs to be resumed b/c it stopped,
                    175:                                 * for some reason */
                    176: #define JOB_CONTINUING 0x200   /* We are in the process of resuming this job.
                    177:                                 * Used to avoid infinite recursion between
                    178:                                 * JobFinish and JobRestart */
                    179:     union {
                    180:        struct {
                    181:            int         op_inPipe;      /* Input side of pipe associated
                    182:                                         * with job's output channel */
                    183:            int         op_outPipe;     /* Output side of pipe associated with
                    184:                                         * job's output channel */
                    185:            char        op_outBuf[JOB_BUFSIZE + 1];
                    186:                                        /* Buffer for storing the output of the
                    187:                                         * job, line by line */
                    188:            int         op_curPos;      /* Current position in op_outBuf */
                    189:        }           o_pipe;         /* data used when catching the output via
                    190:                                     * a pipe */
                    191:        struct {
                    192:            char        of_outFile[sizeof(TMPPAT)];
                    193:                                        /* Name of file to which shell output
                    194:                                         * was rerouted */
                    195:            int         of_outFd;       /* Stream open to the output
                    196:                                         * file. Used to funnel all
                    197:                                         * from a single job to one file
                    198:                                         * while still allowing
                    199:                                         * multiple shell invocations */
                    200:        }           o_file;         /* Data used when catching the output in
                    201:                                     * a temporary file */
                    202:     }          output;     /* Data for tracking a shell's output */
                    203: } Job;
                    204:
                    205: #define outPipe        output.o_pipe.op_outPipe
                    206: #define inPipe         output.o_pipe.op_inPipe
                    207: #define outBuf         output.o_pipe.op_outBuf
                    208: #define curPos         output.o_pipe.op_curPos
                    209: #define outFile        output.o_file.of_outFile
                    210: #define outFd          output.o_file.of_outFd
                    211:
                    212:
                    213: /*-
                    214:  * Shell Specifications:
                    215:  * Each shell type has associated with it the following information:
                    216:  *     1) The string which must match the last character of the shell name
                    217:  *        for the shell to be considered of this type. The longest match
                    218:  *        wins.
                    219:  *     2) A command to issue to turn off echoing of command lines
                    220:  *     3) A command to issue to turn echoing back on again
                    221:  *     4) What the shell prints, and its length, when given the echo-off
                    222:  *        command. This line will not be printed when received from the shell
                    223:  *     5) A boolean to tell if the shell has the ability to control
                    224:  *        error checking for individual commands.
                    225:  *     6) The string to turn this checking on.
                    226:  *     7) The string to turn it off.
                    227:  *     8) The command-flag to give to cause the shell to start echoing
                    228:  *        commands right away.
                    229:  *     9) The command-flag to cause the shell to Lib_Exit when an error is
                    230:  *        detected in one of the commands.
                    231:  *
                    232:  * Some special stuff goes on if a shell doesn't have error control. In such
                    233:  * a case, errCheck becomes a printf template for echoing the command,
                    234:  * should echoing be on and ignErr becomes another printf template for
                    235:  * executing the command while ignoring the return status. If either of these
                    236:  * strings is empty when hasErrCtl is false, the command will be executed
                    237:  * anyway as is and if it causes an error, so be it.
                    238:  */
                    239: typedef struct Shell_ {
                    240:     char         *name;        /* the name of the shell. For Bourne and C
                    241:                                 * shells, this is used only to find the
                    242:                                 * shell description when used as the single
                    243:                                 * source of a .SHELL target. For user-defined
                    244:                                 * shells, this is the full path of the shell.
                    245:                                 */
                    246:     bool         hasEchoCtl;   /* True if both echoOff and echoOn defined */
                    247:     char         *echoOff;     /* command to turn off echo */
                    248:     char         *echoOn;      /* command to turn it back on again */
                    249:     char         *noPrint;     /* command to skip when printing output from
                    250:                                 * shell. This is usually the command which
                    251:                                 * was executed to turn off echoing */
                    252:     int          noPLen;       /* length of noPrint command */
                    253:     bool         hasErrCtl;    /* set if can control error checking for
                    254:                                 * individual commands */
                    255:     char         *errCheck;    /* string to turn error checking on */
                    256:     char         *ignErr;      /* string to turn off error checking */
                    257:     /*
                    258:      * command-line flags
                    259:      */
                    260:     char         *echo;        /* echo commands */
                    261:     char         *exit;        /* exit on error */
                    262: }              Shell;
                    263:
1.1       deraadt   264: /*
1.6       millert   265:  * error handling variables
1.1       deraadt   266:  */
1.40      espie     267: static int     errors = 0;         /* number of errors reported */
                    268: static int     aborting = 0;       /* why is the make aborting? */
                    269: #define ABORT_ERROR    1           /* Because of an error */
                    270: #define ABORT_INTERRUPT 2          /* Because it was interrupted */
                    271: #define ABORT_WAIT     3           /* Waiting for jobs to finish */
1.1       deraadt   272:
1.6       millert   273: /*
1.2       deraadt   274:  * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file
                    275:  * is a char! So when we go above 127 we turn negative!
                    276:  */
                    277: #define FILENO(a) ((unsigned) fileno(a))
1.1       deraadt   278:
                    279: /*
                    280:  * post-make command processing. The node postCommands is really just the
                    281:  * .END target but we keep it around to avoid having to search for it
                    282:  * all the time.
                    283:  */
1.40      espie     284: static GNode     *postCommands;    /* node containing commands to execute when
1.1       deraadt   285:                                     * everything else is done */
1.40      espie     286: static int       numCommands;      /* The number of commands actually printed
1.1       deraadt   287:                                     * for a target. Should this number be
                    288:                                     * 0, no shell will be executed. */
                    289:
                    290: /*
                    291:  * Return values from JobStart.
                    292:  */
1.40      espie     293: #define JOB_RUNNING    0       /* Job is running */
                    294: #define JOB_ERROR      1       /* Error in starting the job */
                    295: #define JOB_FINISHED   2       /* The job is already finished */
                    296: #define JOB_STOPPED    3       /* The job is stopped */
1.1       deraadt   297:
                    298: /*
1.40      espie     299:  * tfile is the name of a file into which all shell commands are put. It is
                    300:  * used over by removing it before the child shell is executed. The XXXXXXXXXX
                    301:  * in the string are replaced by mkstemp(3).
1.1       deraadt   302:  */
1.40      espie     303: static char    tfile[sizeof(TMPPAT)];
1.1       deraadt   304:
                    305:
                    306: /*
                    307:  * Descriptions for various shells.
                    308:  */
1.40      espie     309: static Shell   shells[] = {
1.1       deraadt   310:     /*
                    311:      * CSH description. The csh can do echo control by playing
                    312:      * with the setting of the 'echo' shell variable. Sadly,
                    313:      * however, it is unable to do error control nicely.
                    314:      */
                    315: {
                    316:     "csh",
1.41      espie     317:     true, "unset verbose", "set verbose", "unset verbose", 10,
                    318:     false, "echo \"%s\"\n", "csh -c \"%s || exit 0\"",
1.1       deraadt   319:     "v", "e",
                    320: },
                    321:     /*
                    322:      * SH description. Echo control is also possible and, under
                    323:      * sun UNIX anyway, one can even control error checking.
                    324:      */
                    325: {
                    326:     "sh",
1.41      espie     327:     true, "set -", "set -v", "set -", 5,
                    328:     true, "set -e", "set +e",
1.2       deraadt   329: #ifdef OLDBOURNESHELL
1.41      espie     330:     false, "echo \"%s\"\n", "sh -c '%s || exit 0'\n",
1.2       deraadt   331: #endif
1.1       deraadt   332:     "v", "e",
                    333: },
                    334:     /*
                    335:      * UNKNOWN.
                    336:      */
                    337: {
1.40      espie     338:     (char *)0,
1.41      espie     339:     false, (char *)0, (char *)0, (char *)0, 0,
                    340:     false, (char *)0, (char *)0,
1.40      espie     341:     (char *)0, (char *)0,
1.1       deraadt   342: }
                    343: };
1.40      espie     344: static Shell   *commandShell = &shells[DEFSHELL];/* this is the shell to
1.1       deraadt   345:                                                   * which we pass all
1.64      espie     346:                                                   * commands in the Makefile*/
1.70      espie     347: #define SHELL_ECHO_OFF "set -"
                    348: #define SHELL_ECHO_ON  "set -v"
                    349: #define SHELL_ERROR_ON "set -e"
                    350: #define SHELL_ERROR_OFF        "set +e"
                    351: #define SHELL_ECHO_FLAG "v"
                    352: #define SHELL_ERROR_FLAG "e"
1.1       deraadt   353:
1.70      espie     354: static const char *shellPath = _PATH_BSHELL;
                    355: static const char *shellName = "sh";
1.1       deraadt   356:
1.40      espie     357: static int     maxJobs;        /* The most children we can run at once */
                    358: static int     maxLocal;       /* The most local ones we can have */
1.48      espie     359: static int     nJobs = 0;      /* The number of children currently running */
                    360: static int     nLocal;         /* The number of local children */
                    361: static LIST    jobs;           /* The structures that describe them */
                    362: static bool    jobFull;        /* Flag to tell when the job table is full. It
1.41      espie     363:                                 * is set true when (1) the total number of
1.1       deraadt   364:                                 * running jobs equals the maximum allowed or
                    365:                                 * (2) a job can only be run locally, but
                    366:                                 * nLocal equals maxLocal */
1.40      espie     367: static fd_set  *outputsp;      /* Set of descriptors of pipes connected to
1.1       deraadt   368:                                 * the output channels of children */
1.8       deraadt   369: static int     outputsn;
1.48      espie     370: static GNode   *lastNode;      /* The node for which output was most recently
1.1       deraadt   371:                                 * produced. */
1.48      espie     372: static char    *targFmt;       /* Format string to use to head output from a
1.1       deraadt   373:                                 * job when it's not the most-recent job heard
                    374:                                 * from */
1.2       deraadt   375:
                    376: # define TARG_FMT  "--- %s ---\n" /* Default format */
                    377: # define MESSAGE(fp, gn) \
1.40      espie     378:        (void)fprintf(fp, targFmt, gn->name);
1.1       deraadt   379:
                    380: /*
1.50      espie     381:  * When JobStart attempts to run a job but isn't allowed to,
                    382:  * the job is placed on the stoppedJobs queue to be run
1.6       millert   383:  * when the next job finishes.
1.1       deraadt   384:  */
1.48      espie     385: static LIST    stoppedJobs;    /* Lst of Job structures describing
1.1       deraadt   386:                                 * jobs that were stopped due to concurrency
                    387:                                 * limits or migration home */
                    388:
                    389:
                    390: #if defined(USE_PGRP) && defined(SYSV)
1.40      espie     391: # define KILL(pid, sig)        killpg(-(pid), (sig))
1.1       deraadt   392: #else
                    393: # if defined(USE_PGRP)
1.2       deraadt   394: #  define KILL(pid, sig)       killpg((pid), (sig))
1.1       deraadt   395: # else
1.2       deraadt   396: #  define KILL(pid, sig)       kill((pid), (sig))
1.1       deraadt   397: # endif
                    398: #endif
                    399:
1.6       millert   400: /*
1.2       deraadt   401:  * Grmpf... There is no way to set bits of the wait structure
                    402:  * anymore with the stupid W*() macros. I liked the union wait
                    403:  * stuff much more. So, we devise our own macros... This is
                    404:  * really ugly, use dramamine sparingly. You have been warned.
                    405:  */
                    406: #define W_SETMASKED(st, val, fun)                              \
                    407:        {                                                       \
                    408:                int sh = (int) ~0;                              \
                    409:                int mask = fun(sh);                             \
                    410:                                                                \
                    411:                for (sh = 0; ((mask >> sh) & 1) == 0; sh++)     \
                    412:                        continue;                               \
                    413:                *(st) = (*(st) & ~mask) | ((val) << sh);        \
                    414:        }
                    415:
                    416: #define W_SETTERMSIG(st, val) W_SETMASKED(st, val, WTERMSIG)
                    417: #define W_SETEXITSTATUS(st, val) W_SETMASKED(st, val, WEXITSTATUS)
                    418:
                    419:
1.40      espie     420: static void JobCondPassSig(void *, void *);
1.57      espie     421: static void SigHandler(int);
                    422: static void HandleSigs(void);
1.40      espie     423: static void JobPassSig(int);
                    424: static int JobCmpPid(void *, void *);
1.60      espie     425: static int JobPrintCommand(LstNode, void *);
1.40      espie     426: static void JobSaveCommand(void *, void *);
                    427: static void JobClose(Job *);
                    428: static void JobFinish(Job *, int *);
                    429: static void JobExec(Job *, char **);
                    430: static void JobMakeArgv(Job *, char **);
                    431: static void JobRestart(Job *);
                    432: static int JobStart(GNode *, int, Job *);
                    433: static char *JobOutput(Job *, char *, char *, int);
1.41      espie     434: static void JobDoOutput(Job *, bool);
1.40      espie     435: static void JobInterrupt(int, int);
                    436: static void JobRestartJobs(void);
1.69      espie     437: static void DBPRINTF(Job *, const char *, ...);
1.1       deraadt   438:
1.57      espie     439: static volatile sig_atomic_t got_SIGINT, got_SIGHUP, got_SIGQUIT,
                    440:     got_SIGTERM;
                    441: #if defined(USE_PGRP)
                    442: static volatile sig_atomic_t got_SIGTSTP, got_SIGTTOU, got_SIGTTIN,
                    443:     got_SIGWINCH;
                    444: #endif
                    445:
                    446: static void
                    447: SigHandler(int sig)
                    448: {
                    449:        switch(sig) {
                    450:        case SIGINT:
                    451:                got_SIGINT++;
                    452:                break;
                    453:        case SIGHUP:
                    454:                got_SIGHUP++;
                    455:                break;
                    456:        case SIGQUIT:
                    457:                got_SIGQUIT++;
                    458:                break;
                    459:        case SIGTERM:
                    460:                got_SIGTERM++;
                    461:                break;
                    462: #if defined(USE_PGRGP)
                    463:        case SIGTSTP:
                    464:                got_SIGTSTP++;
                    465:                break;
                    466:        case SIGTTOU:
                    467:                got_SIGTTOU++;
                    468:                break;
                    469:        case SIGTTIN:
                    470:                got_SIGTTIN++;
                    471:                break;
                    472:        case SIGWINCH:
                    473:                got_SIGWINCH++;
                    474:                break;
                    475: #endif
                    476:        }
                    477: }
                    478:
                    479: static void
                    480: HandleSigs()
                    481: {
                    482:        if (got_SIGINT) {
                    483:                got_SIGINT=0;
                    484:                JobPassSig(SIGINT);
                    485:        }
                    486:        if (got_SIGHUP) {
                    487:                got_SIGHUP=0;
                    488:                JobPassSig(SIGHUP);
                    489:        }
                    490:        if (got_SIGQUIT) {
                    491:                got_SIGQUIT=0;
                    492:                JobPassSig(SIGQUIT);
                    493:        }
                    494:        if (got_SIGTERM) {
                    495:                got_SIGTERM=0;
                    496:                JobPassSig(SIGTERM);
                    497:        }
                    498: #if defined(USE_PGRP)
                    499:        if (got_SIGTSTP) {
                    500:                got_SIGTSTP=0;
                    501:                JobPassSig(SIGTSTP);
                    502:        }
                    503:        if (got_SIGTTOU) {
                    504:                got_SIGTTOU=0;
                    505:                JobPassSig(SIGTTOU);
                    506:        }
                    507:        if (got_SIGTTIN) {
                    508:                got_SIGTTIN=0;
                    509:                JobPassSig(SIGTTIN);
                    510:        }
                    511:        if (got_SIGWINCH) {
                    512:                got_SIGWINCH=0;
                    513:                JobPassSig(SIGWINCH);
                    514:        }
                    515: #endif
                    516: }
                    517:
1.1       deraadt   518: /*-
                    519:  *-----------------------------------------------------------------------
                    520:  * JobCondPassSig --
1.50      espie     521:  *     Pass a signal to a job if USE_PGRP
1.1       deraadt   522:  *     is defined.
                    523:  *
                    524:  * Side Effects:
                    525:  *     None, except the job may bite it.
                    526:  *-----------------------------------------------------------------------
                    527:  */
1.27      espie     528: static void
1.56      espie     529: JobCondPassSig(void *jobp,     /* Job to biff */
                    530:     void *signop)              /* Signal to send it */
1.1       deraadt   531: {
1.66      espie     532:        Job *job = (Job *)jobp;
                    533:        int signo = *(int *)signop;
                    534:        if (DEBUG(JOB)) {
                    535:                (void)fprintf(stdout,
                    536:                    "JobCondPassSig passing signal %d to child %ld.\n",
                    537:                    signo, (long)job->pid);
                    538:                (void)fflush(stdout);
                    539:        }
                    540:        KILL(job->pid, signo);
1.1       deraadt   541: }
                    542:
                    543: /*-
                    544:  *-----------------------------------------------------------------------
                    545:  * JobPassSig --
1.68      espie     546:  *     Pass a signal to all local jobs if USE_PGRP is defined,
1.50      espie     547:  *     then die ourselves.
1.1       deraadt   548:  *
                    549:  * Side Effects:
                    550:  *     We die by the same signal.
                    551:  *-----------------------------------------------------------------------
                    552:  */
                    553: static void
1.56      espie     554: JobPassSig(int signo) /* The signal number we've received */
1.1       deraadt   555: {
1.66      espie     556:        sigset_t nmask, omask;
                    557:        struct sigaction act;
1.6       millert   558:
1.66      espie     559:        if (DEBUG(JOB)) {
                    560:                (void)fprintf(stdout, "JobPassSig(%d) called.\n", signo);
                    561:                (void)fflush(stdout);
                    562:        }
                    563:        Lst_ForEach(&jobs, JobCondPassSig, &signo);
                    564:
                    565:        /*
                    566:         * Deal with proper cleanup based on the signal received. We only run
                    567:         * the .INTERRUPT target if the signal was in fact an interrupt. The
                    568:         * other three termination signals are more of a "get out *now*"
                    569:         * command.
                    570:         */
                    571:        if (signo == SIGINT) {
                    572:                JobInterrupt(true, signo);
                    573:        } else if (signo == SIGHUP || signo == SIGTERM || signo == SIGQUIT) {
                    574:                JobInterrupt(false, signo);
                    575:        }
1.1       deraadt   576:
1.66      espie     577:        /*
                    578:         * Leave gracefully if SIGQUIT, rather than core dumping.
                    579:         */
                    580:        if (signo == SIGQUIT) {
                    581:                Finish(0);
                    582:        }
1.6       millert   583:
1.66      espie     584:        /*
                    585:         * Send ourselves the signal now we've given the message to everyone
                    586:         * else.  Note we block everything else possible while we're getting
                    587:         * the signal.  This ensures that all our jobs get continued when we
                    588:         * wake up before we take any other signal.
                    589:         */
                    590:        sigemptyset(&nmask);
                    591:        sigaddset(&nmask, signo);
                    592:        sigprocmask(SIG_SETMASK, &nmask, &omask);
                    593:        memset(&act, 0, sizeof act);
                    594:        act.sa_handler = SIG_DFL;
                    595:        sigemptyset(&act.sa_mask);
                    596:        act.sa_flags = 0;
                    597:        sigaction(signo, &act, NULL);
1.6       millert   598:
1.66      espie     599:        if (DEBUG(JOB)) {
                    600:                (void)fprintf(stdout,
                    601:                    "JobPassSig passing signal to self, mask = %x.\n",
                    602:                    ~0 & ~(1 << (signo-1)));
                    603:                (void)fflush(stdout);
                    604:        }
                    605:        (void)signal(signo, SIG_DFL);
1.1       deraadt   606:
1.66      espie     607:        (void)KILL(getpid(), signo);
1.1       deraadt   608:
1.66      espie     609:        signo = SIGCONT;
                    610:        Lst_ForEach(&jobs, JobCondPassSig, &signo);
1.1       deraadt   611:
1.66      espie     612:        (void)sigprocmask(SIG_SETMASK, &omask, NULL);
                    613:        sigprocmask(SIG_SETMASK, &omask, NULL);
                    614:        act.sa_handler = SigHandler;
                    615:        sigaction(signo, &act, NULL);
1.1       deraadt   616: }
                    617:
                    618: /*-
                    619:  *-----------------------------------------------------------------------
                    620:  * JobCmpPid  --
                    621:  *     Compare the pid of the job with the given pid and return 0 if they
                    622:  *     are equal. This function is called from Job_CatchChildren via
                    623:  *     Lst_Find to find the job descriptor of the finished job.
                    624:  *
                    625:  * Results:
                    626:  *     0 if the pid's match
                    627:  *-----------------------------------------------------------------------
                    628:  */
                    629: static int
1.56      espie     630: JobCmpPid(void *job,   /* job to examine */
                    631:     void *pid)         /* process id desired */
1.1       deraadt   632: {
1.66      espie     633:        return *(pid_t *)pid - ((Job *)job)->pid;
1.1       deraadt   634: }
                    635:
1.69      espie     636: static void
                    637: DBPRINTF(Job *job, const char *fmt, ...)
                    638: {
                    639:        va_list va;
                    640:        va_start(va, fmt);
                    641:        if (DEBUG(JOB)) {
                    642:                (void)vfprintf(stdout, fmt, va);
                    643:                fflush(stdout);
                    644:        }
                    645:        vfprintf(job->cmdFILE, fmt, va);
                    646:        va_end(va);
                    647: }
                    648:
1.1       deraadt   649: /*-
                    650:  *-----------------------------------------------------------------------
                    651:  * JobPrintCommand  --
                    652:  *     Put out another command for the given job. If the command starts
                    653:  *     with an @ or a - we process it specially. In the former case,
                    654:  *     so long as the -s and -n flags weren't given to make, we stick
                    655:  *     a shell-specific echoOff command in the script. In the latter,
                    656:  *     we ignore errors for the entire job, unless the shell has error
                    657:  *     control.
                    658:  *     If the command is just "..." we take all future commands for this
                    659:  *     job to be commands to be executed once the entire graph has been
                    660:  *     made and return non-zero to signal that the end of the commands
                    661:  *     was reached. These commands are later attached to the postCommands
                    662:  *     node and executed by Job_End when all things are done.
1.40      espie     663:  *     This function is called from JobStart via Lst_Find
1.1       deraadt   664:  *
                    665:  * Results:
1.26      espie     666:  *     Always 1, unless the command was "..."
1.1       deraadt   667:  *
                    668:  * Side Effects:
                    669:  *     If the command begins with a '-' and the shell has no error control,
                    670:  *     the JOB_IGNERR flag is set in the job descriptor.
                    671:  *     If the command is "..." and we're not ignoring such things,
                    672:  *     tailCmds is set to the successor node of the cmd.
                    673:  *     numCommands is incremented if the command is actually printed.
                    674:  *-----------------------------------------------------------------------
                    675:  */
                    676: static int
1.60      espie     677: JobPrintCommand(LstNode cmdNode,    /* command string to print */
1.56      espie     678:     void *jobp)                            /* job for which to print it */
1.1       deraadt   679: {
1.66      espie     680:        bool noSpecials;        /* true if we shouldn't worry about
                    681:                                 * inserting special commands into
                    682:                                 * the input stream. */
                    683:        bool shutUp = false;    /* true if we put a no echo command
                    684:                                 * into the command file */
                    685:        bool errOff = false;    /* true if we turned error checking
                    686:                                 * off before printing the command
                    687:                                 * and need to turn it back on */
                    688:        char *cmdTemplate;      /* Template to use when printing the
                    689:                                 * command */
                    690:        char *cmdStart;         /* Start of expanded command */
                    691:        char *cmd = (char *)Lst_Datum(cmdNode);
                    692:        Job *job = (Job *)jobp;
                    693:
                    694:        noSpecials = (noExecute && !(job->node->type & OP_MAKE));
                    695:
                    696:        if (strcmp(cmd, "...") == 0) {
                    697:                job->node->type |= OP_SAVE_CMDS;
                    698:                if ((job->flags & JOB_IGNDOTS) == 0) {
                    699:                        job->tailCmds = Lst_Succ(cmdNode);
                    700:                        return 0;
                    701:                }
                    702:                return 1;
1.2       deraadt   703:        }
1.1       deraadt   704:
1.67      espie     705:        numCommands++;
1.1       deraadt   706:
1.66      espie     707:        /* For debugging, we replace each command with the result of expanding
                    708:         * the variables in the command.  */
                    709:        cmdStart = cmd = Var_Subst(cmd, &job->node->context, false);
                    710:        Lst_Replace(cmdNode, cmdStart);
1.1       deraadt   711:
1.66      espie     712:        cmdTemplate = "%s\n";
1.1       deraadt   713:
1.66      espie     714:        /*
                    715:         * Check for leading @' and -'s to control echoing and error checking.
                    716:         */
                    717:        for (;; cmd++) {
                    718:                if (*cmd == '@')
                    719:                        shutUp = DEBUG(LOUD) ? false : true;
                    720:                else if (*cmd == '-')
                    721:                        errOff = true;
                    722:                else if (*cmd != '+')
                    723:                        break;
1.1       deraadt   724:        }
                    725:
1.66      espie     726:        while (isspace(*cmd))
                    727:                cmd++;
                    728:
                    729:        if (shutUp) {
1.72    ! espie     730:                if (!(job->flags & JOB_SILENT) && !noSpecials) {
1.71      espie     731:                        DBPRINTF(job, "%s\n", SHELL_ECHO_OFF);
1.1       deraadt   732:                } else {
1.66      espie     733:                        shutUp = false;
                    734:                }
                    735:        }
                    736:
                    737:        if (errOff) {
                    738:                if ( !(job->flags & JOB_IGNERR) && !noSpecials) {
1.72    ! espie     739:                        /*
        !           740:                         * we don't want the error-control commands
        !           741:                         * showing up either, so we turn off echoing
        !           742:                         * while executing them. We could put another
        !           743:                         * field in the shell structure to tell
        !           744:                         * JobDoOutput to look for this string too, but
        !           745:                         * why make it any more complex than it already
        !           746:                         * is?
        !           747:                         */
        !           748:                        if (!(job->flags & JOB_SILENT) && !shutUp) {
        !           749:                                DBPRINTF(job, "%s\n", SHELL_ECHO_OFF);
        !           750:                                DBPRINTF(job, "%s\n", SHELL_ERROR_OFF);
        !           751:                                DBPRINTF(job, "%s\n", SHELL_ECHO_ON);
1.66      espie     752:                        } else {
1.72    ! espie     753:                                DBPRINTF(job, "%s\n", SHELL_ERROR_OFF);
1.66      espie     754:                        }
                    755:                } else {
                    756:                        errOff = false;
1.1       deraadt   757:                }
1.66      espie     758:        }
                    759:
1.69      espie     760:        DBPRINTF(job, cmdTemplate, cmd);
1.66      espie     761:
                    762:        if (errOff) {
                    763:                /*
                    764:                 * If echoing is already off, there's no point in issuing the
                    765:                 * echoOff command. Otherwise we issue it and pretend it was on
                    766:                 * for the whole command...
1.1       deraadt   767:                 */
1.72    ! espie     768:                if (!shutUp && !(job->flags & JOB_SILENT)) {
1.71      espie     769:                        DBPRINTF(job, "%s\n", SHELL_ECHO_OFF);
1.41      espie     770:                        shutUp = true;
1.1       deraadt   771:                }
1.71      espie     772:                DBPRINTF(job, "%s\n", SHELL_ERROR_ON);
1.66      espie     773:        }
                    774:        if (shutUp) {
1.71      espie     775:                DBPRINTF(job, "%s\n", SHELL_ECHO_ON);
1.1       deraadt   776:        }
1.66      espie     777:        return 1;
1.1       deraadt   778: }
                    779:
                    780: /*-
                    781:  *-----------------------------------------------------------------------
                    782:  * JobSaveCommand --
                    783:  *     Save a command to be executed when everything else is done.
                    784:  *     Callback function for JobFinish...
                    785:  *
                    786:  * Side Effects:
                    787:  *     The command is tacked onto the end of postCommands's commands list.
                    788:  *-----------------------------------------------------------------------
                    789:  */
1.27      espie     790: static void
1.56      espie     791: JobSaveCommand(void *cmd, void *gn)
1.1       deraadt   792: {
1.66      espie     793:        GNode *g = (GNode *)gn;
                    794:        char *result;
1.28      espie     795:
1.66      espie     796:        result = Var_Subst((char *)cmd, &g->context, false);
                    797:        Lst_AtEnd(&postCommands->commands, result);
1.2       deraadt   798: }
                    799:
                    800:
                    801: /*-
                    802:  *-----------------------------------------------------------------------
                    803:  * JobClose --
                    804:  *     Called to close both input and output pipes when a job is finished.
                    805:  *
                    806:  * Side Effects:
                    807:  *     The file descriptors associated with the job are closed.
                    808:  *-----------------------------------------------------------------------
                    809:  */
                    810: static void
1.56      espie     811: JobClose(Job *job)
1.2       deraadt   812: {
1.66      espie     813:        if (usePipes) {
                    814:                FD_CLR(job->inPipe, outputsp);
                    815:                if (job->outPipe != job->inPipe) {
                    816:                       (void)close(job->outPipe);
                    817:                }
                    818:                JobDoOutput(job, true);
                    819:                (void)close(job->inPipe);
                    820:        } else {
                    821:                (void)close(job->outFd);
                    822:                JobDoOutput(job, true);
                    823:        }
1.1       deraadt   824: }
                    825:
                    826: /*-
                    827:  *-----------------------------------------------------------------------
                    828:  * JobFinish  --
                    829:  *     Do final processing for the given job including updating
                    830:  *     parents and starting new jobs as available/necessary. Note
                    831:  *     that we pay no attention to the JOB_IGNERR flag here.
                    832:  *     This is because when we're called because of a noexecute flag
                    833:  *     or something, jstat.w_status is 0 and when called from
                    834:  *     Job_CatchChildren, the status is zeroed if it s/b ignored.
                    835:  *
                    836:  * Side Effects:
                    837:  *     Some nodes may be put on the toBeMade queue.
                    838:  *     Final commands for the job are placed on postCommands.
                    839:  *
1.6       millert   840:  *     If we got an error and are aborting (aborting == ABORT_ERROR) and
1.1       deraadt   841:  *     the job list is now empty, we are done for the day.
1.6       millert   842:  *     If we recognized an error (errors !=0), we set the aborting flag
1.1       deraadt   843:  *     to ABORT_ERROR so no more jobs will be started.
                    844:  *-----------------------------------------------------------------------
                    845:  */
                    846: /*ARGSUSED*/
                    847: static void
1.56      espie     848: JobFinish(Job *job,            /* job to finish */
                    849:     int *status)               /* sub-why job went away */
1.2       deraadt   850: {
1.66      espie     851:        bool done;
1.2       deraadt   852:
1.66      espie     853:        if ((WIFEXITED(*status) &&
                    854:             WEXITSTATUS(*status) != 0 && !(job->flags & JOB_IGNERR)) ||
                    855:            (WIFSIGNALED(*status) && WTERMSIG(*status) != SIGCONT)) {
                    856:                /*
                    857:                 * If it exited non-zero and either we're doing things our
                    858:                 * way or we're not ignoring errors, the job is finished.
                    859:                 * Similarly, if the shell died because of a signal
                    860:                 * the job is also finished. In these
                    861:                 * cases, finish out the job's output before printing the exit
                    862:                 * status...
                    863:                 */
                    864:                JobClose(job);
                    865:                if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
                    866:                       (void)fclose(job->cmdFILE);
                    867:                }
                    868:                done = true;
                    869:        } else if (WIFEXITED(*status)) {
                    870:                /*
                    871:                 * Deal with ignored errors in -B mode. We need to print a
                    872:                 * message telling of the ignored error as well as setting
                    873:                 * status.w_status to 0 so the next command gets run. To do
                    874:                 * this, we set done to be true if in -B mode and the job
                    875:                 * exited non-zero.
                    876:                 */
                    877:                done = WEXITSTATUS(*status) != 0;
                    878:                /*
                    879:                 * Old comment said: "Note we don't want to close down any of
                    880:                 * the streams until we know we're at the end." But we do.
                    881:                 * Otherwise when are we going to print the rest of the stuff?
                    882:                 */
                    883:                JobClose(job);
                    884:        } else {
                    885:                /*
                    886:                 * No need to close things down or anything.
                    887:                 */
                    888:                done = false;
1.1       deraadt   889:        }
1.6       millert   890:
1.66      espie     891:        if (done ||
                    892:            WIFSTOPPED(*status) ||
                    893:            (WIFSIGNALED(*status) && WTERMSIG(*status) == SIGCONT) ||
                    894:            DEBUG(JOB)) {
                    895:                FILE *out;
                    896:
                    897:                if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
                    898:                        /*
                    899:                         * If output is going to a file and this job is ignoring
                    900:                         * errors, arrange to have the exit status sent to the
                    901:                         * output file as well.
                    902:                         */
                    903:                        out = fdopen(job->outFd, "w");
                    904:                } else {
                    905:                        out = stdout;
                    906:                }
1.1       deraadt   907:
1.66      espie     908:                if (WIFEXITED(*status)) {
                    909:                        if (DEBUG(JOB)) {
1.68      espie     910:                                (void)fprintf(stdout, "Process %ld exited.\n",
1.66      espie     911:                                    (long)job->pid);
                    912:                                (void)fflush(stdout);
                    913:                        }
                    914:                        if (WEXITSTATUS(*status) != 0) {
                    915:                                if (usePipes && job->node != lastNode) {
                    916:                                        MESSAGE(out, job->node);
                    917:                                        lastNode = job->node;
                    918:                                }
                    919:                                (void)fprintf(out, "*** Error code %d%s\n",
                    920:                                    WEXITSTATUS(*status),
1.68      espie     921:                                    (job->flags & JOB_IGNERR) ? "(ignored)" :
1.66      espie     922:                                    "");
                    923:
                    924:                                if (job->flags & JOB_IGNERR) {
                    925:                                        *status = 0;
                    926:                                }
                    927:                        } else if (DEBUG(JOB)) {
                    928:                                if (usePipes && job->node != lastNode) {
                    929:                                        MESSAGE(out, job->node);
                    930:                                        lastNode = job->node;
                    931:                                }
1.68      espie     932:                                (void)fprintf(out,
1.66      espie     933:                                    "*** Completed successfully\n");
                    934:                        }
                    935:                } else if (WIFSTOPPED(*status)) {
                    936:                        if (DEBUG(JOB)) {
1.68      espie     937:                                (void)fprintf(stdout, "Process %ld stopped.\n",
1.66      espie     938:                                    (long)job->pid);
                    939:                                (void)fflush(stdout);
                    940:                        }
                    941:                        if (usePipes && job->node != lastNode) {
                    942:                                MESSAGE(out, job->node);
                    943:                                lastNode = job->node;
                    944:                        }
                    945:                        (void)fprintf(out, "*** Stopped -- signal %d\n",
                    946:                            WSTOPSIG(*status));
                    947:                        job->flags |= JOB_RESUME;
                    948:                        Lst_AtEnd(&stoppedJobs, job);
                    949:                        (void)fflush(out);
                    950:                        return;
                    951:                } else if (WTERMSIG(*status) == SIGCONT) {
                    952:                        /*
                    953:                         * If the beastie has continued, shift the Job from the
                    954:                         * stopped list to the running one (or re-stop it if
                    955:                         * concurrency is exceeded) and go and get another
                    956:                         * child.
                    957:                         */
                    958:                        if (job->flags & (JOB_RESUME|JOB_RESTART)) {
                    959:                                if (usePipes && job->node != lastNode) {
                    960:                                        MESSAGE(out, job->node);
                    961:                                        lastNode = job->node;
                    962:                                }
                    963:                                (void)fprintf(out, "*** Continued\n");
                    964:                        }
                    965:                        if (!(job->flags & JOB_CONTINUING)) {
                    966:                                if (DEBUG(JOB)) {
                    967:                                        (void)fprintf(stdout,
                    968:                                "Warning: process %ld was not continuing.\n",
                    969:                                            (long)job->pid);
                    970:                                        (void)fflush(stdout);
                    971:                                }
                    972: #if 0
                    973:                                /*
                    974:                                 * We don't really want to restart a job from
                    975:                                 * scratch just because it continued,
                    976:                                 * especially not without killing the
                    977:                                 * continuing process!  That's why this is
                    978:                                 * ifdef'ed out.  FD - 9/17/90
                    979:                                 */
                    980:                                JobRestart(job);
1.2       deraadt   981: #endif
1.66      espie     982:                        }
                    983:                        job->flags &= ~JOB_CONTINUING;
                    984:                        Lst_AtEnd(&jobs, job);
1.67      espie     985:                        nJobs++;
1.66      espie     986:                        if (DEBUG(JOB)) {
                    987:                                (void)fprintf(stdout,
                    988:                                    "Process %ld is continuing locally.\n",
                    989:                                    (long)job->pid);
                    990:                                (void)fflush(stdout);
                    991:                        }
1.67      espie     992:                        nLocal++;
1.66      espie     993:                        if (nJobs == maxJobs) {
                    994:                                jobFull = true;
                    995:                                if (DEBUG(JOB)) {
1.68      espie     996:                                        (void)fprintf(stdout,
1.66      espie     997:                                            "Job queue is full.\n");
                    998:                                        (void)fflush(stdout);
                    999:                                }
                   1000:                        }
                   1001:                        (void)fflush(out);
                   1002:                        return;
                   1003:                } else {
                   1004:                        if (usePipes && job->node != lastNode) {
                   1005:                                MESSAGE(out, job->node);
                   1006:                                lastNode = job->node;
                   1007:                        }
1.68      espie    1008:                        (void)fprintf(out, "*** Signal %d\n",
1.66      espie    1009:                            WTERMSIG(*status));
1.40      espie    1010:                }
1.66      espie    1011:
                   1012:                (void)fflush(out);
1.1       deraadt  1013:        }
                   1014:
1.66      espie    1015:        /*
                   1016:         * Now handle the -B-mode stuff. If the beast still isn't finished,
                   1017:         * try and restart the job on the next command. If JobStart says it's
                   1018:         * ok, it's ok. If there's an error, this puppy is done.
                   1019:         */
                   1020:        if (compatMake && WIFEXITED(*status) && job->node->current != NULL) {
                   1021:                switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
                   1022:                case JOB_RUNNING:
                   1023:                        done = false;
                   1024:                        break;
                   1025:                case JOB_ERROR:
                   1026:                        done = true;
                   1027:                        W_SETEXITSTATUS(status, 1);
                   1028:                        break;
                   1029:                case JOB_FINISHED:
                   1030:                        /*
                   1031:                         * If we got back a JOB_FINISHED code, JobStart has
                   1032:                         * already called Make_Update and freed the job
                   1033:                         * descriptor. We set done to false here to avoid fake
                   1034:                         * cycles and double frees.  JobStart needs to do the
                   1035:                         * update so we can proceed up the graph when given the
                   1036:                         * -n flag..
                   1037:                         */
                   1038:                        done = false;
                   1039:                        break;
                   1040:                }
                   1041:        } else
                   1042:                done = true;
1.1       deraadt  1043:
1.66      espie    1044:        if (done &&
                   1045:            aborting != ABORT_ERROR &&
                   1046:            aborting != ABORT_INTERRUPT &&
                   1047:            *status == 0) {
                   1048:                /* As long as we aren't aborting and the job didn't return a
                   1049:                 * non-zero status that we shouldn't ignore, we call
                   1050:                 * Make_Update to update the parents. In addition, any saved
                   1051:                 * commands for the node are placed on the .END target. */
                   1052:                Lst_ForEachFrom(job->tailCmds, JobSaveCommand, job->node);
                   1053:                job->node->made = MADE;
                   1054:                Make_Update(job->node);
                   1055:                free(job);
                   1056:        } else if (*status != 0) {
1.67      espie    1057:                errors++;
1.66      espie    1058:                free(job);
                   1059:        }
1.1       deraadt  1060:
1.66      espie    1061:        JobRestartJobs();
1.1       deraadt  1062:
                   1063:        /*
1.66      espie    1064:         * Set aborting if any error.
1.1       deraadt  1065:         */
1.66      espie    1066:        if (errors && !keepgoing && aborting != ABORT_INTERRUPT) {
                   1067:                /*
                   1068:                 * If we found any errors in this batch of children and the -k
                   1069:                 * flag wasn't given, we set the aborting flag so no more jobs
                   1070:                 * get started.
                   1071:                 */
                   1072:                aborting = ABORT_ERROR;
                   1073:        }
1.6       millert  1074:
1.66      espie    1075:        if (aborting == ABORT_ERROR && Job_Empty()) {
                   1076:                /*
                   1077:                 * If we are aborting and the job table is now empty, we finish.
                   1078:                 */
                   1079:                (void)eunlink(tfile);
                   1080:                Finish(errors);
                   1081:        }
1.1       deraadt  1082: }
                   1083:
                   1084: /*-
                   1085:  *-----------------------------------------------------------------------
                   1086:  * JobExec --
                   1087:  *     Execute the shell for the given job. Called from JobStart and
                   1088:  *     JobRestart.
                   1089:  *
                   1090:  * Side Effects:
                   1091:  *     A shell is executed, outputs is altered and the Job structure added
                   1092:  *     to the job table.
                   1093:  *-----------------------------------------------------------------------
                   1094:  */
                   1095: static void
1.56      espie    1096: JobExec(Job *job, char **argv)
1.1       deraadt  1097: {
1.66      espie    1098:        pid_t cpid;     /* ID of new child */
1.6       millert  1099:
1.66      espie    1100:        if (DEBUG(JOB)) {
                   1101:                int       i;
1.6       millert  1102:
1.66      espie    1103:                (void)fprintf(stdout, "Running %s\n", job->node->name);
                   1104:                (void)fprintf(stdout, "\tCommand: ");
                   1105:                for (i = 0; argv[i] != NULL; i++) {
                   1106:                        (void)fprintf(stdout, "%s ", argv[i]);
                   1107:                }
                   1108:                (void)fprintf(stdout, "\n");
                   1109:                (void)fflush(stdout);
1.1       deraadt  1110:        }
1.6       millert  1111:
1.66      espie    1112:        /*
                   1113:         * Some jobs produce no output and it's disconcerting to have
                   1114:         * no feedback of their running (since they produce no output, the
                   1115:         * banner with their name in it never appears). This is an attempt to
                   1116:         * provide that feedback, even if nothing follows it.
                   1117:         */
                   1118:        if (lastNode != job->node && (job->flags & JOB_FIRST) &&
                   1119:            !(job->flags & JOB_SILENT)) {
                   1120:                MESSAGE(stdout, job->node);
                   1121:                lastNode = job->node;
                   1122:        }
1.1       deraadt  1123:
1.66      espie    1124:        if ((cpid = fork()) == -1) {
                   1125:                Punt("Cannot fork");
                   1126:        } else if (cpid == 0) {
1.6       millert  1127:
1.66      espie    1128:                /*
                   1129:                 * Must duplicate the input stream down to the child's input
                   1130:                 * and reset it to the beginning (again). Since the stream was
                   1131:                 * marked close-on-exec, we must clear that bit in the new
                   1132:                 * input.
                   1133:                 */
                   1134:                if (dup2(FILENO(job->cmdFILE), 0) == -1)
                   1135:                        Punt("Cannot dup2: %s", strerror(errno));
                   1136:                (void)fcntl(0, F_SETFD, 0);
                   1137:                (void)lseek(0, 0, SEEK_SET);
                   1138:
                   1139:                if (usePipes) {
                   1140:                        /*
                   1141:                         * Set up the child's output to be routed through the
                   1142:                         * pipe we've created for it.
                   1143:                         */
                   1144:                        if (dup2(job->outPipe, 1) == -1)
                   1145:                                Punt("Cannot dup2: %s", strerror(errno));
                   1146:                } else {
                   1147:                        /*
                   1148:                         * We're capturing output in a file, so we duplicate the
                   1149:                         * descriptor to the temporary file into the standard
                   1150:                         * output.
                   1151:                         */
                   1152:                        if (dup2(job->outFd, 1) == -1)
                   1153:                                Punt("Cannot dup2: %s", strerror(errno));
                   1154:                }
                   1155:                /*
                   1156:                 * The output channels are marked close on exec. This bit was
                   1157:                 * duplicated by the dup2 (on some systems), so we have to
                   1158:                 * clear it before routing the shell's error output to the same
                   1159:                 * place as its standard output.
                   1160:                 */
                   1161:                (void)fcntl(1, F_SETFD, 0);
                   1162:                if (dup2(1, 2) == -1)
                   1163:                        Punt("Cannot dup2: %s", strerror(errno));
1.1       deraadt  1164:
                   1165: #ifdef USE_PGRP
1.66      espie    1166:                /*
                   1167:                 * We want to switch the child into a different process family
                   1168:                 * so we can kill it and all its descendants in one fell swoop,
                   1169:                 * by killing its process family, but not commit suicide.
                   1170:                 */
1.2       deraadt  1171: # if defined(SYSV)
1.66      espie    1172:                (void)setsid();
1.2       deraadt  1173: # else
1.66      espie    1174:                (void)setpgid(0, getpid());
1.2       deraadt  1175: # endif
                   1176: #endif /* USE_PGRP */
1.1       deraadt  1177:
1.66      espie    1178:                (void)execv(shellPath, argv);
                   1179:
                   1180:                (void)write(STDERR_FILENO, "Could not execute shell\n",
                   1181:                    sizeof("Could not execute shell"));
                   1182:                _exit(1);
                   1183:        } else {
                   1184:                job->pid = cpid;
                   1185:
                   1186:                if (usePipes && (job->flags & JOB_FIRST) ) {
                   1187:                        /*
                   1188:                         * The first time a job is run for a node, we set the
                   1189:                         * current position in the buffer to the beginning and
                   1190:                         * mark another stream to watch in the outputs mask
                   1191:                         */
                   1192:                        job->curPos = 0;
                   1193:
                   1194:                        if (outputsp == NULL || job->inPipe > outputsn) {
                   1195:                                int bytes, obytes;
                   1196:                                char *tmp;
                   1197:
1.68      espie    1198:                                bytes = howmany(job->inPipe+1, NFDBITS) *
1.66      espie    1199:                                    sizeof(fd_mask);
1.68      espie    1200:                                obytes = outputsn ?
                   1201:                                    howmany(outputsn+1, NFDBITS) *
1.66      espie    1202:                                    sizeof(fd_mask) : 0;
                   1203:
                   1204:                                if (bytes != obytes) {
                   1205:                                        tmp = realloc(outputsp, bytes);
                   1206:                                        if (tmp == NULL)
                   1207:                                                return;
                   1208:                                        memset(tmp + obytes, 0, bytes - obytes);
                   1209:                                        outputsp = (fd_set *)tmp;
                   1210:                                }
                   1211:                                outputsn = job->inPipe;
                   1212:                        }
                   1213:                        FD_SET(job->inPipe, outputsp);
                   1214:                }
1.2       deraadt  1215:
1.67      espie    1216:                nLocal++;
1.66      espie    1217:                /*
                   1218:                 * XXX: Used to not happen if REMOTE. Why?
                   1219:                 */
                   1220:                if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
                   1221:                        (void)fclose(job->cmdFILE);
                   1222:                        job->cmdFILE = NULL;
                   1223:                }
1.1       deraadt  1224:        }
                   1225:
1.48      espie    1226:        /*
1.66      espie    1227:         * Now the job is actually running, add it to the table.
1.48      espie    1228:         */
1.67      espie    1229:        nJobs++;
1.66      espie    1230:        Lst_AtEnd(&jobs, job);
                   1231:        if (nJobs == maxJobs) {
                   1232:                jobFull = true;
1.1       deraadt  1233:        }
                   1234: }
                   1235:
                   1236: /*-
                   1237:  *-----------------------------------------------------------------------
                   1238:  * JobMakeArgv --
                   1239:  *     Create the argv needed to execute the shell for a given job.
                   1240:  *-----------------------------------------------------------------------
                   1241:  */
                   1242: static void
1.56      espie    1243: JobMakeArgv(Job *job, char **argv)
1.1       deraadt  1244: {
1.66      espie    1245:        int argc;
                   1246:        static char args[10];   /* For merged arguments */
1.6       millert  1247:
1.70      espie    1248:        argv[0] = (char *)shellName;
1.66      espie    1249:        argc = 1;
1.1       deraadt  1250:
1.66      espie    1251:        if ((commandShell->exit && *commandShell->exit != '-') ||
                   1252:            (commandShell->echo && *commandShell->echo != '-')) {
                   1253:                /*
                   1254:                 * At least one of the flags doesn't have a minus before it, so
                   1255:                 * merge them together. Have to do this because the
                   1256:                 * *(&(@*#*&#$# Bourne shell thinks its second argument is a
                   1257:                 * file to source.  Grrrr. Note the ten-character limitation on
                   1258:                 * the combined arguments.
                   1259:                 */
                   1260:                (void)snprintf(args, sizeof(args), "-%s%s",
                   1261:                    ((job->flags & JOB_IGNERR) ? "" :
                   1262:                    (commandShell->exit ? commandShell->exit : "")),
                   1263:                    ((job->flags & JOB_SILENT) ? "" :
                   1264:                    (commandShell->echo ? commandShell->echo : "")));
                   1265:
                   1266:                if (args[1]) {
                   1267:                        argv[argc] = args;
                   1268:                        argc++;
                   1269:                }
                   1270:        } else {
                   1271:                if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
                   1272:                        argv[argc] = commandShell->exit;
                   1273:                        argc++;
                   1274:                }
                   1275:                if (!(job->flags & JOB_SILENT) && commandShell->echo) {
                   1276:                        argv[argc] = commandShell->echo;
                   1277:                        argc++;
                   1278:                }
1.1       deraadt  1279:        }
1.66      espie    1280:        argv[argc] = NULL;
1.1       deraadt  1281: }
                   1282:
                   1283: /*-
                   1284:  *-----------------------------------------------------------------------
                   1285:  * JobRestart --
1.6       millert  1286:  *     Restart a job that stopped for some reason.
1.1       deraadt  1287:  *
                   1288:  * Side Effects:
                   1289:  *     jobFull will be set if the job couldn't be run.
                   1290:  *-----------------------------------------------------------------------
                   1291:  */
                   1292: static void
1.56      espie    1293: JobRestart(Job *job)
1.1       deraadt  1294: {
1.66      espie    1295:        if (job->flags & JOB_RESTART) {
                   1296:                /*
                   1297:                 * Set up the control arguments to the shell. This is based on
                   1298:                 * the flags set earlier for this job. If the JOB_IGNERR flag
                   1299:                 * is clear, the 'exit' flag of the commandShell is used to
                   1300:                 * cause it to exit upon receiving an error. If the JOB_SILENT
                   1301:                 * flag is clear, the 'echo' flag of the commandShell is used
                   1302:                 * to get it to start echoing as soon as it starts processing
                   1303:                 * commands.
                   1304:                 */
                   1305:                char *argv[4];
1.6       millert  1306:
1.66      espie    1307:                JobMakeArgv(job, argv);
1.2       deraadt  1308:
1.1       deraadt  1309:                if (DEBUG(JOB)) {
1.68      espie    1310:                        (void)fprintf(stdout, "Restarting %s...",
1.66      espie    1311:                            job->node->name);
                   1312:                        (void)fflush(stdout);
1.1       deraadt  1313:                }
1.66      espie    1314:                if (nLocal >= maxLocal && !(job->flags & JOB_SPECIAL)) {
                   1315:                        /*
                   1316:                         * Can't be exported and not allowed to run locally --
                   1317:                         * put it back on the hold queue and mark the table
                   1318:                         * full
                   1319:                         */
                   1320:                        if (DEBUG(JOB)) {
                   1321:                                (void)fprintf(stdout, "holding\n");
                   1322:                                (void)fflush(stdout);
                   1323:                        }
                   1324:                        Lst_AtFront(&stoppedJobs, job);
                   1325:                        jobFull = true;
                   1326:                        if (DEBUG(JOB)) {
                   1327:                                (void)fprintf(stdout, "Job queue is full.\n");
                   1328:                                (void)fflush(stdout);
                   1329:                        }
                   1330:                        return;
                   1331:                } else {
                   1332:                        /*
                   1333:                         * Job may be run locally.
                   1334:                         */
                   1335:                        if (DEBUG(JOB)) {
                   1336:                                (void)fprintf(stdout, "running locally\n");
                   1337:                                (void)fflush(stdout);
                   1338:                        }
1.1       deraadt  1339:                }
1.66      espie    1340:                JobExec(job, argv);
                   1341:        } else {
1.1       deraadt  1342:                /*
1.66      espie    1343:                 * The job has stopped and needs to be restarted. Why it
                   1344:                 * stopped, we don't know...
1.1       deraadt  1345:                 */
                   1346:                if (DEBUG(JOB)) {
1.66      espie    1347:                       (void)fprintf(stdout, "Resuming %s...", job->node->name);
                   1348:                       (void)fflush(stdout);
1.1       deraadt  1349:                }
1.66      espie    1350:                if ((nLocal < maxLocal ||
                   1351:                    ((job->flags & JOB_SPECIAL) &&
                   1352:                     maxLocal == 0)
                   1353:                   ) && nJobs != maxJobs) {
                   1354:                        /*
                   1355:                         * If we haven't reached the concurrency limit already
                   1356:                         * (or maxLocal is 0), it's ok to resume the job.
                   1357:                         */
                   1358:                        bool error;
                   1359:                        int status;
                   1360:
                   1361:                        error = KILL(job->pid, SIGCONT) != 0;
                   1362:
                   1363:                        if (!error) {
                   1364:                                /*
                   1365:                                 * Make sure the user knows we've continued the
                   1366:                                 * beast and actually put the thing in the job
                   1367:                                 * table.
                   1368:                                 */
                   1369:                                job->flags |= JOB_CONTINUING;
                   1370:                                W_SETTERMSIG(&status, SIGCONT);
                   1371:                                JobFinish(job, &status);
                   1372:
                   1373:                                job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
                   1374:                                if (DEBUG(JOB)) {
                   1375:                                       (void)fprintf(stdout, "done\n");
                   1376:                                       (void)fflush(stdout);
                   1377:                                }
                   1378:                        } else {
                   1379:                                Error("couldn't resume %s: %s",
                   1380:                                    job->node->name, strerror(errno));
                   1381:                                status = 0;
                   1382:                                W_SETEXITSTATUS(&status, 1);
                   1383:                                JobFinish(job, &status);
                   1384:                        }
                   1385:                } else {
                   1386:                        /*
                   1387:                         * Job cannot be restarted. Mark the table as full and
                   1388:                         * place the job back on the list of stopped jobs.
                   1389:                         */
                   1390:                        if (DEBUG(JOB)) {
                   1391:                                (void)fprintf(stdout, "table full\n");
                   1392:                                (void)fflush(stdout);
                   1393:                        }
                   1394:                        Lst_AtFront(&stoppedJobs, job);
                   1395:                        jobFull = true;
                   1396:                        if (DEBUG(JOB)) {
                   1397:                                (void)fprintf(stdout, "Job queue is full.\n");
                   1398:                                (void)fflush(stdout);
                   1399:                        }
1.1       deraadt  1400:                }
                   1401:        }
                   1402: }
                   1403:
                   1404: /*-
                   1405:  *-----------------------------------------------------------------------
                   1406:  * JobStart  --
                   1407:  *     Start a target-creation process going for the target described
1.6       millert  1408:  *     by the graph node gn.
1.1       deraadt  1409:  *
                   1410:  * Results:
                   1411:  *     JOB_ERROR if there was an error in the commands, JOB_FINISHED
                   1412:  *     if there isn't actually anything left to do for the job and
                   1413:  *     JOB_RUNNING if the job has been started.
                   1414:  *
                   1415:  * Side Effects:
                   1416:  *     A new Job node is created and added to the list of running
                   1417:  *     jobs. PMake is forked and a child shell created.
                   1418:  *-----------------------------------------------------------------------
                   1419:  */
                   1420: static int
1.56      espie    1421: JobStart(GNode   *gn,        /* target to create */
                   1422:     int           flags,      /* flags for the job to override normal ones.
1.1       deraadt  1423:                               * e.g. JOB_SPECIAL or JOB_IGNDOTS */
1.56      espie    1424:     Job          *previous)  /* The previous Job structure for this node,
1.1       deraadt  1425:                               * if any. */
                   1426: {
1.66      espie    1427:        Job *job;       /* new job descriptor */
                   1428:        char *argv[4];  /* Argument vector to shell */
                   1429:        bool cmdsOK;    /* true if the nodes commands were all right */
                   1430:        bool local;     /* Set true if the job was run locally */
                   1431:        bool noExec;    /* Set true if we decide not to run the job */
                   1432:
                   1433:        if (previous != NULL) {
                   1434:                previous->flags &= ~(JOB_FIRST|JOB_IGNERR|JOB_SILENT);
                   1435:                job = previous;
                   1436:        } else {
                   1437:                job = emalloc(sizeof(Job));
                   1438:                if (job == NULL) {
                   1439:                        Punt("JobStart out of memory");
                   1440:                }
                   1441:                flags |= JOB_FIRST;
1.1       deraadt  1442:        }
                   1443:
1.66      espie    1444:        job->node = gn;
                   1445:        job->tailCmds = NULL;
1.1       deraadt  1446:
                   1447:        /*
1.66      espie    1448:         * Set the initial value of the flags for this job based on the global
                   1449:         * ones and the node's attributes... Any flags supplied by the caller
                   1450:         * are also added to the field.
1.1       deraadt  1451:         */
1.66      espie    1452:        job->flags = 0;
                   1453:        if (Targ_Ignore(gn)) {
                   1454:                job->flags |= JOB_IGNERR;
                   1455:        }
                   1456:        if (Targ_Silent(gn)) {
                   1457:                job->flags |= JOB_SILENT;
1.1       deraadt  1458:        }
1.66      espie    1459:        job->flags |= flags;
1.6       millert  1460:
1.1       deraadt  1461:        /*
1.66      espie    1462:         * Check the commands now so any attributes from .DEFAULT have a chance
                   1463:         * to migrate to the node
1.1       deraadt  1464:         */
1.66      espie    1465:        if (!compatMake && job->flags & JOB_FIRST) {
                   1466:                cmdsOK = Job_CheckCommands(gn, Error);
                   1467:        } else {
                   1468:                cmdsOK = true;
                   1469:        }
1.1       deraadt  1470:
                   1471:        /*
1.66      espie    1472:         * If the -n flag wasn't given, we open up OUR (not the child's)
                   1473:         * temporary file to stuff commands in it. The thing is rd/wr so we
                   1474:         * don't need to reopen it to feed it to the shell. If the -n flag
                   1475:         * *was* given, we just set the file to be stdout. Cute, huh?
1.1       deraadt  1476:         */
1.66      espie    1477:        if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
                   1478:                /*
                   1479:                 * We're serious here, but if the commands were bogus, we're
                   1480:                 * also dead...
                   1481:                 */
                   1482:                if (!cmdsOK) {
                   1483:                        DieHorribly();
                   1484:                }
1.6       millert  1485:
1.66      espie    1486:                job->cmdFILE = fopen(tfile, "w+");
                   1487:                if (job->cmdFILE == NULL) {
                   1488:                        Punt("Could not open %s", tfile);
                   1489:                }
                   1490:                (void)fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
                   1491:                /*
                   1492:                 * Send the commands to the command file, flush all its buffers
                   1493:                 * then rewind and remove the thing.
                   1494:                 */
                   1495:                noExec = false;
                   1496:
                   1497:                /*
                   1498:                 * used to be backwards; replace when start doing multiple
                   1499:                 * commands per shell.
                   1500:                 */
                   1501:                if (compatMake) {
                   1502:                        /*
                   1503:                         * Be compatible: If this is the first time for this
                   1504:                         * node, verify its commands are ok and open the
                   1505:                         * commands list for sequential access by later
                   1506:                         * invocations of JobStart.  Once that is done, we take
                   1507:                         * the next command off the list and print it to the
                   1508:                         * command file. If the command was an ellipsis, note
                   1509:                         * that there's nothing more to execute.
                   1510:                         */
                   1511:                        if ((job->flags&JOB_FIRST))
                   1512:                                gn->current = Lst_First(&gn->commands);
                   1513:                        else
                   1514:                                gn->current = Lst_Succ(gn->current);
                   1515:
                   1516:                        if (gn->current == NULL ||
                   1517:                            !JobPrintCommand(gn->current, job)) {
                   1518:                                noExec = true;
                   1519:                                gn->current = NULL;
                   1520:                        }
                   1521:                        if (noExec && !(job->flags & JOB_FIRST)) {
                   1522:                                /*
                   1523:                                 * If we're not going to execute anything, the
                   1524:                                 * job is done and we need to close down the
                   1525:                                 * various file descriptors we've opened for
                   1526:                                 * output, then call JobDoOutput to catch the
                   1527:                                 * final characters or send the file to the
                   1528:                                 * screen... Note that the i/o streams are only
                   1529:                                 * open if this isn't the first job.  Note also
                   1530:                                 * that this could not be done in
                   1531:                                 * Job_CatchChildren b/c it wasn't clear if
                   1532:                                 * there were more commands to execute or
                   1533:                                 * not...
                   1534:                                 */
                   1535:                                JobClose(job);
                   1536:                        }
                   1537:                } else {
                   1538:                        /*
                   1539:                         * We can do all the commands at once. hooray for
                   1540:                         * sanity
                   1541:                         */
                   1542:                        numCommands = 0;
1.68      espie    1543:                        Lst_ForEachNodeWhile(&gn->commands, JobPrintCommand,
1.66      espie    1544:                            job);
                   1545:
                   1546:                        /*
                   1547:                         * If we didn't print out any commands to the shell
                   1548:                         * script, there's not much point in executing the
                   1549:                         * shell, is there?
                   1550:                         */
                   1551:                        if (numCommands == 0) {
                   1552:                                noExec = true;
                   1553:                        }
                   1554:                }
                   1555:        } else if (noExecute) {
                   1556:                /*
                   1557:                 * Not executing anything -- just print all the commands to
                   1558:                 * stdout in one fell swoop. This will still set up
                   1559:                 * job->tailCmds correctly.
                   1560:                 */
                   1561:                if (lastNode != gn) {
                   1562:                        MESSAGE(stdout, gn);
                   1563:                        lastNode = gn;
                   1564:                }
                   1565:                job->cmdFILE = stdout;
                   1566:                /*
                   1567:                 * Only print the commands if they're ok, but don't die if
                   1568:                 * they're not -- just let the user know they're bad and keep
                   1569:                 * going. It doesn't do any harm in this case and may do some
                   1570:                 * good.
                   1571:                 */
                   1572:                if (cmdsOK) {
1.68      espie    1573:                        Lst_ForEachNodeWhile(&gn->commands, JobPrintCommand,
1.66      espie    1574:                            job);
                   1575:                }
                   1576:                /*
                   1577:                 * Don't execute the shell, thank you.
                   1578:                 */
1.41      espie    1579:                noExec = true;
1.66      espie    1580:        } else {
                   1581:                /*
                   1582:                 * Just touch the target and note that no shell should be
                   1583:                 * executed.  Set cmdFILE to stdout to make life easier. Check
                   1584:                 * the commands, too, but don't die if they're no good -- it
                   1585:                 * does no harm to keep working up the graph.
1.30      espie    1586:                 */
1.66      espie    1587:                job->cmdFILE = stdout;
                   1588:                Job_Touch(gn, job->flags&JOB_SILENT);
1.41      espie    1589:                noExec = true;
1.1       deraadt  1590:        }
1.66      espie    1591:
1.1       deraadt  1592:        /*
1.66      espie    1593:         * If we're not supposed to execute a shell, don't.
1.1       deraadt  1594:         */
1.66      espie    1595:        if (noExec) {
                   1596:                /*
                   1597:                 * Unlink and close the command file if we opened one
                   1598:                 */
                   1599:                if (job->cmdFILE != stdout) {
                   1600:                        (void)eunlink(tfile);
                   1601:                        if (job->cmdFILE != NULL)
                   1602:                                (void)fclose(job->cmdFILE);
                   1603:                } else {
                   1604:                         (void)fflush(stdout);
                   1605:                }
1.1       deraadt  1606:
1.66      espie    1607:                /*
                   1608:                 * We only want to work our way up the graph if we aren't here
                   1609:                 * because the commands for the job were no good.
                   1610:                 */
                   1611:                if (cmdsOK) {
                   1612:                        if (aborting == 0) {
1.68      espie    1613:                                Lst_ForEachFrom(job->tailCmds, JobSaveCommand,
1.66      espie    1614:                                    job->node);
                   1615:                                Make_Update(job->node);
                   1616:                        }
                   1617:                        free(job);
                   1618:                        return JOB_FINISHED;
                   1619:                } else {
                   1620:                        free(job);
                   1621:                        return JOB_ERROR;
                   1622:                }
1.1       deraadt  1623:        } else {
1.66      espie    1624:                (void)fflush(job->cmdFILE);
                   1625:                (void)eunlink(tfile);
1.1       deraadt  1626:        }
                   1627:
                   1628:        /*
1.66      espie    1629:         * Set up the control arguments to the shell. This is based on the flags
                   1630:         * set earlier for this job.
1.1       deraadt  1631:         */
1.66      espie    1632:        JobMakeArgv(job, argv);
1.1       deraadt  1633:
1.66      espie    1634:        /*
                   1635:         * If we're using pipes to catch output, create the pipe by which we'll
                   1636:         * get the shell's output. If we're using files, print out that we're
                   1637:         * starting a job and then set up its temporary-file name.
                   1638:         */
                   1639:        if (!compatMake || (job->flags & JOB_FIRST)) {
                   1640:                if (usePipes) {
                   1641:                        int fd[2];
                   1642:                        if (pipe(fd) == -1)
                   1643:                                Punt("Cannot create pipe: %s", strerror(errno));
                   1644:                        job->inPipe = fd[0];
                   1645:                        job->outPipe = fd[1];
                   1646:                        (void)fcntl(job->inPipe, F_SETFD, 1);
                   1647:                        (void)fcntl(job->outPipe, F_SETFD, 1);
                   1648:                } else {
                   1649:                        (void)fprintf(stdout, "Remaking `%s'\n", gn->name);
                   1650:                        (void)fflush(stdout);
1.68      espie    1651:                        (void)strlcpy(job->outFile, TMPPAT,
1.66      espie    1652:                            sizeof(job->outFile));
                   1653:                        if ((job->outFd = mkstemp(job->outFile)) == -1)
1.68      espie    1654:                                Punt("Cannot create temp file: %s",
1.66      espie    1655:                                    strerror(errno));
                   1656:                        (void)fcntl(job->outFd, F_SETFD, 1);
                   1657:                }
1.1       deraadt  1658:        }
                   1659:
1.41      espie    1660:        local = true;
1.1       deraadt  1661:
1.66      espie    1662:        if (local && nLocal >= maxLocal &&
                   1663:            !(job->flags & JOB_SPECIAL) &&
                   1664:            maxLocal != 0
                   1665:            ) {
                   1666:                /*
                   1667:                 * The job can only be run locally, but we've hit the limit of
                   1668:                 * local concurrency, so put the job on hold until some other
                   1669:                 * job finishes. Note that the special jobs (.BEGIN, .INTERRUPT
                   1670:                 * and .END) may be run locally even when the local limit has
                   1671:                 * been reached (e.g. when maxLocal == 0), though they will be
                   1672:                 * exported if at all possible. In addition, any target marked
                   1673:                 * with .NOEXPORT will be run locally if maxLocal is 0.
                   1674:                 */
                   1675:                jobFull = true;
1.6       millert  1676:
1.66      espie    1677:                if (DEBUG(JOB)) {
                   1678:                       (void)fprintf(stdout, "Can only run job locally.\n");
                   1679:                       (void)fflush(stdout);
                   1680:                }
                   1681:                job->flags |= JOB_RESTART;
                   1682:                Lst_AtEnd(&stoppedJobs, job);
                   1683:        } else {
                   1684:                if (nLocal >= maxLocal && local) {
                   1685:                        /*
                   1686:                         * If we're running this job locally as a special case
                   1687:                         * (see above), at least say the table is full.
                   1688:                         */
                   1689:                        jobFull = true;
                   1690:                        if (DEBUG(JOB)) {
1.68      espie    1691:                                (void)fprintf(stdout,
1.66      espie    1692:                                    "Local job queue is full.\n");
                   1693:                                (void)fflush(stdout);
                   1694:                        }
                   1695:                }
                   1696:                JobExec(job, argv);
1.1       deraadt  1697:        }
1.66      espie    1698:        return JOB_RUNNING;
1.1       deraadt  1699: }
                   1700:
1.6       millert  1701: static char *
1.56      espie    1702: JobOutput(Job *job, char *cp, char *endp, int msg)
1.2       deraadt  1703: {
1.66      espie    1704:        char *ecp;
1.2       deraadt  1705:
1.66      espie    1706:        if (commandShell->noPrint) {
                   1707:                ecp = strstr(cp, commandShell->noPrint);
                   1708:                while (ecp != NULL) {
                   1709:                        if (cp != ecp) {
                   1710:                                *ecp = '\0';
                   1711:                                if (msg && job->node != lastNode) {
                   1712:                                        MESSAGE(stdout, job->node);
                   1713:                                        lastNode = job->node;
                   1714:                                }
                   1715:                                /*
                   1716:                                 * The only way there wouldn't be a newline
                   1717:                                 * after this line is if it were the last in
                   1718:                                 * the buffer.  however, since the
                   1719:                                 * non-printable comes after it, there must be
                   1720:                                 * a newline, so we don't print one.
                   1721:                                 */
                   1722:                                (void)fprintf(stdout, "%s", cp);
                   1723:                                (void)fflush(stdout);
                   1724:                        }
                   1725:                        cp = ecp + commandShell->noPLen;
                   1726:                        if (cp != endp) {
                   1727:                                /*
                   1728:                                 * Still more to print, look again after
                   1729:                                 * skipping the whitespace following the
                   1730:                                 * non-printable command....
                   1731:                                 */
                   1732:                                cp++;
1.68      espie    1733:                                while (*cp == ' ' || *cp == '\t' ||
1.66      espie    1734:                                    *cp == '\n') {
                   1735:                                        cp++;
                   1736:                                }
                   1737:                                ecp = strstr(cp, commandShell->noPrint);
                   1738:                        } else {
                   1739:                                return cp;
                   1740:                        }
1.2       deraadt  1741:                }
                   1742:        }
1.66      espie    1743:        return cp;
1.2       deraadt  1744: }
                   1745:
1.1       deraadt  1746: /*-
                   1747:  *-----------------------------------------------------------------------
1.40      espie    1748:  * JobDoOutput --
1.1       deraadt  1749:  *     This function is called at different times depending on
                   1750:  *     whether the user has specified that output is to be collected
                   1751:  *     via pipes or temporary files. In the former case, we are called
                   1752:  *     whenever there is something to read on the pipe. We collect more
                   1753:  *     output from the given job and store it in the job's outBuf. If
                   1754:  *     this makes up a line, we print it tagged by the job's identifier,
                   1755:  *     as necessary.
                   1756:  *     If output has been collected in a temporary file, we open the
                   1757:  *     file and read it line by line, transfering it to our own
                   1758:  *     output channel until the file is empty. At which point we
                   1759:  *     remove the temporary file.
                   1760:  *     In both cases, however, we keep our figurative eye out for the
                   1761:  *     'noPrint' line for the shell from which the output came. If
                   1762:  *     we recognize a line, we don't print it. If the command is not
1.6       millert  1763:  *     alone on the line (the character after it is not \0 or \n), we
1.1       deraadt  1764:  *     do print whatever follows it.
                   1765:  *
                   1766:  * Side Effects:
                   1767:  *     curPos may be shifted as may the contents of outBuf.
                   1768:  *-----------------------------------------------------------------------
                   1769:  */
1.48      espie    1770: static void
1.66      espie    1771: JobDoOutput(Job *job,          /* the job whose output needs printing */
                   1772:     bool finish)               /* true if this is the last time we'll be
                   1773:                                 * called for this job */
                   1774: {
                   1775:        bool gotNL = false;     /* true if got a newline */
                   1776:        bool fbuf;              /* true if our buffer filled up */
                   1777:        int nr;                 /* number of bytes read */
                   1778:        int i;                  /* auxiliary index into outBuf */
                   1779:        int max;                /* limit for i (end of current data) */
                   1780:        int nRead;              /* (Temporary) number of bytes read */
1.1       deraadt  1781:
1.66      espie    1782:        FILE *oFILE;            /* Stream pointer to shell's output file */
                   1783:        char inLine[132];
1.1       deraadt  1784:
1.6       millert  1785:
1.66      espie    1786:        if (usePipes) {
                   1787:                /*
                   1788:                 * Read as many bytes as will fit in the buffer.
                   1789:                 */
1.1       deraadt  1790: end_loop:
1.66      espie    1791:                gotNL = false;
                   1792:                fbuf = false;
1.6       millert  1793:
1.66      espie    1794:                nRead = read(job->inPipe, &job->outBuf[job->curPos],
                   1795:                    JOB_BUFSIZE - job->curPos);
                   1796:                if (nRead == -1) {
                   1797:                        if (DEBUG(JOB)) {
                   1798:                                perror("JobDoOutput(piperead)");
                   1799:                        }
                   1800:                        nr = 0;
                   1801:                } else {
                   1802:                        nr = nRead;
                   1803:                }
1.1       deraadt  1804:
1.66      espie    1805:                /*
                   1806:                 * If we hit the end-of-file (the job is dead), we must flush
                   1807:                 * its remaining output, so pretend we read a newline if
                   1808:                 * there's any output remaining in the buffer.  Also clear the
                   1809:                 * 'finish' flag so we stop looping.
                   1810:                 */
                   1811:                if (nr == 0 && job->curPos != 0) {
                   1812:                        job->outBuf[job->curPos] = '\n';
                   1813:                        nr = 1;
                   1814:                        finish = false;
                   1815:                } else if (nr == 0) {
                   1816:                        finish = false;
                   1817:                }
1.6       millert  1818:
1.1       deraadt  1819:                /*
1.66      espie    1820:                 * Look for the last newline in the bytes we just got. If there
                   1821:                 * is one, break out of the loop with 'i' as its index and
                   1822:                 * gotNL set true.
1.1       deraadt  1823:                 */
1.66      espie    1824:                max = job->curPos + nr;
                   1825:                for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
                   1826:                        if (job->outBuf[i] == '\n') {
                   1827:                                gotNL = true;
                   1828:                                break;
                   1829:                        } else if (job->outBuf[i] == '\0') {
                   1830:                                /*
                   1831:                                 * Why?
                   1832:                                 */
                   1833:                                job->outBuf[i] = ' ';
                   1834:                        }
                   1835:                }
1.6       millert  1836:
1.66      espie    1837:                if (!gotNL) {
                   1838:                        job->curPos += nr;
                   1839:                        if (job->curPos == JOB_BUFSIZE) {
                   1840:                                /*
                   1841:                                 * If we've run out of buffer space, we have no
                   1842:                                 * choice but to print the stuff. sigh.
                   1843:                                 */
                   1844:                                fbuf = true;
                   1845:                                i = job->curPos;
                   1846:                        }
                   1847:                }
                   1848:                if (gotNL || fbuf) {
                   1849:                        /*
                   1850:                         * Need to send the output to the screen. Null
                   1851:                         * terminate it first, overwriting the newline
                   1852:                         * character if there was one.  So long as the line
                   1853:                         * isn't one we should filter (according to the shell
                   1854:                         * description), we print the line, preceded by a
                   1855:                         * target banner if this target isn't the same as the
                   1856:                         * one for which we last printed something.  The rest
                   1857:                         * of the data in the buffer are then shifted down to
                   1858:                         * the start of the buffer and curPos is set
                   1859:                         * accordingly.
                   1860:                         */
                   1861:                        job->outBuf[i] = '\0';
                   1862:                        if (i >= job->curPos) {
                   1863:                                char *cp;
                   1864:
1.68      espie    1865:                                cp = JobOutput(job, job->outBuf,
1.66      espie    1866:                                    &job->outBuf[i], false);
                   1867:
                   1868:                                /*
                   1869:                                 * There's still more in that thar buffer. This
                   1870:                                 * time, though, we know there's no newline at
                   1871:                                 * the end, so we add one of our own free will.
                   1872:                                 */
                   1873:                                if (*cp != '\0') {
                   1874:                                        if (job->node != lastNode) {
                   1875:                                                MESSAGE(stdout, job->node);
                   1876:                                                lastNode = job->node;
                   1877:                                        }
1.68      espie    1878:                                        (void)fprintf(stdout, "%s%s", cp,
1.66      espie    1879:                                            gotNL ? "\n" : "");
                   1880:                                        (void)fflush(stdout);
                   1881:                                }
                   1882:                        }
                   1883:                        if (i < max - 1) {
                   1884:                                /* shift the remaining characters down */
1.68      espie    1885:                                (void)memcpy(job->outBuf, &job->outBuf[i + 1],
1.66      espie    1886:                                    max - (i + 1));
                   1887:                                job->curPos = max - (i + 1);
                   1888:
                   1889:                        } else {
                   1890:                                /*
                   1891:                                 * We have written everything out, so we just
                   1892:                                 * start over from the start of the buffer. No
                   1893:                                 * copying.  No nothing.
                   1894:                                 */
                   1895:                                job->curPos = 0;
                   1896:                        }
                   1897:                }
                   1898:                if (finish) {
                   1899:                        /*
                   1900:                         * If the finish flag is true, we must loop until we
                   1901:                         * hit end-of-file on the pipe. This is guaranteed to
                   1902:                         * happen eventually since the other end of the pipe is
                   1903:                         * now closed (we closed it explicitly and the child
                   1904:                         * has exited). When we do get an EOF, finish will be
                   1905:                         * set false and we'll fall through and out.
                   1906:                         */
                   1907:                        goto end_loop;
                   1908:                }
                   1909:        } else {
                   1910:                /*
                   1911:                 * We've been called to retrieve the output of the job from the
                   1912:                 * temporary file where it's been squirreled away. This
                   1913:                 * consists of opening the file, reading the output line by
                   1914:                 * line, being sure not to print the noPrint line for the shell
                   1915:                 * we used, then close and remove the temporary file. Very
                   1916:                 * simple.
                   1917:                 *
                   1918:                 * Change to read in blocks and do FindSubString type things as
                   1919:                 * for pipes? That would allow for "@echo -n..."
1.1       deraadt  1920:                 */
1.66      espie    1921:                oFILE = fopen(job->outFile, "r");
                   1922:                if (oFILE != NULL) {
1.68      espie    1923:                        (void)fprintf(stdout, "Results of making %s:\n",
1.66      espie    1924:                            job->node->name);
                   1925:                        (void)fflush(stdout);
                   1926:                        while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
                   1927:                                char *cp, *endp, *oendp;
                   1928:
                   1929:                                cp = inLine;
                   1930:                                oendp = endp = inLine + strlen(inLine);
                   1931:                                if (endp != inLine && endp[-1] == '\n') {
                   1932:                                        *--endp = '\0';
                   1933:                                }
                   1934:                                cp = JobOutput(job, inLine, endp, false);
                   1935:
                   1936:                                /*
                   1937:                                 * There's still more in that thar buffer. This
                   1938:                                 * time, though, we know there's no newline at
                   1939:                                 * the end, so we add one of our own free will.
                   1940:                                 */
                   1941:                                (void)fprintf(stdout, "%s", cp);
                   1942:                                (void)fflush(stdout);
                   1943:                                if (endp != oendp) {
                   1944:                                        (void)fprintf(stdout, "\n");
                   1945:                                        (void)fflush(stdout);
                   1946:                                }
                   1947:                        }
                   1948:                        (void)fclose(oFILE);
                   1949:                        (void)eunlink(job->outFile);
                   1950:                }
1.1       deraadt  1951:        }
                   1952: }
                   1953:
                   1954: /*-
                   1955:  *-----------------------------------------------------------------------
                   1956:  * Job_CatchChildren --
                   1957:  *     Handle the exit of a child. Called from Make_Make.
                   1958:  *
                   1959:  * Side Effects:
                   1960:  *     The job descriptor is removed from the list of children.
                   1961:  *
                   1962:  * Notes:
                   1963:  *     We do waits, blocking or not, according to the wisdom of our
                   1964:  *     caller, until there are no more children to report. For each
                   1965:  *     job, call JobFinish to finish things off. This will take care of
                   1966:  *     putting jobs on the stoppedJobs queue.
                   1967:  *-----------------------------------------------------------------------
                   1968:  */
                   1969: void
1.56      espie    1970: Job_CatchChildren(bool block)  /* true if should block on the wait. */
1.1       deraadt  1971: {
1.66      espie    1972:        pid_t pid;              /* pid of dead child */
                   1973:        Job *job;               /* job descriptor for dead child */
                   1974:        LstNode jnode;          /* list element for finding job */
                   1975:        int status;             /* Exit/termination status */
1.1       deraadt  1976:
1.66      espie    1977:        /*
                   1978:         * Don't even bother if we know there's no one around.
                   1979:         */
                   1980:        if (nLocal == 0) {
                   1981:                return;
1.2       deraadt  1982:        }
1.6       millert  1983:
1.66      espie    1984:        while ((pid = waitpid((pid_t) -1, &status,
                   1985:            (block?0:WNOHANG)|WUNTRACED)) > 0) {
                   1986:                HandleSigs();
                   1987:                if (DEBUG(JOB)) {
1.68      espie    1988:                        (void)fprintf(stdout,
1.66      espie    1989:                            "Process %ld exited or stopped.\n", (long)pid);
                   1990:                        (void)fflush(stdout);
                   1991:                }
                   1992:
1.1       deraadt  1993:
1.66      espie    1994:                jnode = Lst_Find(&jobs, JobCmpPid, &pid);
1.1       deraadt  1995:
1.18      espie    1996:                if (jnode == NULL) {
1.68      espie    1997:                        if (WIFSIGNALED(status) &&
1.66      espie    1998:                            (WTERMSIG(status) == SIGCONT)) {
                   1999:                                jnode = Lst_Find(&stoppedJobs, JobCmpPid, &pid);
                   2000:                                if (jnode == NULL) {
                   2001:                                        Error("Resumed child (%ld) not in table", (long)pid);
                   2002:                                        continue;
                   2003:                                }
                   2004:                                job = (Job *)Lst_Datum(jnode);
                   2005:                                Lst_Remove(&stoppedJobs, jnode);
                   2006:                        } else {
                   2007:                                Error("Child (%ld) not in table?", (long)pid);
                   2008:                                continue;
                   2009:                        }
                   2010:                } else {
                   2011:                        job = (Job *)Lst_Datum(jnode);
                   2012:                        Lst_Remove(&jobs, jnode);
1.67      espie    2013:                        nJobs--;
1.66      espie    2014:                        if (jobFull && DEBUG(JOB)) {
1.68      espie    2015:                                (void)fprintf(stdout,
1.66      espie    2016:                                    "Job queue is no longer full.\n");
                   2017:                                (void)fflush(stdout);
                   2018:                        }
                   2019:                        jobFull = false;
1.67      espie    2020:                        nLocal--;
1.1       deraadt  2021:                }
1.66      espie    2022:
                   2023:                JobFinish(job, &status);
1.1       deraadt  2024:        }
                   2025: }
                   2026:
                   2027: /*-
                   2028:  *-----------------------------------------------------------------------
                   2029:  * Job_CatchOutput --
                   2030:  *     Catch the output from our children, if we're using
                   2031:  *     pipes do so. Otherwise just block time until we get a
1.6       millert  2032:  *     signal (most likely a SIGCHLD) since there's no point in
1.1       deraadt  2033:  *     just spinning when there's nothing to do and the reaping
1.6       millert  2034:  *     of a child can wait for a while.
1.1       deraadt  2035:  *
                   2036:  * Side Effects:
                   2037:  *     Output is read from pipes if we're piping.
                   2038:  * -----------------------------------------------------------------------
                   2039:  */
                   2040: void
1.56      espie    2041: Job_CatchOutput(void)
1.1       deraadt  2042: {
1.66      espie    2043:        int nfds;
                   2044:        struct timeval timeout;
                   2045:        LstNode ln;
                   2046:        Job *job;
                   2047:
                   2048:        (void)fflush(stdout);
                   2049:        if (usePipes) {
                   2050:                int count = howmany(outputsn+1, NFDBITS) * sizeof(fd_mask);
                   2051:                fd_set *readfdsp = malloc(count);
                   2052:                if (readfdsp == NULL)
                   2053:                        return;
                   2054:
                   2055:                memcpy(readfdsp, outputsp, count);
                   2056:                timeout.tv_sec = SEL_SEC;
                   2057:                timeout.tv_usec = SEL_USEC;
                   2058:
                   2059:                if ((nfds = select(outputsn+1, readfdsp, (fd_set *) 0,
                   2060:                    (fd_set *) 0, &timeout)) <= 0) {
                   2061:                        HandleSigs();
                   2062:                        free(readfdsp);
                   2063:                        return;
                   2064:                } else {
                   2065:                        HandleSigs();
1.68      espie    2066:                        for (ln = Lst_First(&jobs); nfds && ln != NULL;
1.66      espie    2067:                            ln = Lst_Adv(ln)) {
                   2068:                                job = (Job *)Lst_Datum(ln);
                   2069:                                if (FD_ISSET(job->inPipe, readfdsp)) {
                   2070:                                        JobDoOutput(job, false);
1.67      espie    2071:                                        nfds--;
1.66      espie    2072:                                }
                   2073:                        }
1.1       deraadt  2074:                }
1.66      espie    2075:                free(readfdsp);
1.1       deraadt  2076:        }
                   2077: }
                   2078:
                   2079: /*-
                   2080:  *-----------------------------------------------------------------------
                   2081:  * Job_Make --
                   2082:  *     Start the creation of a target. Basically a front-end for
                   2083:  *     JobStart used by the Make module.
                   2084:  *
                   2085:  * Side Effects:
                   2086:  *     Another job is started.
                   2087:  *-----------------------------------------------------------------------
                   2088:  */
                   2089: void
1.56      espie    2090: Job_Make(GNode *gn)
1.1       deraadt  2091: {
1.66      espie    2092:        (void)JobStart(gn, 0, NULL);
1.1       deraadt  2093: }
                   2094:
                   2095: /*-
                   2096:  *-----------------------------------------------------------------------
                   2097:  * Job_Init --
                   2098:  *     Initialize the process module
                   2099:  *
                   2100:  * Side Effects:
                   2101:  *     lists and counters are initialized
                   2102:  *-----------------------------------------------------------------------
                   2103:  */
                   2104: void
1.56      espie    2105: Job_Init(int     maxproc,  /* the greatest number of jobs which may be
1.1       deraadt  2106:                             * running at one time */
1.56      espie    2107:     int          maxlocal) /* the greatest number of local jobs which may
1.1       deraadt  2108:                             * be running at once. */
                   2109: {
1.66      espie    2110:        GNode *begin;     /* node for commands to do at the very start */
                   2111:        int tfd;
                   2112:
                   2113:        (void)strlcpy(tfile, TMPPAT, sizeof(tfile));
                   2114:        if ((tfd = mkstemp(tfile)) == -1)
                   2115:                Punt("Cannot create temp file: %s", strerror(errno));
                   2116:        else
                   2117:                (void)close(tfd);
                   2118:
                   2119:        Static_Lst_Init(&jobs);
                   2120:        Static_Lst_Init(&stoppedJobs);
                   2121:        maxJobs =         maxproc;
                   2122:        maxLocal =        maxlocal;
                   2123:        nJobs =   0;
                   2124:        nLocal =          0;
                   2125:        jobFull =         false;
                   2126:
                   2127:        aborting =        0;
                   2128:        errors =          0;
1.40      espie    2129:
1.66      espie    2130:        lastNode =        NULL;
1.1       deraadt  2131:
1.66      espie    2132:        if (maxJobs == 1) {
                   2133:                /*
                   2134:                 * If only one job can run at a time, there's no need for a
                   2135:                 * banner, no is there?
                   2136:                 */
                   2137:                targFmt = "";
                   2138:        } else {
                   2139:                targFmt = TARG_FMT;
                   2140:        }
                   2141:
                   2142:        if (commandShell->exit == NULL) {
                   2143:                commandShell->exit = "";
                   2144:        }
                   2145:        if (commandShell->echo == NULL) {
                   2146:                commandShell->echo = "";
                   2147:        }
1.1       deraadt  2148:
                   2149:        /*
1.66      espie    2150:         * Catch the four signals that POSIX specifies if they aren't ignored.
                   2151:         * JobPassSig will take care of calling JobInterrupt if appropriate.
1.1       deraadt  2152:         */
1.66      espie    2153:        if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
                   2154:                (void)signal(SIGINT, SigHandler);
                   2155:        }
                   2156:        if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
                   2157:                (void)signal(SIGHUP, SigHandler);
                   2158:        }
                   2159:        if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
                   2160:                (void)signal(SIGQUIT, SigHandler);
                   2161:        }
                   2162:        if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
                   2163:                (void)signal(SIGTERM, SigHandler);
                   2164:        }
1.1       deraadt  2165:        /*
1.66      espie    2166:         * There are additional signals that need to be caught and passed if
                   2167:         * either the export system wants to be told directly of signals or if
                   2168:         * we're giving each job its own process group (since then it won't get
                   2169:         * signals from the terminal driver as we own the terminal)
1.1       deraadt  2170:         */
1.48      espie    2171: #if defined(USE_PGRP)
1.66      espie    2172:        if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
                   2173:                (void)signal(SIGTSTP, SigHandler);
                   2174:        }
                   2175:        if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
                   2176:                (void)signal(SIGTTOU, SigHandler);
                   2177:        }
                   2178:        if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
                   2179:                (void)signal(SIGTTIN, SigHandler);
                   2180:        }
                   2181:        if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
                   2182:                (void)signal(SIGWINCH, SigHandler);
                   2183:        }
1.1       deraadt  2184: #endif
1.6       millert  2185:
1.66      espie    2186:        begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
1.1       deraadt  2187:
1.66      espie    2188:        if (begin != NULL) {
                   2189:                JobStart(begin, JOB_SPECIAL, (Job *)0);
                   2190:                while (nJobs) {
                   2191:                        Job_CatchOutput();
                   2192:                        Job_CatchChildren(!usePipes);
                   2193:                }
1.1       deraadt  2194:        }
1.66      espie    2195:        postCommands = Targ_FindNode(".END", TARG_CREATE);
1.1       deraadt  2196: }
                   2197:
                   2198: /*-
                   2199:  *-----------------------------------------------------------------------
                   2200:  * Job_Full --
                   2201:  *     See if the job table is full. It is considered full if it is OR
                   2202:  *     if we are in the process of aborting OR if we have
                   2203:  *     reached/exceeded our local quota. This prevents any more jobs
                   2204:  *     from starting up.
                   2205:  *
                   2206:  * Results:
1.41      espie    2207:  *     true if the job table is full, false otherwise
1.1       deraadt  2208:  *-----------------------------------------------------------------------
                   2209:  */
1.41      espie    2210: bool
1.56      espie    2211: Job_Full(void)
1.1       deraadt  2212: {
1.66      espie    2213:        return aborting || jobFull;
1.1       deraadt  2214: }
                   2215:
                   2216: /*-
                   2217:  *-----------------------------------------------------------------------
                   2218:  * Job_Empty --
1.40      espie    2219:  *     See if the job table is empty.  Because the local concurrency may
1.1       deraadt  2220:  *     be set to 0, it is possible for the job table to become empty,
                   2221:  *     while the list of stoppedJobs remains non-empty. In such a case,
                   2222:  *     we want to restart as many jobs as we can.
                   2223:  *
                   2224:  * Results:
1.41      espie    2225:  *     true if it is. false if it ain't.
1.1       deraadt  2226:  * -----------------------------------------------------------------------
                   2227:  */
1.41      espie    2228: bool
1.56      espie    2229: Job_Empty(void)
1.1       deraadt  2230: {
1.66      espie    2231:        if (nJobs == 0) {
                   2232:                if (!Lst_IsEmpty(&stoppedJobs) && !aborting) {
                   2233:                        /*
                   2234:                         * The job table is obviously not full if it has no
                   2235:                         * jobs in it...Try and restart the stopped jobs.
                   2236:                         */
                   2237:                        jobFull = false;
                   2238:                        JobRestartJobs();
                   2239:                        return false;
                   2240:                } else {
                   2241:                        return true;
                   2242:                }
1.1       deraadt  2243:        } else {
1.66      espie    2244:                return false;
1.1       deraadt  2245:        }
                   2246: }
                   2247:
                   2248: /*-
                   2249:  *-----------------------------------------------------------------------
                   2250:  * JobInterrupt --
                   2251:  *     Handle the receipt of an interrupt.
                   2252:  *
                   2253:  * Side Effects:
                   2254:  *     All children are killed. Another job will be started if the
                   2255:  *     .INTERRUPT target was given.
                   2256:  *-----------------------------------------------------------------------
                   2257:  */
                   2258: static void
1.56      espie    2259: JobInterrupt(int runINTERRUPT, /* Non-zero if commands for the .INTERRUPT
1.1       deraadt  2260:                                 * target should be executed */
1.66      espie    2261:     int signo)                 /* signal received */
1.1       deraadt  2262: {
1.66      espie    2263:        LstNode ln;             /* element in job table */
                   2264:        Job  *job;              /* job descriptor in that element */
                   2265:        GNode *interrupt;       /* the node describing the .INTERRUPT target */
                   2266:
                   2267:        aborting = ABORT_INTERRUPT;
                   2268:
                   2269:        for (ln = Lst_First(&jobs); ln != NULL; ln = Lst_Adv(ln)) {
                   2270:                job = (Job *)Lst_Datum(ln);
                   2271:
                   2272:                if (!Targ_Precious(job->node)) {
                   2273:                        const char *file = job->node->path == NULL ?
                   2274:                            job->node->name : job->node->path;
                   2275:                        if (!noExecute && eunlink(file) != -1) {
                   2276:                                Error("*** %s removed", file);
                   2277:                        }
                   2278:                }
                   2279:                if (job->pid) {
                   2280:                        if (DEBUG(JOB)) {
                   2281:                                (void)fprintf(stdout,
                   2282:                                    "JobInterrupt passing signal to child %ld.\n",
                   2283:                                    (long)job->pid);
                   2284:                                (void)fflush(stdout);
                   2285:                        }
                   2286:                        KILL(job->pid, signo);
                   2287:                }
1.2       deraadt  2288:        }
1.1       deraadt  2289:
1.66      espie    2290:        if (runINTERRUPT && !touchFlag) {
                   2291:                interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
                   2292:                if (interrupt != NULL) {
                   2293:                        ignoreErrors = false;
                   2294:
                   2295:                        JobStart(interrupt, JOB_IGNDOTS, (Job *)0);
                   2296:                        while (nJobs) {
                   2297:                                Job_CatchOutput();
                   2298:                                Job_CatchChildren(!usePipes);
                   2299:                        }
                   2300:                }
1.1       deraadt  2301:        }
1.66      espie    2302:        (void)eunlink(tfile);
                   2303:        exit(signo);
1.1       deraadt  2304: }
                   2305:
                   2306: /*
                   2307:  *-----------------------------------------------------------------------
1.12      espie    2308:  * Job_Finish --
1.1       deraadt  2309:  *     Do final processing such as the running of the commands
1.6       millert  2310:  *     attached to the .END target.
1.1       deraadt  2311:  *
                   2312:  * Results:
                   2313:  *     Number of errors reported.
1.40      espie    2314:  *
                   2315:  * Side Effects:
                   2316:  *     The process' temporary file (tfile) is removed if it still
                   2317:  *     existed.
1.1       deraadt  2318:  *-----------------------------------------------------------------------
                   2319:  */
                   2320: int
1.56      espie    2321: Job_Finish(void)
1.1       deraadt  2322: {
1.66      espie    2323:        if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
                   2324:                if (errors) {
                   2325:                        Error("Errors reported so .END ignored");
                   2326:                } else {
                   2327:                        JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
1.1       deraadt  2328:
1.66      espie    2329:                        while (nJobs) {
                   2330:                                Job_CatchOutput();
                   2331:                                Job_CatchChildren(!usePipes);
                   2332:                        }
                   2333:                }
1.1       deraadt  2334:        }
1.66      espie    2335:        (void)eunlink(tfile);
                   2336:        return errors;
1.1       deraadt  2337: }
                   2338:
1.12      espie    2339: /*-
                   2340:  *-----------------------------------------------------------------------
                   2341:  * Job_End --
                   2342:  *     Cleanup any memory used by the jobs module
                   2343:  *
                   2344:  * Side Effects:
                   2345:  *     Memory is freed
                   2346:  *-----------------------------------------------------------------------
                   2347:  */
1.41      espie    2348: #ifdef CLEANUP
1.12      espie    2349: void
1.56      espie    2350: Job_End(void)
1.12      espie    2351: {
1.66      espie    2352:        efree(shellArgv);
1.41      espie    2353: }
1.13      espie    2354: #endif
1.40      espie    2355:
1.1       deraadt  2356: /*-
                   2357:  *-----------------------------------------------------------------------
                   2358:  * Job_Wait --
                   2359:  *     Waits for all running jobs to finish and returns. Sets 'aborting'
                   2360:  *     to ABORT_WAIT to prevent other jobs from starting.
                   2361:  *
                   2362:  * Side Effects:
                   2363:  *     Currently running jobs finish.
                   2364:  *
                   2365:  *-----------------------------------------------------------------------
                   2366:  */
                   2367: void
1.56      espie    2368: Job_Wait(void)
1.1       deraadt  2369: {
1.66      espie    2370:        aborting = ABORT_WAIT;
                   2371:        while (nJobs != 0) {
                   2372:                Job_CatchOutput();
                   2373:                Job_CatchChildren(!usePipes);
                   2374:        }
                   2375:        aborting = 0;
1.1       deraadt  2376: }
                   2377:
                   2378: /*-
                   2379:  *-----------------------------------------------------------------------
                   2380:  * Job_AbortAll --
                   2381:  *     Abort all currently running jobs without handling output or anything.
                   2382:  *     This function is to be called only in the event of a major
                   2383:  *     error. Most definitely NOT to be called from JobInterrupt.
                   2384:  *
                   2385:  * Side Effects:
                   2386:  *     All children are killed, not just the firstborn
                   2387:  *-----------------------------------------------------------------------
                   2388:  */
                   2389: void
1.56      espie    2390: Job_AbortAll(void)
1.1       deraadt  2391: {
1.66      espie    2392:        LstNode ln;     /* element in job table */
                   2393:        Job *job;       /* the job descriptor in that element */
                   2394:        int foo;
1.6       millert  2395:
1.66      espie    2396:        aborting = ABORT_ERROR;
1.6       millert  2397:
1.66      espie    2398:        if (nJobs) {
                   2399:                for (ln = Lst_First(&jobs); ln != NULL; ln = Lst_Adv(ln)) {
                   2400:                        job = (Job *)Lst_Datum(ln);
                   2401:
                   2402:                        /*
                   2403:                         * kill the child process with increasingly drastic
                   2404:                         * signals to make darn sure it's dead.
                   2405:                         */
                   2406:                        KILL(job->pid, SIGINT);
                   2407:                        KILL(job->pid, SIGKILL);
                   2408:                }
1.1       deraadt  2409:        }
1.6       millert  2410:
1.66      espie    2411:        /*
                   2412:         * Catch as many children as want to report in at first, then give up
                   2413:         */
                   2414:        while (waitpid(-1, &foo, WNOHANG) > 0)
                   2415:                continue;
                   2416:        (void)eunlink(tfile);
1.2       deraadt  2417: }
1.40      espie    2418:
1.2       deraadt  2419: /*-
                   2420:  *-----------------------------------------------------------------------
                   2421:  * JobRestartJobs --
                   2422:  *     Tries to restart stopped jobs if there are slots available.
                   2423:  *     Note that this tries to restart them regardless of pending errors.
                   2424:  *     It's not good to leave stopped jobs lying around!
                   2425:  *
                   2426:  * Side Effects:
                   2427:  *     Resumes(and possibly migrates) jobs.
                   2428:  *-----------------------------------------------------------------------
                   2429:  */
                   2430: static void
1.56      espie    2431: JobRestartJobs(void)
1.2       deraadt  2432: {
1.66      espie    2433:        Job *job;
1.19      espie    2434:
1.66      espie    2435:        while (!jobFull && (job = (Job *)Lst_DeQueue(&stoppedJobs)) != NULL) {
                   2436:                if (DEBUG(JOB)) {
                   2437:                        (void)fprintf(stdout,
                   2438:                            "Job queue is not full. Restarting a stopped job.\n");
                   2439:                        (void)fflush(stdout);
                   2440:                }
                   2441:                JobRestart(job);
1.2       deraadt  2442:        }
1.1       deraadt  2443: }