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