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