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