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