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

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