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