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