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

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