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

1.40      espie       1: /*     $OpenPackages$ */
1.73    ! espie       2: /*     $OpenBSD: job.c,v 1.72 2007/09/17 10:31:13 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.73    ! espie    1251:        (void)snprintf(args, sizeof(args), "-%s%s",
        !          1252:            (job->flags & JOB_IGNERR) ? "" : SHELL_ERROR_FLAG,
        !          1253:            (job->flags & JOB_SILENT) ? "" : SHELL_ECHO_FLAG);
        !          1254:
        !          1255:        if (args[1]) {
        !          1256:                argv[argc] = args;
        !          1257:                argc++;
        !          1258:        }
1.66      espie    1259:        argv[argc] = NULL;
1.1       deraadt  1260: }
                   1261:
                   1262: /*-
                   1263:  *-----------------------------------------------------------------------
                   1264:  * JobRestart --
1.6       millert  1265:  *     Restart a job that stopped for some reason.
1.1       deraadt  1266:  *
                   1267:  * Side Effects:
                   1268:  *     jobFull will be set if the job couldn't be run.
                   1269:  *-----------------------------------------------------------------------
                   1270:  */
                   1271: static void
1.56      espie    1272: JobRestart(Job *job)
1.1       deraadt  1273: {
1.66      espie    1274:        if (job->flags & JOB_RESTART) {
                   1275:                /*
                   1276:                 * Set up the control arguments to the shell. This is based on
                   1277:                 * the flags set earlier for this job. If the JOB_IGNERR flag
                   1278:                 * is clear, the 'exit' flag of the commandShell is used to
                   1279:                 * cause it to exit upon receiving an error. If the JOB_SILENT
                   1280:                 * flag is clear, the 'echo' flag of the commandShell is used
                   1281:                 * to get it to start echoing as soon as it starts processing
                   1282:                 * commands.
                   1283:                 */
                   1284:                char *argv[4];
1.6       millert  1285:
1.66      espie    1286:                JobMakeArgv(job, argv);
1.2       deraadt  1287:
1.1       deraadt  1288:                if (DEBUG(JOB)) {
1.68      espie    1289:                        (void)fprintf(stdout, "Restarting %s...",
1.66      espie    1290:                            job->node->name);
                   1291:                        (void)fflush(stdout);
1.1       deraadt  1292:                }
1.66      espie    1293:                if (nLocal >= maxLocal && !(job->flags & JOB_SPECIAL)) {
                   1294:                        /*
                   1295:                         * Can't be exported and not allowed to run locally --
                   1296:                         * put it back on the hold queue and mark the table
                   1297:                         * full
                   1298:                         */
                   1299:                        if (DEBUG(JOB)) {
                   1300:                                (void)fprintf(stdout, "holding\n");
                   1301:                                (void)fflush(stdout);
                   1302:                        }
                   1303:                        Lst_AtFront(&stoppedJobs, job);
                   1304:                        jobFull = true;
                   1305:                        if (DEBUG(JOB)) {
                   1306:                                (void)fprintf(stdout, "Job queue is full.\n");
                   1307:                                (void)fflush(stdout);
                   1308:                        }
                   1309:                        return;
                   1310:                } else {
                   1311:                        /*
                   1312:                         * Job may be run locally.
                   1313:                         */
                   1314:                        if (DEBUG(JOB)) {
                   1315:                                (void)fprintf(stdout, "running locally\n");
                   1316:                                (void)fflush(stdout);
                   1317:                        }
1.1       deraadt  1318:                }
1.66      espie    1319:                JobExec(job, argv);
                   1320:        } else {
1.1       deraadt  1321:                /*
1.66      espie    1322:                 * The job has stopped and needs to be restarted. Why it
                   1323:                 * stopped, we don't know...
1.1       deraadt  1324:                 */
                   1325:                if (DEBUG(JOB)) {
1.66      espie    1326:                       (void)fprintf(stdout, "Resuming %s...", job->node->name);
                   1327:                       (void)fflush(stdout);
1.1       deraadt  1328:                }
1.66      espie    1329:                if ((nLocal < maxLocal ||
                   1330:                    ((job->flags & JOB_SPECIAL) &&
                   1331:                     maxLocal == 0)
                   1332:                   ) && nJobs != maxJobs) {
                   1333:                        /*
                   1334:                         * If we haven't reached the concurrency limit already
                   1335:                         * (or maxLocal is 0), it's ok to resume the job.
                   1336:                         */
                   1337:                        bool error;
                   1338:                        int status;
                   1339:
                   1340:                        error = KILL(job->pid, SIGCONT) != 0;
                   1341:
                   1342:                        if (!error) {
                   1343:                                /*
                   1344:                                 * Make sure the user knows we've continued the
                   1345:                                 * beast and actually put the thing in the job
                   1346:                                 * table.
                   1347:                                 */
                   1348:                                job->flags |= JOB_CONTINUING;
                   1349:                                W_SETTERMSIG(&status, SIGCONT);
                   1350:                                JobFinish(job, &status);
                   1351:
                   1352:                                job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
                   1353:                                if (DEBUG(JOB)) {
                   1354:                                       (void)fprintf(stdout, "done\n");
                   1355:                                       (void)fflush(stdout);
                   1356:                                }
                   1357:                        } else {
                   1358:                                Error("couldn't resume %s: %s",
                   1359:                                    job->node->name, strerror(errno));
                   1360:                                status = 0;
                   1361:                                W_SETEXITSTATUS(&status, 1);
                   1362:                                JobFinish(job, &status);
                   1363:                        }
                   1364:                } else {
                   1365:                        /*
                   1366:                         * Job cannot be restarted. Mark the table as full and
                   1367:                         * place the job back on the list of stopped jobs.
                   1368:                         */
                   1369:                        if (DEBUG(JOB)) {
                   1370:                                (void)fprintf(stdout, "table full\n");
                   1371:                                (void)fflush(stdout);
                   1372:                        }
                   1373:                        Lst_AtFront(&stoppedJobs, job);
                   1374:                        jobFull = true;
                   1375:                        if (DEBUG(JOB)) {
                   1376:                                (void)fprintf(stdout, "Job queue is full.\n");
                   1377:                                (void)fflush(stdout);
                   1378:                        }
1.1       deraadt  1379:                }
                   1380:        }
                   1381: }
                   1382:
                   1383: /*-
                   1384:  *-----------------------------------------------------------------------
                   1385:  * JobStart  --
                   1386:  *     Start a target-creation process going for the target described
1.6       millert  1387:  *     by the graph node gn.
1.1       deraadt  1388:  *
                   1389:  * Results:
                   1390:  *     JOB_ERROR if there was an error in the commands, JOB_FINISHED
                   1391:  *     if there isn't actually anything left to do for the job and
                   1392:  *     JOB_RUNNING if the job has been started.
                   1393:  *
                   1394:  * Side Effects:
                   1395:  *     A new Job node is created and added to the list of running
                   1396:  *     jobs. PMake is forked and a child shell created.
                   1397:  *-----------------------------------------------------------------------
                   1398:  */
                   1399: static int
1.56      espie    1400: JobStart(GNode   *gn,        /* target to create */
                   1401:     int           flags,      /* flags for the job to override normal ones.
1.1       deraadt  1402:                               * e.g. JOB_SPECIAL or JOB_IGNDOTS */
1.56      espie    1403:     Job          *previous)  /* The previous Job structure for this node,
1.1       deraadt  1404:                               * if any. */
                   1405: {
1.66      espie    1406:        Job *job;       /* new job descriptor */
                   1407:        char *argv[4];  /* Argument vector to shell */
                   1408:        bool cmdsOK;    /* true if the nodes commands were all right */
                   1409:        bool local;     /* Set true if the job was run locally */
                   1410:        bool noExec;    /* Set true if we decide not to run the job */
                   1411:
                   1412:        if (previous != NULL) {
                   1413:                previous->flags &= ~(JOB_FIRST|JOB_IGNERR|JOB_SILENT);
                   1414:                job = previous;
                   1415:        } else {
                   1416:                job = emalloc(sizeof(Job));
                   1417:                if (job == NULL) {
                   1418:                        Punt("JobStart out of memory");
                   1419:                }
                   1420:                flags |= JOB_FIRST;
1.1       deraadt  1421:        }
                   1422:
1.66      espie    1423:        job->node = gn;
                   1424:        job->tailCmds = NULL;
1.1       deraadt  1425:
                   1426:        /*
1.66      espie    1427:         * Set the initial value of the flags for this job based on the global
                   1428:         * ones and the node's attributes... Any flags supplied by the caller
                   1429:         * are also added to the field.
1.1       deraadt  1430:         */
1.66      espie    1431:        job->flags = 0;
                   1432:        if (Targ_Ignore(gn)) {
                   1433:                job->flags |= JOB_IGNERR;
                   1434:        }
                   1435:        if (Targ_Silent(gn)) {
                   1436:                job->flags |= JOB_SILENT;
1.1       deraadt  1437:        }
1.66      espie    1438:        job->flags |= flags;
1.6       millert  1439:
1.1       deraadt  1440:        /*
1.66      espie    1441:         * Check the commands now so any attributes from .DEFAULT have a chance
                   1442:         * to migrate to the node
1.1       deraadt  1443:         */
1.66      espie    1444:        if (!compatMake && job->flags & JOB_FIRST) {
                   1445:                cmdsOK = Job_CheckCommands(gn, Error);
                   1446:        } else {
                   1447:                cmdsOK = true;
                   1448:        }
1.1       deraadt  1449:
                   1450:        /*
1.66      espie    1451:         * If the -n flag wasn't given, we open up OUR (not the child's)
                   1452:         * temporary file to stuff commands in it. The thing is rd/wr so we
                   1453:         * don't need to reopen it to feed it to the shell. If the -n flag
                   1454:         * *was* given, we just set the file to be stdout. Cute, huh?
1.1       deraadt  1455:         */
1.66      espie    1456:        if ((gn->type & OP_MAKE) || (!noExecute && !touchFlag)) {
                   1457:                /*
                   1458:                 * We're serious here, but if the commands were bogus, we're
                   1459:                 * also dead...
                   1460:                 */
                   1461:                if (!cmdsOK) {
                   1462:                        DieHorribly();
                   1463:                }
1.6       millert  1464:
1.66      espie    1465:                job->cmdFILE = fopen(tfile, "w+");
                   1466:                if (job->cmdFILE == NULL) {
                   1467:                        Punt("Could not open %s", tfile);
                   1468:                }
                   1469:                (void)fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
                   1470:                /*
                   1471:                 * Send the commands to the command file, flush all its buffers
                   1472:                 * then rewind and remove the thing.
                   1473:                 */
                   1474:                noExec = false;
                   1475:
                   1476:                /*
                   1477:                 * used to be backwards; replace when start doing multiple
                   1478:                 * commands per shell.
                   1479:                 */
                   1480:                if (compatMake) {
                   1481:                        /*
                   1482:                         * Be compatible: If this is the first time for this
                   1483:                         * node, verify its commands are ok and open the
                   1484:                         * commands list for sequential access by later
                   1485:                         * invocations of JobStart.  Once that is done, we take
                   1486:                         * the next command off the list and print it to the
                   1487:                         * command file. If the command was an ellipsis, note
                   1488:                         * that there's nothing more to execute.
                   1489:                         */
                   1490:                        if ((job->flags&JOB_FIRST))
                   1491:                                gn->current = Lst_First(&gn->commands);
                   1492:                        else
                   1493:                                gn->current = Lst_Succ(gn->current);
                   1494:
                   1495:                        if (gn->current == NULL ||
                   1496:                            !JobPrintCommand(gn->current, job)) {
                   1497:                                noExec = true;
                   1498:                                gn->current = NULL;
                   1499:                        }
                   1500:                        if (noExec && !(job->flags & JOB_FIRST)) {
                   1501:                                /*
                   1502:                                 * If we're not going to execute anything, the
                   1503:                                 * job is done and we need to close down the
                   1504:                                 * various file descriptors we've opened for
                   1505:                                 * output, then call JobDoOutput to catch the
                   1506:                                 * final characters or send the file to the
                   1507:                                 * screen... Note that the i/o streams are only
                   1508:                                 * open if this isn't the first job.  Note also
                   1509:                                 * that this could not be done in
                   1510:                                 * Job_CatchChildren b/c it wasn't clear if
                   1511:                                 * there were more commands to execute or
                   1512:                                 * not...
                   1513:                                 */
                   1514:                                JobClose(job);
                   1515:                        }
                   1516:                } else {
                   1517:                        /*
                   1518:                         * We can do all the commands at once. hooray for
                   1519:                         * sanity
                   1520:                         */
                   1521:                        numCommands = 0;
1.68      espie    1522:                        Lst_ForEachNodeWhile(&gn->commands, JobPrintCommand,
1.66      espie    1523:                            job);
                   1524:
                   1525:                        /*
                   1526:                         * If we didn't print out any commands to the shell
                   1527:                         * script, there's not much point in executing the
                   1528:                         * shell, is there?
                   1529:                         */
                   1530:                        if (numCommands == 0) {
                   1531:                                noExec = true;
                   1532:                        }
                   1533:                }
                   1534:        } else if (noExecute) {
                   1535:                /*
                   1536:                 * Not executing anything -- just print all the commands to
                   1537:                 * stdout in one fell swoop. This will still set up
                   1538:                 * job->tailCmds correctly.
                   1539:                 */
                   1540:                if (lastNode != gn) {
                   1541:                        MESSAGE(stdout, gn);
                   1542:                        lastNode = gn;
                   1543:                }
                   1544:                job->cmdFILE = stdout;
                   1545:                /*
                   1546:                 * Only print the commands if they're ok, but don't die if
                   1547:                 * they're not -- just let the user know they're bad and keep
                   1548:                 * going. It doesn't do any harm in this case and may do some
                   1549:                 * good.
                   1550:                 */
                   1551:                if (cmdsOK) {
1.68      espie    1552:                        Lst_ForEachNodeWhile(&gn->commands, JobPrintCommand,
1.66      espie    1553:                            job);
                   1554:                }
                   1555:                /*
                   1556:                 * Don't execute the shell, thank you.
                   1557:                 */
1.41      espie    1558:                noExec = true;
1.66      espie    1559:        } else {
                   1560:                /*
                   1561:                 * Just touch the target and note that no shell should be
                   1562:                 * executed.  Set cmdFILE to stdout to make life easier. Check
                   1563:                 * the commands, too, but don't die if they're no good -- it
                   1564:                 * does no harm to keep working up the graph.
1.30      espie    1565:                 */
1.66      espie    1566:                job->cmdFILE = stdout;
                   1567:                Job_Touch(gn, job->flags&JOB_SILENT);
1.41      espie    1568:                noExec = true;
1.1       deraadt  1569:        }
1.66      espie    1570:
1.1       deraadt  1571:        /*
1.66      espie    1572:         * If we're not supposed to execute a shell, don't.
1.1       deraadt  1573:         */
1.66      espie    1574:        if (noExec) {
                   1575:                /*
                   1576:                 * Unlink and close the command file if we opened one
                   1577:                 */
                   1578:                if (job->cmdFILE != stdout) {
                   1579:                        (void)eunlink(tfile);
                   1580:                        if (job->cmdFILE != NULL)
                   1581:                                (void)fclose(job->cmdFILE);
                   1582:                } else {
                   1583:                         (void)fflush(stdout);
                   1584:                }
1.1       deraadt  1585:
1.66      espie    1586:                /*
                   1587:                 * We only want to work our way up the graph if we aren't here
                   1588:                 * because the commands for the job were no good.
                   1589:                 */
                   1590:                if (cmdsOK) {
                   1591:                        if (aborting == 0) {
1.68      espie    1592:                                Lst_ForEachFrom(job->tailCmds, JobSaveCommand,
1.66      espie    1593:                                    job->node);
                   1594:                                Make_Update(job->node);
                   1595:                        }
                   1596:                        free(job);
                   1597:                        return JOB_FINISHED;
                   1598:                } else {
                   1599:                        free(job);
                   1600:                        return JOB_ERROR;
                   1601:                }
1.1       deraadt  1602:        } else {
1.66      espie    1603:                (void)fflush(job->cmdFILE);
                   1604:                (void)eunlink(tfile);
1.1       deraadt  1605:        }
                   1606:
                   1607:        /*
1.66      espie    1608:         * Set up the control arguments to the shell. This is based on the flags
                   1609:         * set earlier for this job.
1.1       deraadt  1610:         */
1.66      espie    1611:        JobMakeArgv(job, argv);
1.1       deraadt  1612:
1.66      espie    1613:        /*
                   1614:         * If we're using pipes to catch output, create the pipe by which we'll
                   1615:         * get the shell's output. If we're using files, print out that we're
                   1616:         * starting a job and then set up its temporary-file name.
                   1617:         */
                   1618:        if (!compatMake || (job->flags & JOB_FIRST)) {
                   1619:                if (usePipes) {
                   1620:                        int fd[2];
                   1621:                        if (pipe(fd) == -1)
                   1622:                                Punt("Cannot create pipe: %s", strerror(errno));
                   1623:                        job->inPipe = fd[0];
                   1624:                        job->outPipe = fd[1];
                   1625:                        (void)fcntl(job->inPipe, F_SETFD, 1);
                   1626:                        (void)fcntl(job->outPipe, F_SETFD, 1);
                   1627:                } else {
                   1628:                        (void)fprintf(stdout, "Remaking `%s'\n", gn->name);
                   1629:                        (void)fflush(stdout);
1.68      espie    1630:                        (void)strlcpy(job->outFile, TMPPAT,
1.66      espie    1631:                            sizeof(job->outFile));
                   1632:                        if ((job->outFd = mkstemp(job->outFile)) == -1)
1.68      espie    1633:                                Punt("Cannot create temp file: %s",
1.66      espie    1634:                                    strerror(errno));
                   1635:                        (void)fcntl(job->outFd, F_SETFD, 1);
                   1636:                }
1.1       deraadt  1637:        }
                   1638:
1.41      espie    1639:        local = true;
1.1       deraadt  1640:
1.66      espie    1641:        if (local && nLocal >= maxLocal &&
                   1642:            !(job->flags & JOB_SPECIAL) &&
                   1643:            maxLocal != 0
                   1644:            ) {
                   1645:                /*
                   1646:                 * The job can only be run locally, but we've hit the limit of
                   1647:                 * local concurrency, so put the job on hold until some other
                   1648:                 * job finishes. Note that the special jobs (.BEGIN, .INTERRUPT
                   1649:                 * and .END) may be run locally even when the local limit has
                   1650:                 * been reached (e.g. when maxLocal == 0), though they will be
                   1651:                 * exported if at all possible. In addition, any target marked
                   1652:                 * with .NOEXPORT will be run locally if maxLocal is 0.
                   1653:                 */
                   1654:                jobFull = true;
1.6       millert  1655:
1.66      espie    1656:                if (DEBUG(JOB)) {
                   1657:                       (void)fprintf(stdout, "Can only run job locally.\n");
                   1658:                       (void)fflush(stdout);
                   1659:                }
                   1660:                job->flags |= JOB_RESTART;
                   1661:                Lst_AtEnd(&stoppedJobs, job);
                   1662:        } else {
                   1663:                if (nLocal >= maxLocal && local) {
                   1664:                        /*
                   1665:                         * If we're running this job locally as a special case
                   1666:                         * (see above), at least say the table is full.
                   1667:                         */
                   1668:                        jobFull = true;
                   1669:                        if (DEBUG(JOB)) {
1.68      espie    1670:                                (void)fprintf(stdout,
1.66      espie    1671:                                    "Local job queue is full.\n");
                   1672:                                (void)fflush(stdout);
                   1673:                        }
                   1674:                }
                   1675:                JobExec(job, argv);
1.1       deraadt  1676:        }
1.66      espie    1677:        return JOB_RUNNING;
1.1       deraadt  1678: }
                   1679:
1.6       millert  1680: static char *
1.56      espie    1681: JobOutput(Job *job, char *cp, char *endp, int msg)
1.2       deraadt  1682: {
1.66      espie    1683:        char *ecp;
1.2       deraadt  1684:
1.66      espie    1685:        if (commandShell->noPrint) {
                   1686:                ecp = strstr(cp, commandShell->noPrint);
                   1687:                while (ecp != NULL) {
                   1688:                        if (cp != ecp) {
                   1689:                                *ecp = '\0';
                   1690:                                if (msg && job->node != lastNode) {
                   1691:                                        MESSAGE(stdout, job->node);
                   1692:                                        lastNode = job->node;
                   1693:                                }
                   1694:                                /*
                   1695:                                 * The only way there wouldn't be a newline
                   1696:                                 * after this line is if it were the last in
                   1697:                                 * the buffer.  however, since the
                   1698:                                 * non-printable comes after it, there must be
                   1699:                                 * a newline, so we don't print one.
                   1700:                                 */
                   1701:                                (void)fprintf(stdout, "%s", cp);
                   1702:                                (void)fflush(stdout);
                   1703:                        }
                   1704:                        cp = ecp + commandShell->noPLen;
                   1705:                        if (cp != endp) {
                   1706:                                /*
                   1707:                                 * Still more to print, look again after
                   1708:                                 * skipping the whitespace following the
                   1709:                                 * non-printable command....
                   1710:                                 */
                   1711:                                cp++;
1.68      espie    1712:                                while (*cp == ' ' || *cp == '\t' ||
1.66      espie    1713:                                    *cp == '\n') {
                   1714:                                        cp++;
                   1715:                                }
                   1716:                                ecp = strstr(cp, commandShell->noPrint);
                   1717:                        } else {
                   1718:                                return cp;
                   1719:                        }
1.2       deraadt  1720:                }
                   1721:        }
1.66      espie    1722:        return cp;
1.2       deraadt  1723: }
                   1724:
1.1       deraadt  1725: /*-
                   1726:  *-----------------------------------------------------------------------
1.40      espie    1727:  * JobDoOutput --
1.1       deraadt  1728:  *     This function is called at different times depending on
                   1729:  *     whether the user has specified that output is to be collected
                   1730:  *     via pipes or temporary files. In the former case, we are called
                   1731:  *     whenever there is something to read on the pipe. We collect more
                   1732:  *     output from the given job and store it in the job's outBuf. If
                   1733:  *     this makes up a line, we print it tagged by the job's identifier,
                   1734:  *     as necessary.
                   1735:  *     If output has been collected in a temporary file, we open the
                   1736:  *     file and read it line by line, transfering it to our own
                   1737:  *     output channel until the file is empty. At which point we
                   1738:  *     remove the temporary file.
                   1739:  *     In both cases, however, we keep our figurative eye out for the
                   1740:  *     'noPrint' line for the shell from which the output came. If
                   1741:  *     we recognize a line, we don't print it. If the command is not
1.6       millert  1742:  *     alone on the line (the character after it is not \0 or \n), we
1.1       deraadt  1743:  *     do print whatever follows it.
                   1744:  *
                   1745:  * Side Effects:
                   1746:  *     curPos may be shifted as may the contents of outBuf.
                   1747:  *-----------------------------------------------------------------------
                   1748:  */
1.48      espie    1749: static void
1.66      espie    1750: JobDoOutput(Job *job,          /* the job whose output needs printing */
                   1751:     bool finish)               /* true if this is the last time we'll be
                   1752:                                 * called for this job */
                   1753: {
                   1754:        bool gotNL = false;     /* true if got a newline */
                   1755:        bool fbuf;              /* true if our buffer filled up */
                   1756:        int nr;                 /* number of bytes read */
                   1757:        int i;                  /* auxiliary index into outBuf */
                   1758:        int max;                /* limit for i (end of current data) */
                   1759:        int nRead;              /* (Temporary) number of bytes read */
1.1       deraadt  1760:
1.66      espie    1761:        FILE *oFILE;            /* Stream pointer to shell's output file */
                   1762:        char inLine[132];
1.1       deraadt  1763:
1.6       millert  1764:
1.66      espie    1765:        if (usePipes) {
                   1766:                /*
                   1767:                 * Read as many bytes as will fit in the buffer.
                   1768:                 */
1.1       deraadt  1769: end_loop:
1.66      espie    1770:                gotNL = false;
                   1771:                fbuf = false;
1.6       millert  1772:
1.66      espie    1773:                nRead = read(job->inPipe, &job->outBuf[job->curPos],
                   1774:                    JOB_BUFSIZE - job->curPos);
                   1775:                if (nRead == -1) {
                   1776:                        if (DEBUG(JOB)) {
                   1777:                                perror("JobDoOutput(piperead)");
                   1778:                        }
                   1779:                        nr = 0;
                   1780:                } else {
                   1781:                        nr = nRead;
                   1782:                }
1.1       deraadt  1783:
1.66      espie    1784:                /*
                   1785:                 * If we hit the end-of-file (the job is dead), we must flush
                   1786:                 * its remaining output, so pretend we read a newline if
                   1787:                 * there's any output remaining in the buffer.  Also clear the
                   1788:                 * 'finish' flag so we stop looping.
                   1789:                 */
                   1790:                if (nr == 0 && job->curPos != 0) {
                   1791:                        job->outBuf[job->curPos] = '\n';
                   1792:                        nr = 1;
                   1793:                        finish = false;
                   1794:                } else if (nr == 0) {
                   1795:                        finish = false;
                   1796:                }
1.6       millert  1797:
1.1       deraadt  1798:                /*
1.66      espie    1799:                 * Look for the last newline in the bytes we just got. If there
                   1800:                 * is one, break out of the loop with 'i' as its index and
                   1801:                 * gotNL set true.
1.1       deraadt  1802:                 */
1.66      espie    1803:                max = job->curPos + nr;
                   1804:                for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
                   1805:                        if (job->outBuf[i] == '\n') {
                   1806:                                gotNL = true;
                   1807:                                break;
                   1808:                        } else if (job->outBuf[i] == '\0') {
                   1809:                                /*
                   1810:                                 * Why?
                   1811:                                 */
                   1812:                                job->outBuf[i] = ' ';
                   1813:                        }
                   1814:                }
1.6       millert  1815:
1.66      espie    1816:                if (!gotNL) {
                   1817:                        job->curPos += nr;
                   1818:                        if (job->curPos == JOB_BUFSIZE) {
                   1819:                                /*
                   1820:                                 * If we've run out of buffer space, we have no
                   1821:                                 * choice but to print the stuff. sigh.
                   1822:                                 */
                   1823:                                fbuf = true;
                   1824:                                i = job->curPos;
                   1825:                        }
                   1826:                }
                   1827:                if (gotNL || fbuf) {
                   1828:                        /*
                   1829:                         * Need to send the output to the screen. Null
                   1830:                         * terminate it first, overwriting the newline
                   1831:                         * character if there was one.  So long as the line
                   1832:                         * isn't one we should filter (according to the shell
                   1833:                         * description), we print the line, preceded by a
                   1834:                         * target banner if this target isn't the same as the
                   1835:                         * one for which we last printed something.  The rest
                   1836:                         * of the data in the buffer are then shifted down to
                   1837:                         * the start of the buffer and curPos is set
                   1838:                         * accordingly.
                   1839:                         */
                   1840:                        job->outBuf[i] = '\0';
                   1841:                        if (i >= job->curPos) {
                   1842:                                char *cp;
                   1843:
1.68      espie    1844:                                cp = JobOutput(job, job->outBuf,
1.66      espie    1845:                                    &job->outBuf[i], false);
                   1846:
                   1847:                                /*
                   1848:                                 * There's still more in that thar buffer. This
                   1849:                                 * time, though, we know there's no newline at
                   1850:                                 * the end, so we add one of our own free will.
                   1851:                                 */
                   1852:                                if (*cp != '\0') {
                   1853:                                        if (job->node != lastNode) {
                   1854:                                                MESSAGE(stdout, job->node);
                   1855:                                                lastNode = job->node;
                   1856:                                        }
1.68      espie    1857:                                        (void)fprintf(stdout, "%s%s", cp,
1.66      espie    1858:                                            gotNL ? "\n" : "");
                   1859:                                        (void)fflush(stdout);
                   1860:                                }
                   1861:                        }
                   1862:                        if (i < max - 1) {
                   1863:                                /* shift the remaining characters down */
1.68      espie    1864:                                (void)memcpy(job->outBuf, &job->outBuf[i + 1],
1.66      espie    1865:                                    max - (i + 1));
                   1866:                                job->curPos = max - (i + 1);
                   1867:
                   1868:                        } else {
                   1869:                                /*
                   1870:                                 * We have written everything out, so we just
                   1871:                                 * start over from the start of the buffer. No
                   1872:                                 * copying.  No nothing.
                   1873:                                 */
                   1874:                                job->curPos = 0;
                   1875:                        }
                   1876:                }
                   1877:                if (finish) {
                   1878:                        /*
                   1879:                         * If the finish flag is true, we must loop until we
                   1880:                         * hit end-of-file on the pipe. This is guaranteed to
                   1881:                         * happen eventually since the other end of the pipe is
                   1882:                         * now closed (we closed it explicitly and the child
                   1883:                         * has exited). When we do get an EOF, finish will be
                   1884:                         * set false and we'll fall through and out.
                   1885:                         */
                   1886:                        goto end_loop;
                   1887:                }
                   1888:        } else {
                   1889:                /*
                   1890:                 * We've been called to retrieve the output of the job from the
                   1891:                 * temporary file where it's been squirreled away. This
                   1892:                 * consists of opening the file, reading the output line by
                   1893:                 * line, being sure not to print the noPrint line for the shell
                   1894:                 * we used, then close and remove the temporary file. Very
                   1895:                 * simple.
                   1896:                 *
                   1897:                 * Change to read in blocks and do FindSubString type things as
                   1898:                 * for pipes? That would allow for "@echo -n..."
1.1       deraadt  1899:                 */
1.66      espie    1900:                oFILE = fopen(job->outFile, "r");
                   1901:                if (oFILE != NULL) {
1.68      espie    1902:                        (void)fprintf(stdout, "Results of making %s:\n",
1.66      espie    1903:                            job->node->name);
                   1904:                        (void)fflush(stdout);
                   1905:                        while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
                   1906:                                char *cp, *endp, *oendp;
                   1907:
                   1908:                                cp = inLine;
                   1909:                                oendp = endp = inLine + strlen(inLine);
                   1910:                                if (endp != inLine && endp[-1] == '\n') {
                   1911:                                        *--endp = '\0';
                   1912:                                }
                   1913:                                cp = JobOutput(job, inLine, endp, false);
                   1914:
                   1915:                                /*
                   1916:                                 * There's still more in that thar buffer. This
                   1917:                                 * time, though, we know there's no newline at
                   1918:                                 * the end, so we add one of our own free will.
                   1919:                                 */
                   1920:                                (void)fprintf(stdout, "%s", cp);
                   1921:                                (void)fflush(stdout);
                   1922:                                if (endp != oendp) {
                   1923:                                        (void)fprintf(stdout, "\n");
                   1924:                                        (void)fflush(stdout);
                   1925:                                }
                   1926:                        }
                   1927:                        (void)fclose(oFILE);
                   1928:                        (void)eunlink(job->outFile);
                   1929:                }
1.1       deraadt  1930:        }
                   1931: }
                   1932:
                   1933: /*-
                   1934:  *-----------------------------------------------------------------------
                   1935:  * Job_CatchChildren --
                   1936:  *     Handle the exit of a child. Called from Make_Make.
                   1937:  *
                   1938:  * Side Effects:
                   1939:  *     The job descriptor is removed from the list of children.
                   1940:  *
                   1941:  * Notes:
                   1942:  *     We do waits, blocking or not, according to the wisdom of our
                   1943:  *     caller, until there are no more children to report. For each
                   1944:  *     job, call JobFinish to finish things off. This will take care of
                   1945:  *     putting jobs on the stoppedJobs queue.
                   1946:  *-----------------------------------------------------------------------
                   1947:  */
                   1948: void
1.56      espie    1949: Job_CatchChildren(bool block)  /* true if should block on the wait. */
1.1       deraadt  1950: {
1.66      espie    1951:        pid_t pid;              /* pid of dead child */
                   1952:        Job *job;               /* job descriptor for dead child */
                   1953:        LstNode jnode;          /* list element for finding job */
                   1954:        int status;             /* Exit/termination status */
1.1       deraadt  1955:
1.66      espie    1956:        /*
                   1957:         * Don't even bother if we know there's no one around.
                   1958:         */
                   1959:        if (nLocal == 0) {
                   1960:                return;
1.2       deraadt  1961:        }
1.6       millert  1962:
1.66      espie    1963:        while ((pid = waitpid((pid_t) -1, &status,
                   1964:            (block?0:WNOHANG)|WUNTRACED)) > 0) {
                   1965:                HandleSigs();
                   1966:                if (DEBUG(JOB)) {
1.68      espie    1967:                        (void)fprintf(stdout,
1.66      espie    1968:                            "Process %ld exited or stopped.\n", (long)pid);
                   1969:                        (void)fflush(stdout);
                   1970:                }
                   1971:
1.1       deraadt  1972:
1.66      espie    1973:                jnode = Lst_Find(&jobs, JobCmpPid, &pid);
1.1       deraadt  1974:
1.18      espie    1975:                if (jnode == NULL) {
1.68      espie    1976:                        if (WIFSIGNALED(status) &&
1.66      espie    1977:                            (WTERMSIG(status) == SIGCONT)) {
                   1978:                                jnode = Lst_Find(&stoppedJobs, JobCmpPid, &pid);
                   1979:                                if (jnode == NULL) {
                   1980:                                        Error("Resumed child (%ld) not in table", (long)pid);
                   1981:                                        continue;
                   1982:                                }
                   1983:                                job = (Job *)Lst_Datum(jnode);
                   1984:                                Lst_Remove(&stoppedJobs, jnode);
                   1985:                        } else {
                   1986:                                Error("Child (%ld) not in table?", (long)pid);
                   1987:                                continue;
                   1988:                        }
                   1989:                } else {
                   1990:                        job = (Job *)Lst_Datum(jnode);
                   1991:                        Lst_Remove(&jobs, jnode);
1.67      espie    1992:                        nJobs--;
1.66      espie    1993:                        if (jobFull && DEBUG(JOB)) {
1.68      espie    1994:                                (void)fprintf(stdout,
1.66      espie    1995:                                    "Job queue is no longer full.\n");
                   1996:                                (void)fflush(stdout);
                   1997:                        }
                   1998:                        jobFull = false;
1.67      espie    1999:                        nLocal--;
1.1       deraadt  2000:                }
1.66      espie    2001:
                   2002:                JobFinish(job, &status);
1.1       deraadt  2003:        }
                   2004: }
                   2005:
                   2006: /*-
                   2007:  *-----------------------------------------------------------------------
                   2008:  * Job_CatchOutput --
                   2009:  *     Catch the output from our children, if we're using
                   2010:  *     pipes do so. Otherwise just block time until we get a
1.6       millert  2011:  *     signal (most likely a SIGCHLD) since there's no point in
1.1       deraadt  2012:  *     just spinning when there's nothing to do and the reaping
1.6       millert  2013:  *     of a child can wait for a while.
1.1       deraadt  2014:  *
                   2015:  * Side Effects:
                   2016:  *     Output is read from pipes if we're piping.
                   2017:  * -----------------------------------------------------------------------
                   2018:  */
                   2019: void
1.56      espie    2020: Job_CatchOutput(void)
1.1       deraadt  2021: {
1.66      espie    2022:        int nfds;
                   2023:        struct timeval timeout;
                   2024:        LstNode ln;
                   2025:        Job *job;
                   2026:
                   2027:        (void)fflush(stdout);
                   2028:        if (usePipes) {
                   2029:                int count = howmany(outputsn+1, NFDBITS) * sizeof(fd_mask);
                   2030:                fd_set *readfdsp = malloc(count);
                   2031:                if (readfdsp == NULL)
                   2032:                        return;
                   2033:
                   2034:                memcpy(readfdsp, outputsp, count);
                   2035:                timeout.tv_sec = SEL_SEC;
                   2036:                timeout.tv_usec = SEL_USEC;
                   2037:
                   2038:                if ((nfds = select(outputsn+1, readfdsp, (fd_set *) 0,
                   2039:                    (fd_set *) 0, &timeout)) <= 0) {
                   2040:                        HandleSigs();
                   2041:                        free(readfdsp);
                   2042:                        return;
                   2043:                } else {
                   2044:                        HandleSigs();
1.68      espie    2045:                        for (ln = Lst_First(&jobs); nfds && ln != NULL;
1.66      espie    2046:                            ln = Lst_Adv(ln)) {
                   2047:                                job = (Job *)Lst_Datum(ln);
                   2048:                                if (FD_ISSET(job->inPipe, readfdsp)) {
                   2049:                                        JobDoOutput(job, false);
1.67      espie    2050:                                        nfds--;
1.66      espie    2051:                                }
                   2052:                        }
1.1       deraadt  2053:                }
1.66      espie    2054:                free(readfdsp);
1.1       deraadt  2055:        }
                   2056: }
                   2057:
                   2058: /*-
                   2059:  *-----------------------------------------------------------------------
                   2060:  * Job_Make --
                   2061:  *     Start the creation of a target. Basically a front-end for
                   2062:  *     JobStart used by the Make module.
                   2063:  *
                   2064:  * Side Effects:
                   2065:  *     Another job is started.
                   2066:  *-----------------------------------------------------------------------
                   2067:  */
                   2068: void
1.56      espie    2069: Job_Make(GNode *gn)
1.1       deraadt  2070: {
1.66      espie    2071:        (void)JobStart(gn, 0, NULL);
1.1       deraadt  2072: }
                   2073:
                   2074: /*-
                   2075:  *-----------------------------------------------------------------------
                   2076:  * Job_Init --
                   2077:  *     Initialize the process module
                   2078:  *
                   2079:  * Side Effects:
                   2080:  *     lists and counters are initialized
                   2081:  *-----------------------------------------------------------------------
                   2082:  */
                   2083: void
1.56      espie    2084: Job_Init(int     maxproc,  /* the greatest number of jobs which may be
1.1       deraadt  2085:                             * running at one time */
1.56      espie    2086:     int          maxlocal) /* the greatest number of local jobs which may
1.1       deraadt  2087:                             * be running at once. */
                   2088: {
1.66      espie    2089:        GNode *begin;     /* node for commands to do at the very start */
                   2090:        int tfd;
                   2091:
                   2092:        (void)strlcpy(tfile, TMPPAT, sizeof(tfile));
                   2093:        if ((tfd = mkstemp(tfile)) == -1)
                   2094:                Punt("Cannot create temp file: %s", strerror(errno));
                   2095:        else
                   2096:                (void)close(tfd);
                   2097:
                   2098:        Static_Lst_Init(&jobs);
                   2099:        Static_Lst_Init(&stoppedJobs);
                   2100:        maxJobs =         maxproc;
                   2101:        maxLocal =        maxlocal;
                   2102:        nJobs =   0;
                   2103:        nLocal =          0;
                   2104:        jobFull =         false;
                   2105:
                   2106:        aborting =        0;
                   2107:        errors =          0;
1.40      espie    2108:
1.66      espie    2109:        lastNode =        NULL;
1.1       deraadt  2110:
1.66      espie    2111:        if (maxJobs == 1) {
                   2112:                /*
                   2113:                 * If only one job can run at a time, there's no need for a
                   2114:                 * banner, no is there?
                   2115:                 */
                   2116:                targFmt = "";
                   2117:        } else {
                   2118:                targFmt = TARG_FMT;
                   2119:        }
                   2120:
                   2121:        if (commandShell->exit == NULL) {
                   2122:                commandShell->exit = "";
                   2123:        }
                   2124:        if (commandShell->echo == NULL) {
                   2125:                commandShell->echo = "";
                   2126:        }
1.1       deraadt  2127:
                   2128:        /*
1.66      espie    2129:         * Catch the four signals that POSIX specifies if they aren't ignored.
                   2130:         * JobPassSig will take care of calling JobInterrupt if appropriate.
1.1       deraadt  2131:         */
1.66      espie    2132:        if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
                   2133:                (void)signal(SIGINT, SigHandler);
                   2134:        }
                   2135:        if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
                   2136:                (void)signal(SIGHUP, SigHandler);
                   2137:        }
                   2138:        if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
                   2139:                (void)signal(SIGQUIT, SigHandler);
                   2140:        }
                   2141:        if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
                   2142:                (void)signal(SIGTERM, SigHandler);
                   2143:        }
1.1       deraadt  2144:        /*
1.66      espie    2145:         * There are additional signals that need to be caught and passed if
                   2146:         * either the export system wants to be told directly of signals or if
                   2147:         * we're giving each job its own process group (since then it won't get
                   2148:         * signals from the terminal driver as we own the terminal)
1.1       deraadt  2149:         */
1.48      espie    2150: #if defined(USE_PGRP)
1.66      espie    2151:        if (signal(SIGTSTP, SIG_IGN) != SIG_IGN) {
                   2152:                (void)signal(SIGTSTP, SigHandler);
                   2153:        }
                   2154:        if (signal(SIGTTOU, SIG_IGN) != SIG_IGN) {
                   2155:                (void)signal(SIGTTOU, SigHandler);
                   2156:        }
                   2157:        if (signal(SIGTTIN, SIG_IGN) != SIG_IGN) {
                   2158:                (void)signal(SIGTTIN, SigHandler);
                   2159:        }
                   2160:        if (signal(SIGWINCH, SIG_IGN) != SIG_IGN) {
                   2161:                (void)signal(SIGWINCH, SigHandler);
                   2162:        }
1.1       deraadt  2163: #endif
1.6       millert  2164:
1.66      espie    2165:        begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
1.1       deraadt  2166:
1.66      espie    2167:        if (begin != NULL) {
                   2168:                JobStart(begin, JOB_SPECIAL, (Job *)0);
                   2169:                while (nJobs) {
                   2170:                        Job_CatchOutput();
                   2171:                        Job_CatchChildren(!usePipes);
                   2172:                }
1.1       deraadt  2173:        }
1.66      espie    2174:        postCommands = Targ_FindNode(".END", TARG_CREATE);
1.1       deraadt  2175: }
                   2176:
                   2177: /*-
                   2178:  *-----------------------------------------------------------------------
                   2179:  * Job_Full --
                   2180:  *     See if the job table is full. It is considered full if it is OR
                   2181:  *     if we are in the process of aborting OR if we have
                   2182:  *     reached/exceeded our local quota. This prevents any more jobs
                   2183:  *     from starting up.
                   2184:  *
                   2185:  * Results:
1.41      espie    2186:  *     true if the job table is full, false otherwise
1.1       deraadt  2187:  *-----------------------------------------------------------------------
                   2188:  */
1.41      espie    2189: bool
1.56      espie    2190: Job_Full(void)
1.1       deraadt  2191: {
1.66      espie    2192:        return aborting || jobFull;
1.1       deraadt  2193: }
                   2194:
                   2195: /*-
                   2196:  *-----------------------------------------------------------------------
                   2197:  * Job_Empty --
1.40      espie    2198:  *     See if the job table is empty.  Because the local concurrency may
1.1       deraadt  2199:  *     be set to 0, it is possible for the job table to become empty,
                   2200:  *     while the list of stoppedJobs remains non-empty. In such a case,
                   2201:  *     we want to restart as many jobs as we can.
                   2202:  *
                   2203:  * Results:
1.41      espie    2204:  *     true if it is. false if it ain't.
1.1       deraadt  2205:  * -----------------------------------------------------------------------
                   2206:  */
1.41      espie    2207: bool
1.56      espie    2208: Job_Empty(void)
1.1       deraadt  2209: {
1.66      espie    2210:        if (nJobs == 0) {
                   2211:                if (!Lst_IsEmpty(&stoppedJobs) && !aborting) {
                   2212:                        /*
                   2213:                         * The job table is obviously not full if it has no
                   2214:                         * jobs in it...Try and restart the stopped jobs.
                   2215:                         */
                   2216:                        jobFull = false;
                   2217:                        JobRestartJobs();
                   2218:                        return false;
                   2219:                } else {
                   2220:                        return true;
                   2221:                }
1.1       deraadt  2222:        } else {
1.66      espie    2223:                return false;
1.1       deraadt  2224:        }
                   2225: }
                   2226:
                   2227: /*-
                   2228:  *-----------------------------------------------------------------------
                   2229:  * JobInterrupt --
                   2230:  *     Handle the receipt of an interrupt.
                   2231:  *
                   2232:  * Side Effects:
                   2233:  *     All children are killed. Another job will be started if the
                   2234:  *     .INTERRUPT target was given.
                   2235:  *-----------------------------------------------------------------------
                   2236:  */
                   2237: static void
1.56      espie    2238: JobInterrupt(int runINTERRUPT, /* Non-zero if commands for the .INTERRUPT
1.1       deraadt  2239:                                 * target should be executed */
1.66      espie    2240:     int signo)                 /* signal received */
1.1       deraadt  2241: {
1.66      espie    2242:        LstNode ln;             /* element in job table */
                   2243:        Job  *job;              /* job descriptor in that element */
                   2244:        GNode *interrupt;       /* the node describing the .INTERRUPT target */
                   2245:
                   2246:        aborting = ABORT_INTERRUPT;
                   2247:
                   2248:        for (ln = Lst_First(&jobs); ln != NULL; ln = Lst_Adv(ln)) {
                   2249:                job = (Job *)Lst_Datum(ln);
                   2250:
                   2251:                if (!Targ_Precious(job->node)) {
                   2252:                        const char *file = job->node->path == NULL ?
                   2253:                            job->node->name : job->node->path;
                   2254:                        if (!noExecute && eunlink(file) != -1) {
                   2255:                                Error("*** %s removed", file);
                   2256:                        }
                   2257:                }
                   2258:                if (job->pid) {
                   2259:                        if (DEBUG(JOB)) {
                   2260:                                (void)fprintf(stdout,
                   2261:                                    "JobInterrupt passing signal to child %ld.\n",
                   2262:                                    (long)job->pid);
                   2263:                                (void)fflush(stdout);
                   2264:                        }
                   2265:                        KILL(job->pid, signo);
                   2266:                }
1.2       deraadt  2267:        }
1.1       deraadt  2268:
1.66      espie    2269:        if (runINTERRUPT && !touchFlag) {
                   2270:                interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
                   2271:                if (interrupt != NULL) {
                   2272:                        ignoreErrors = false;
                   2273:
                   2274:                        JobStart(interrupt, JOB_IGNDOTS, (Job *)0);
                   2275:                        while (nJobs) {
                   2276:                                Job_CatchOutput();
                   2277:                                Job_CatchChildren(!usePipes);
                   2278:                        }
                   2279:                }
1.1       deraadt  2280:        }
1.66      espie    2281:        (void)eunlink(tfile);
                   2282:        exit(signo);
1.1       deraadt  2283: }
                   2284:
                   2285: /*
                   2286:  *-----------------------------------------------------------------------
1.12      espie    2287:  * Job_Finish --
1.1       deraadt  2288:  *     Do final processing such as the running of the commands
1.6       millert  2289:  *     attached to the .END target.
1.1       deraadt  2290:  *
                   2291:  * Results:
                   2292:  *     Number of errors reported.
1.40      espie    2293:  *
                   2294:  * Side Effects:
                   2295:  *     The process' temporary file (tfile) is removed if it still
                   2296:  *     existed.
1.1       deraadt  2297:  *-----------------------------------------------------------------------
                   2298:  */
                   2299: int
1.56      espie    2300: Job_Finish(void)
1.1       deraadt  2301: {
1.66      espie    2302:        if (postCommands != NULL && !Lst_IsEmpty(&postCommands->commands)) {
                   2303:                if (errors) {
                   2304:                        Error("Errors reported so .END ignored");
                   2305:                } else {
                   2306:                        JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
1.1       deraadt  2307:
1.66      espie    2308:                        while (nJobs) {
                   2309:                                Job_CatchOutput();
                   2310:                                Job_CatchChildren(!usePipes);
                   2311:                        }
                   2312:                }
1.1       deraadt  2313:        }
1.66      espie    2314:        (void)eunlink(tfile);
                   2315:        return errors;
1.1       deraadt  2316: }
                   2317:
1.12      espie    2318: /*-
                   2319:  *-----------------------------------------------------------------------
                   2320:  * Job_End --
                   2321:  *     Cleanup any memory used by the jobs module
                   2322:  *
                   2323:  * Side Effects:
                   2324:  *     Memory is freed
                   2325:  *-----------------------------------------------------------------------
                   2326:  */
1.41      espie    2327: #ifdef CLEANUP
1.12      espie    2328: void
1.56      espie    2329: Job_End(void)
1.12      espie    2330: {
1.66      espie    2331:        efree(shellArgv);
1.41      espie    2332: }
1.13      espie    2333: #endif
1.40      espie    2334:
1.1       deraadt  2335: /*-
                   2336:  *-----------------------------------------------------------------------
                   2337:  * Job_Wait --
                   2338:  *     Waits for all running jobs to finish and returns. Sets 'aborting'
                   2339:  *     to ABORT_WAIT to prevent other jobs from starting.
                   2340:  *
                   2341:  * Side Effects:
                   2342:  *     Currently running jobs finish.
                   2343:  *
                   2344:  *-----------------------------------------------------------------------
                   2345:  */
                   2346: void
1.56      espie    2347: Job_Wait(void)
1.1       deraadt  2348: {
1.66      espie    2349:        aborting = ABORT_WAIT;
                   2350:        while (nJobs != 0) {
                   2351:                Job_CatchOutput();
                   2352:                Job_CatchChildren(!usePipes);
                   2353:        }
                   2354:        aborting = 0;
1.1       deraadt  2355: }
                   2356:
                   2357: /*-
                   2358:  *-----------------------------------------------------------------------
                   2359:  * Job_AbortAll --
                   2360:  *     Abort all currently running jobs without handling output or anything.
                   2361:  *     This function is to be called only in the event of a major
                   2362:  *     error. Most definitely NOT to be called from JobInterrupt.
                   2363:  *
                   2364:  * Side Effects:
                   2365:  *     All children are killed, not just the firstborn
                   2366:  *-----------------------------------------------------------------------
                   2367:  */
                   2368: void
1.56      espie    2369: Job_AbortAll(void)
1.1       deraadt  2370: {
1.66      espie    2371:        LstNode ln;     /* element in job table */
                   2372:        Job *job;       /* the job descriptor in that element */
                   2373:        int foo;
1.6       millert  2374:
1.66      espie    2375:        aborting = ABORT_ERROR;
1.6       millert  2376:
1.66      espie    2377:        if (nJobs) {
                   2378:                for (ln = Lst_First(&jobs); ln != NULL; ln = Lst_Adv(ln)) {
                   2379:                        job = (Job *)Lst_Datum(ln);
                   2380:
                   2381:                        /*
                   2382:                         * kill the child process with increasingly drastic
                   2383:                         * signals to make darn sure it's dead.
                   2384:                         */
                   2385:                        KILL(job->pid, SIGINT);
                   2386:                        KILL(job->pid, SIGKILL);
                   2387:                }
1.1       deraadt  2388:        }
1.6       millert  2389:
1.66      espie    2390:        /*
                   2391:         * Catch as many children as want to report in at first, then give up
                   2392:         */
                   2393:        while (waitpid(-1, &foo, WNOHANG) > 0)
                   2394:                continue;
                   2395:        (void)eunlink(tfile);
1.2       deraadt  2396: }
1.40      espie    2397:
1.2       deraadt  2398: /*-
                   2399:  *-----------------------------------------------------------------------
                   2400:  * JobRestartJobs --
                   2401:  *     Tries to restart stopped jobs if there are slots available.
                   2402:  *     Note that this tries to restart them regardless of pending errors.
                   2403:  *     It's not good to leave stopped jobs lying around!
                   2404:  *
                   2405:  * Side Effects:
                   2406:  *     Resumes(and possibly migrates) jobs.
                   2407:  *-----------------------------------------------------------------------
                   2408:  */
                   2409: static void
1.56      espie    2410: JobRestartJobs(void)
1.2       deraadt  2411: {
1.66      espie    2412:        Job *job;
1.19      espie    2413:
1.66      espie    2414:        while (!jobFull && (job = (Job *)Lst_DeQueue(&stoppedJobs)) != NULL) {
                   2415:                if (DEBUG(JOB)) {
                   2416:                        (void)fprintf(stdout,
                   2417:                            "Job queue is not full. Restarting a stopped job.\n");
                   2418:                        (void)fflush(stdout);
                   2419:                }
                   2420:                JobRestart(job);
1.2       deraadt  2421:        }
1.1       deraadt  2422: }