1 /* $NetBSD: main.c,v 1.174 2009/09/09 17:09:49 sjg Exp $ */ 2 3 /* 4 * Copyright (c) 1988, 1989, 1990, 1993 5 * The Regents of the University of California. 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) 1989 by Berkeley Softworks 37 * All rights reserved. 38 * 39 * This code is derived from software contributed to Berkeley by 40 * Adam de Boor. 41 * 42 * Redistribution and use in source and binary forms, with or without 43 * modification, are permitted provided that the following conditions 44 * are met: 45 * 1. Redistributions of source code must retain the above copyright 46 * notice, this list of conditions and the following disclaimer. 47 * 2. Redistributions in binary form must reproduce the above copyright 48 * notice, this list of conditions and the following disclaimer in the 49 * documentation and/or other materials provided with the distribution. 50 * 3. All advertising materials mentioning features or use of this software 51 * must display the following acknowledgement: 52 * This product includes software developed by the University of 53 * California, Berkeley and its contributors. 54 * 4. Neither the name of the University nor the names of its contributors 55 * may be used to endorse or promote products derived from this software 56 * without specific prior written permission. 57 * 58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 68 * SUCH DAMAGE. 69 */ 70 71 #ifndef MAKE_NATIVE 72 static char rcsid[] = "$NetBSD: main.c,v 1.174 2009/09/09 17:09:49 sjg Exp $"; 73 #else 74 #include <sys/cdefs.h> 75 #ifndef lint 76 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993\ 77 The Regents of the University of California. All rights reserved."); 78 #endif /* not lint */ 79 80 #ifndef lint 81 #if 0 82 static char sccsid[] = "@(#)main.c 8.3 (Berkeley) 3/19/94"; 83 #else 84 __RCSID("$NetBSD: main.c,v 1.174 2009/09/09 17:09:49 sjg Exp $"); 85 #endif 86 #endif /* not lint */ 87 #endif 88 89 /*- 90 * main.c -- 91 * The main file for this entire program. Exit routines etc 92 * reside here. 93 * 94 * Utility functions defined in this file: 95 * Main_ParseArgLine Takes a line of arguments, breaks them and 96 * treats them as if they were given when first 97 * invoked. Used by the parse module to implement 98 * the .MFLAGS target. 99 * 100 * Error Print a tagged error message. The global 101 * MAKE variable must have been defined. This 102 * takes a format string and two optional 103 * arguments for it. 104 * 105 * Fatal Print an error message and exit. Also takes 106 * a format string and two arguments. 107 * 108 * Punt Aborts all jobs and exits with a message. Also 109 * takes a format string and two arguments. 110 * 111 * Finish Finish things up by printing the number of 112 * errors which occurred, as passed to it, and 113 * exiting. 114 */ 115 116 #include <sys/types.h> 117 #include <sys/time.h> 118 #include <sys/param.h> 119 #include <sys/resource.h> 120 #include <sys/signal.h> 121 #include <sys/stat.h> 122 #ifdef MAKE_NATIVE 123 #include <sys/utsname.h> 124 #endif 125 #include <sys/wait.h> 126 127 #include <errno.h> 128 #include <fcntl.h> 129 #include <stdarg.h> 130 #include <stdio.h> 131 #include <stdlib.h> 132 #include <time.h> 133 134 #include "make.h" 135 #include "hash.h" 136 #include "dir.h" 137 #include "job.h" 138 #include "pathnames.h" 139 #include "trace.h" 140 141 #ifdef USE_IOVEC 142 #include <sys/uio.h> 143 #endif 144 145 #ifndef DEFMAXLOCAL 146 #define DEFMAXLOCAL DEFMAXJOBS 147 #endif /* DEFMAXLOCAL */ 148 149 Lst create; /* Targets to be made */ 150 time_t now; /* Time at start of make */ 151 GNode *DEFAULT; /* .DEFAULT node */ 152 Boolean allPrecious; /* .PRECIOUS given on line by itself */ 153 154 static Boolean noBuiltins; /* -r flag */ 155 static Lst makefiles; /* ordered list of makefiles to read */ 156 static Boolean printVars; /* print value of one or more vars */ 157 static Lst variables; /* list of variables to print */ 158 int maxJobs; /* -j argument */ 159 static int maxJobTokens; /* -j argument */ 160 Boolean compatMake; /* -B argument */ 161 int debug; /* -d argument */ 162 Boolean noExecute; /* -n flag */ 163 Boolean noRecursiveExecute; /* -N flag */ 164 Boolean keepgoing; /* -k flag */ 165 Boolean queryFlag; /* -q flag */ 166 Boolean touchFlag; /* -t flag */ 167 Boolean ignoreErrors; /* -i flag */ 168 Boolean beSilent; /* -s flag */ 169 Boolean oldVars; /* variable substitution style */ 170 Boolean checkEnvFirst; /* -e flag */ 171 Boolean parseWarnFatal; /* -W flag */ 172 Boolean jobServer; /* -J flag */ 173 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */ 174 Boolean varNoExportEnv; /* -X flag */ 175 Boolean doing_depend; /* Set while reading .depend */ 176 static Boolean jobsRunning; /* TRUE if the jobs might be running */ 177 static const char * tracefile; 178 static char * Check_Cwd_av(int, char **, int); 179 static void MainParseArgs(int, char **); 180 static int ReadMakefile(const void *, const void *); 181 static void usage(void); 182 183 static Boolean ignorePWD; /* if we use -C, PWD is meaningless */ 184 static char curdir[MAXPATHLEN + 1]; /* startup directory */ 185 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */ 186 char *progname; /* the program name */ 187 188 Boolean forceJobs = FALSE; 189 190 extern Lst parseIncPath; 191 192 static void 193 parse_debug_options(const char *argvalue) 194 { 195 const char *modules; 196 const char *mode; 197 char *fname; 198 int len; 199 200 for (modules = argvalue; *modules; ++modules) { 201 switch (*modules) { 202 case 'A': 203 debug = ~0; 204 break; 205 case 'a': 206 debug |= DEBUG_ARCH; 207 break; 208 case 'C': 209 debug |= DEBUG_CWD; 210 break; 211 case 'c': 212 debug |= DEBUG_COND; 213 break; 214 case 'd': 215 debug |= DEBUG_DIR; 216 break; 217 case 'e': 218 debug |= DEBUG_ERROR; 219 break; 220 case 'f': 221 debug |= DEBUG_FOR; 222 break; 223 case 'g': 224 if (modules[1] == '1') { 225 debug |= DEBUG_GRAPH1; 226 ++modules; 227 } 228 else if (modules[1] == '2') { 229 debug |= DEBUG_GRAPH2; 230 ++modules; 231 } 232 else if (modules[1] == '3') { 233 debug |= DEBUG_GRAPH3; 234 ++modules; 235 } 236 break; 237 case 'j': 238 debug |= DEBUG_JOB; 239 break; 240 case 'l': 241 debug |= DEBUG_LOUD; 242 break; 243 case 'm': 244 debug |= DEBUG_MAKE; 245 break; 246 case 'n': 247 debug |= DEBUG_SCRIPT; 248 break; 249 case 'p': 250 debug |= DEBUG_PARSE; 251 break; 252 case 's': 253 debug |= DEBUG_SUFF; 254 break; 255 case 't': 256 debug |= DEBUG_TARG; 257 break; 258 case 'v': 259 debug |= DEBUG_VAR; 260 break; 261 case 'x': 262 debug |= DEBUG_SHELL; 263 break; 264 case 'F': 265 if (debug_file != stdout && debug_file != stderr) 266 fclose(debug_file); 267 if (*++modules == '+') 268 mode = "a"; 269 else 270 mode = "w"; 271 if (strcmp(modules, "stdout") == 0) { 272 debug_file = stdout; 273 goto debug_setbuf; 274 } 275 if (strcmp(modules, "stderr") == 0) { 276 debug_file = stderr; 277 goto debug_setbuf; 278 } 279 len = strlen(modules); 280 fname = malloc(len + 20); 281 memcpy(fname, modules, len + 1); 282 /* Let the filename be modified by the pid */ 283 if (strcmp(fname + len - 3, ".%d") == 0) 284 snprintf(fname + len - 2, 20, "%d", getpid()); 285 debug_file = fopen(fname, mode); 286 if (!debug_file) { 287 fprintf(stderr, "Cannot open debug file %s\n", 288 fname); 289 usage(); 290 } 291 free(fname); 292 goto debug_setbuf; 293 default: 294 (void)fprintf(stderr, 295 "%s: illegal argument to d option -- %c\n", 296 progname, *modules); 297 usage(); 298 } 299 } 300 debug_setbuf: 301 /* 302 * Make the debug_file unbuffered, and make 303 * stdout line buffered (unless debugfile == stdout). 304 */ 305 setvbuf(debug_file, NULL, _IONBF, 0); 306 if (debug_file != stdout) { 307 setvbuf(stdout, NULL, _IOLBF, 0); 308 } 309 } 310 311 /*- 312 * MainParseArgs -- 313 * Parse a given argument vector. Called from main() and from 314 * Main_ParseArgLine() when the .MAKEFLAGS target is used. 315 * 316 * XXX: Deal with command line overriding .MAKEFLAGS in makefile 317 * 318 * Results: 319 * None 320 * 321 * Side Effects: 322 * Various global and local flags will be set depending on the flags 323 * given 324 */ 325 static void 326 MainParseArgs(int argc, char **argv) 327 { 328 char *p; 329 int c = '?'; 330 int arginc; 331 char *argvalue; 332 const char *getopt_def; 333 char *optscan; 334 Boolean inOption, dashDash = FALSE; 335 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */ 336 337 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrst" 338 /* Can't actually use getopt(3) because rescanning is not portable */ 339 340 getopt_def = OPTFLAGS; 341 rearg: 342 inOption = FALSE; 343 optscan = NULL; 344 while(argc > 1) { 345 char *getopt_spec; 346 if(!inOption) 347 optscan = argv[1]; 348 c = *optscan++; 349 arginc = 0; 350 if(inOption) { 351 if(c == '\0') { 352 ++argv; 353 --argc; 354 inOption = FALSE; 355 continue; 356 } 357 } else { 358 if (c != '-' || dashDash) 359 break; 360 inOption = TRUE; 361 c = *optscan++; 362 } 363 /* '-' found at some earlier point */ 364 getopt_spec = strchr(getopt_def, c); 365 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') { 366 /* -<something> found, and <something> should have an arg */ 367 inOption = FALSE; 368 arginc = 1; 369 argvalue = optscan; 370 if(*argvalue == '\0') { 371 if (argc < 3) 372 goto noarg; 373 argvalue = argv[2]; 374 arginc = 2; 375 } 376 } else { 377 argvalue = NULL; 378 } 379 switch(c) { 380 case '\0': 381 arginc = 1; 382 inOption = FALSE; 383 break; 384 case 'B': 385 compatMake = TRUE; 386 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL); 387 break; 388 case 'C': 389 if (chdir(argvalue) == -1) { 390 (void)fprintf(stderr, 391 "%s: chdir %s: %s\n", 392 progname, argvalue, 393 strerror(errno)); 394 exit(1); 395 } 396 ignorePWD = TRUE; 397 break; 398 case 'D': 399 if (argvalue == NULL || argvalue[0] == 0) goto noarg; 400 Var_Set(argvalue, "1", VAR_GLOBAL, 0); 401 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL); 402 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 403 break; 404 case 'I': 405 if (argvalue == NULL) goto noarg; 406 Parse_AddIncludeDir(argvalue); 407 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL); 408 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 409 break; 410 case 'J': 411 if (argvalue == NULL) goto noarg; 412 if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) { 413 (void)fprintf(stderr, 414 "%s: internal error -- J option malformed (%s)\n", 415 progname, argvalue); 416 usage(); 417 } 418 if ((fcntl(jp_0, F_GETFD, 0) < 0) || 419 (fcntl(jp_1, F_GETFD, 0) < 0)) { 420 #if 0 421 (void)fprintf(stderr, 422 "%s: ###### warning -- J descriptors were closed!\n", 423 progname); 424 exit(2); 425 #endif 426 jp_0 = -1; 427 jp_1 = -1; 428 compatMake = TRUE; 429 } else { 430 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL); 431 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 432 jobServer = TRUE; 433 } 434 break; 435 case 'N': 436 noExecute = TRUE; 437 noRecursiveExecute = TRUE; 438 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL); 439 break; 440 case 'S': 441 keepgoing = FALSE; 442 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL); 443 break; 444 case 'T': 445 if (argvalue == NULL) goto noarg; 446 tracefile = bmake_strdup(argvalue); 447 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL); 448 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 449 break; 450 case 'V': 451 if (argvalue == NULL) goto noarg; 452 printVars = TRUE; 453 (void)Lst_AtEnd(variables, argvalue); 454 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL); 455 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 456 break; 457 case 'W': 458 parseWarnFatal = TRUE; 459 break; 460 case 'X': 461 varNoExportEnv = TRUE; 462 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL); 463 break; 464 case 'd': 465 if (argvalue == NULL) goto noarg; 466 /* If '-d-opts' don't pass to children */ 467 if (argvalue[0] == '-') 468 argvalue++; 469 else { 470 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL); 471 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 472 } 473 parse_debug_options(argvalue); 474 break; 475 case 'e': 476 checkEnvFirst = TRUE; 477 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL); 478 break; 479 case 'f': 480 if (argvalue == NULL) goto noarg; 481 (void)Lst_AtEnd(makefiles, argvalue); 482 break; 483 case 'i': 484 ignoreErrors = TRUE; 485 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL); 486 break; 487 case 'j': 488 if (argvalue == NULL) goto noarg; 489 forceJobs = TRUE; 490 maxJobs = strtol(argvalue, &p, 0); 491 if (*p != '\0' || maxJobs < 1) { 492 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n", 493 progname); 494 exit(1); 495 } 496 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL); 497 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 498 maxJobTokens = maxJobs; 499 break; 500 case 'k': 501 keepgoing = TRUE; 502 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL); 503 break; 504 case 'm': 505 if (argvalue == NULL) goto noarg; 506 /* look for magic parent directory search string */ 507 if (strncmp(".../", argvalue, 4) == 0) { 508 if (!Dir_FindHereOrAbove(curdir, argvalue+4, 509 found_path, sizeof(found_path))) 510 break; /* nothing doing */ 511 (void)Dir_AddDir(sysIncPath, found_path); 512 513 } else { 514 (void)Dir_AddDir(sysIncPath, argvalue); 515 } 516 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL); 517 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 518 break; 519 case 'n': 520 noExecute = TRUE; 521 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL); 522 break; 523 case 'q': 524 queryFlag = TRUE; 525 /* Kind of nonsensical, wot? */ 526 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL); 527 break; 528 case 'r': 529 noBuiltins = TRUE; 530 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL); 531 break; 532 case 's': 533 beSilent = TRUE; 534 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL); 535 break; 536 case 't': 537 touchFlag = TRUE; 538 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL); 539 break; 540 case '-': 541 dashDash = TRUE; 542 break; 543 default: 544 case '?': 545 usage(); 546 } 547 argv += arginc; 548 argc -= arginc; 549 } 550 551 oldVars = TRUE; 552 553 /* 554 * See if the rest of the arguments are variable assignments and 555 * perform them if so. Else take them to be targets and stuff them 556 * on the end of the "create" list. 557 */ 558 for (; argc > 1; ++argv, --argc) 559 if (Parse_IsVar(argv[1])) { 560 Parse_DoVar(argv[1], VAR_CMD); 561 } else { 562 if (!*argv[1]) 563 Punt("illegal (null) argument."); 564 if (*argv[1] == '-' && !dashDash) 565 goto rearg; 566 (void)Lst_AtEnd(create, bmake_strdup(argv[1])); 567 } 568 569 return; 570 noarg: 571 (void)fprintf(stderr, "%s: option requires an argument -- %c\n", 572 progname, c); 573 usage(); 574 } 575 576 /*- 577 * Main_ParseArgLine -- 578 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target 579 * is encountered and by main() when reading the .MAKEFLAGS envariable. 580 * Takes a line of arguments and breaks it into its 581 * component words and passes those words and the number of them to the 582 * MainParseArgs function. 583 * The line should have all its leading whitespace removed. 584 * 585 * Input: 586 * line Line to fracture 587 * 588 * Results: 589 * None 590 * 591 * Side Effects: 592 * Only those that come from the various arguments. 593 */ 594 void 595 Main_ParseArgLine(const char *line) 596 { 597 char **argv; /* Manufactured argument vector */ 598 int argc; /* Number of arguments in argv */ 599 char *args; /* Space used by the args */ 600 char *buf, *p1; 601 char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1); 602 size_t len; 603 604 if (line == NULL) 605 return; 606 for (; *line == ' '; ++line) 607 continue; 608 if (!*line) 609 return; 610 611 buf = bmake_malloc(len = strlen(line) + strlen(argv0) + 2); 612 (void)snprintf(buf, len, "%s %s", argv0, line); 613 if (p1) 614 free(p1); 615 616 argv = brk_string(buf, &argc, TRUE, &args); 617 if (argv == NULL) { 618 Error("Unterminated quoted string [%s]", buf); 619 free(buf); 620 return; 621 } 622 free(buf); 623 MainParseArgs(argc, argv); 624 625 free(args); 626 free(argv); 627 } 628 629 Boolean 630 Main_SetObjdir(const char *path) 631 { 632 struct stat sb; 633 char *p = NULL; 634 char buf[MAXPATHLEN + 1]; 635 Boolean rc = FALSE; 636 637 /* expand variable substitutions */ 638 if (strchr(path, '$') != 0) { 639 snprintf(buf, MAXPATHLEN, "%s", path); 640 path = p = Var_Subst(NULL, buf, VAR_GLOBAL, 0); 641 } 642 643 if (path[0] != '/') { 644 snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path); 645 path = buf; 646 } 647 648 /* look for the directory and try to chdir there */ 649 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) { 650 if (chdir(path)) { 651 (void)fprintf(stderr, "make warning: %s: %s.\n", 652 path, strerror(errno)); 653 } else { 654 strncpy(objdir, path, MAXPATHLEN); 655 Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0); 656 setenv("PWD", objdir, 1); 657 Dir_InitDot(); 658 rc = TRUE; 659 } 660 } 661 662 if (p) 663 free(p); 664 return rc; 665 } 666 667 /*- 668 * ReadAllMakefiles -- 669 * wrapper around ReadMakefile() to read all. 670 * 671 * Results: 672 * TRUE if ok, FALSE on error 673 */ 674 static int 675 ReadAllMakefiles(const void *p, const void *q) 676 { 677 return (ReadMakefile(p, q) == 0); 678 } 679 680 #ifdef SIGINFO 681 /*ARGSUSED*/ 682 static void 683 siginfo(int signo) 684 { 685 char dir[MAXPATHLEN]; 686 char str[2 * MAXPATHLEN]; 687 int len; 688 if (getcwd(dir, sizeof(dir)) == NULL) 689 return; 690 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir); 691 if (len > 0) 692 (void)write(STDERR_FILENO, str, (size_t)len); 693 } 694 #endif 695 696 /*- 697 * main -- 698 * The main function, for obvious reasons. Initializes variables 699 * and a few modules, then parses the arguments give it in the 700 * environment and on the command line. Reads the system makefile 701 * followed by either Makefile, makefile or the file given by the 702 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the 703 * flags it has received by then uses either the Make or the Compat 704 * module to create the initial list of targets. 705 * 706 * Results: 707 * If -q was given, exits -1 if anything was out-of-date. Else it exits 708 * 0. 709 * 710 * Side Effects: 711 * The program exits when done. Targets are created. etc. etc. etc. 712 */ 713 int 714 main(int argc, char **argv) 715 { 716 Lst targs; /* target nodes to create -- passed to Make_Init */ 717 Boolean outOfDate = FALSE; /* FALSE if all targets up to date */ 718 struct stat sb, sa; 719 char *p1, *path, *pwd; 720 char mdpath[MAXPATHLEN]; 721 char *machine = getenv("MACHINE"); 722 const char *machine_arch = getenv("MACHINE_ARCH"); 723 char *syspath = getenv("MAKESYSPATH"); 724 Lst sysMkPath; /* Path of sys.mk */ 725 char *cp = NULL, *start; 726 /* avoid faults on read-only strings */ 727 static char defsyspath[] = _PATH_DEFSYSPATH; 728 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */ 729 struct timeval rightnow; /* to initialize random seed */ 730 #ifdef MAKE_NATIVE 731 struct utsname utsname; 732 #endif 733 734 /* default to writing debug to stderr */ 735 debug_file = stderr; 736 737 #ifdef SIGINFO 738 (void)signal(SIGINFO, siginfo); 739 #endif 740 /* 741 * Set the seed to produce a different random sequence 742 * on each program execution. 743 */ 744 gettimeofday(&rightnow, NULL); 745 srandom(rightnow.tv_sec + rightnow.tv_usec); 746 747 if ((progname = strrchr(argv[0], '/')) != NULL) 748 progname++; 749 else 750 progname = argv[0]; 751 #ifdef RLIMIT_NOFILE 752 /* 753 * get rid of resource limit on file descriptors 754 */ 755 { 756 struct rlimit rl; 757 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 && 758 rl.rlim_cur != rl.rlim_max) { 759 rl.rlim_cur = rl.rlim_max; 760 (void)setrlimit(RLIMIT_NOFILE, &rl); 761 } 762 } 763 #endif 764 765 /* 766 * Get the name of this type of MACHINE from utsname 767 * so we can share an executable for similar machines. 768 * (i.e. m68k: amiga hp300, mac68k, sun3, ...) 769 * 770 * Note that both MACHINE and MACHINE_ARCH are decided at 771 * run-time. 772 */ 773 if (!machine) { 774 #ifdef MAKE_NATIVE 775 if (uname(&utsname) == -1) { 776 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname, 777 strerror(errno)); 778 exit(2); 779 } 780 machine = utsname.machine; 781 #else 782 #ifdef MAKE_MACHINE 783 machine = MAKE_MACHINE; 784 #else 785 machine = "unknown"; 786 #endif 787 #endif 788 } 789 790 if (!machine_arch) { 791 #ifndef MACHINE_ARCH 792 #ifdef MAKE_MACHINE_ARCH 793 machine_arch = MAKE_MACHINE_ARCH; 794 #else 795 machine_arch = "unknown"; 796 #endif 797 #else 798 machine_arch = MACHINE_ARCH; 799 #endif 800 } 801 802 /* 803 * Just in case MAKEOBJDIR wants us to do something tricky. 804 */ 805 Var_Init(); /* Initialize the lists of variables for 806 * parsing arguments */ 807 Var_Set("MACHINE", machine, VAR_GLOBAL, 0); 808 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0); 809 #ifdef MAKE_VERSION 810 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0); 811 #endif 812 Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */ 813 814 create = Lst_Init(FALSE); 815 makefiles = Lst_Init(FALSE); 816 printVars = FALSE; 817 variables = Lst_Init(FALSE); 818 beSilent = FALSE; /* Print commands as executed */ 819 ignoreErrors = FALSE; /* Pay attention to non-zero returns */ 820 noExecute = FALSE; /* Execute all commands */ 821 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */ 822 keepgoing = FALSE; /* Stop on error */ 823 allPrecious = FALSE; /* Remove targets when interrupted */ 824 queryFlag = FALSE; /* This is not just a check-run */ 825 noBuiltins = FALSE; /* Read the built-in rules */ 826 touchFlag = FALSE; /* Actually update targets */ 827 debug = 0; /* No debug verbosity, please. */ 828 jobsRunning = FALSE; 829 830 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */ 831 maxJobTokens = maxJobs; 832 compatMake = FALSE; /* No compat mode */ 833 ignorePWD = FALSE; 834 835 /* 836 * Initialize the parsing, directory and variable modules to prepare 837 * for the reading of inclusion paths and variable settings on the 838 * command line 839 */ 840 841 /* 842 * Initialize various variables. 843 * MAKE also gets this name, for compatibility 844 * .MAKEFLAGS gets set to the empty string just in case. 845 * MFLAGS also gets initialized empty, for compatibility. 846 */ 847 Parse_Init(); 848 Var_Set("MAKE", argv[0], VAR_GLOBAL, 0); 849 Var_Set(".MAKE", argv[0], VAR_GLOBAL, 0); 850 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0); 851 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0); 852 Var_Set("MFLAGS", "", VAR_GLOBAL, 0); 853 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0); 854 855 /* 856 * Set some other useful macros 857 */ 858 { 859 char tmp[64]; 860 const char *ep; 861 862 if (!(ep = getenv(MAKE_LEVEL))) { 863 ep = "0"; 864 } 865 Var_Set(MAKE_LEVEL, ep, VAR_GLOBAL, 0); 866 snprintf(tmp, sizeof(tmp), "%u", getpid()); 867 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0); 868 snprintf(tmp, sizeof(tmp), "%u", getppid()); 869 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0); 870 } 871 Job_SetPrefix(); 872 873 /* 874 * First snag any flags out of the MAKE environment variable. 875 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's 876 * in a different format). 877 */ 878 #ifdef POSIX 879 Main_ParseArgLine(getenv("MAKEFLAGS")); 880 #else 881 Main_ParseArgLine(getenv("MAKE")); 882 #endif 883 884 MainParseArgs(argc, argv); 885 886 /* 887 * Find where we are (now) and take care of PWD for the automounter... 888 * All this code is so that we know where we are when we start up 889 * on a different machine with pmake. 890 */ 891 if (getcwd(curdir, MAXPATHLEN) == NULL) { 892 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno)); 893 exit(2); 894 } 895 896 if (stat(curdir, &sa) == -1) { 897 (void)fprintf(stderr, "%s: %s: %s.\n", 898 progname, curdir, strerror(errno)); 899 exit(2); 900 } 901 902 /* 903 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX 904 * since the value of curdir can vary depending on how we got 905 * here. Ie sitting at a shell prompt (shell that provides $PWD) 906 * or via subdir.mk in which case its likely a shell which does 907 * not provide it. 908 * So, to stop it breaking this case only, we ignore PWD if 909 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform. 910 */ 911 if (!ignorePWD && 912 (pwd = getenv("PWD")) != NULL && 913 getenv("MAKEOBJDIRPREFIX") == NULL) { 914 const char *makeobjdir = getenv("MAKEOBJDIR"); 915 916 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) { 917 if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino && 918 sa.st_dev == sb.st_dev) 919 (void)strncpy(curdir, pwd, MAXPATHLEN); 920 } 921 } 922 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0); 923 924 /* 925 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that, 926 * MAKEOBJDIR is set in the environment, try only that value 927 * and fall back to .CURDIR if it does not exist. 928 * 929 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and 930 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none 931 * of these paths exist, just use .CURDIR. 932 */ 933 Dir_Init(curdir); 934 (void)Main_SetObjdir(curdir); 935 936 if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) { 937 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir); 938 (void)Main_SetObjdir(mdpath); 939 } else if ((path = getenv("MAKEOBJDIR")) != NULL) { 940 (void)Main_SetObjdir(path); 941 } else { 942 (void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine); 943 if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) { 944 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", 945 _PATH_OBJDIRPREFIX, curdir); 946 (void)Main_SetObjdir(mdpath); 947 } 948 } 949 950 /* 951 * Be compatible if user did not specify -j and did not explicitly 952 * turned compatibility on 953 */ 954 if (!compatMake && !forceJobs) { 955 compatMake = TRUE; 956 } 957 958 /* 959 * Initialize archive, target and suffix modules in preparation for 960 * parsing the makefile(s) 961 */ 962 Arch_Init(); 963 Targ_Init(); 964 Suff_Init(); 965 Trace_Init(tracefile); 966 967 DEFAULT = NULL; 968 (void)time(&now); 969 970 Trace_Log(MAKESTART, NULL); 971 972 /* 973 * Set up the .TARGETS variable to contain the list of targets to be 974 * created. If none specified, make the variable empty -- the parser 975 * will fill the thing in with the default or .MAIN target. 976 */ 977 if (!Lst_IsEmpty(create)) { 978 LstNode ln; 979 980 for (ln = Lst_First(create); ln != NULL; 981 ln = Lst_Succ(ln)) { 982 char *name = (char *)Lst_Datum(ln); 983 984 Var_Append(".TARGETS", name, VAR_GLOBAL); 985 } 986 } else 987 Var_Set(".TARGETS", "", VAR_GLOBAL, 0); 988 989 990 /* 991 * If no user-supplied system path was given (through the -m option) 992 * add the directories from the DEFSYSPATH (more than one may be given 993 * as dir1:...:dirn) to the system include path. 994 */ 995 if (syspath == NULL || *syspath == '\0') 996 syspath = defsyspath; 997 else 998 syspath = bmake_strdup(syspath); 999 1000 for (start = syspath; *start != '\0'; start = cp) { 1001 for (cp = start; *cp != '\0' && *cp != ':'; cp++) 1002 continue; 1003 if (*cp == ':') { 1004 *cp++ = '\0'; 1005 } 1006 /* look for magic parent directory search string */ 1007 if (strncmp(".../", start, 4) != 0) { 1008 (void)Dir_AddDir(defIncPath, start); 1009 } else { 1010 if (Dir_FindHereOrAbove(curdir, start+4, 1011 found_path, sizeof(found_path))) { 1012 (void)Dir_AddDir(defIncPath, found_path); 1013 } 1014 } 1015 } 1016 if (syspath != defsyspath) 1017 free(syspath); 1018 1019 /* 1020 * Read in the built-in rules first, followed by the specified 1021 * makefile, if it was (makefile != NULL), or the default 1022 * makefile and Makefile, in that order, if it wasn't. 1023 */ 1024 if (!noBuiltins) { 1025 LstNode ln; 1026 1027 sysMkPath = Lst_Init(FALSE); 1028 Dir_Expand(_PATH_DEFSYSMK, 1029 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath, 1030 sysMkPath); 1031 if (Lst_IsEmpty(sysMkPath)) 1032 Fatal("%s: no system rules (%s).", progname, 1033 _PATH_DEFSYSMK); 1034 ln = Lst_Find(sysMkPath, NULL, ReadMakefile); 1035 if (ln == NULL) 1036 Fatal("%s: cannot open %s.", progname, 1037 (char *)Lst_Datum(ln)); 1038 } 1039 1040 if (!Lst_IsEmpty(makefiles)) { 1041 LstNode ln; 1042 1043 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles); 1044 if (ln != NULL) 1045 Fatal("%s: cannot open %s.", progname, 1046 (char *)Lst_Datum(ln)); 1047 } else if (ReadMakefile("makefile", NULL) != 0) 1048 (void)ReadMakefile("Makefile", NULL); 1049 1050 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */ 1051 if (!noBuiltins || !printVars) { 1052 doing_depend = TRUE; 1053 (void)ReadMakefile(".depend", NULL); 1054 doing_depend = FALSE; 1055 } 1056 1057 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL); 1058 if (p1) 1059 free(p1); 1060 1061 if (!compatMake) 1062 Job_ServerStart(maxJobTokens, jp_0, jp_1); 1063 if (DEBUG(JOB)) 1064 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n", 1065 jp_0, jp_1, maxJobs, maxJobTokens, compatMake); 1066 1067 Main_ExportMAKEFLAGS(TRUE); /* initial export */ 1068 1069 Check_Cwd_av(0, NULL, 0); /* initialize it */ 1070 1071 1072 /* 1073 * For compatibility, look at the directories in the VPATH variable 1074 * and add them to the search path, if the variable is defined. The 1075 * variable's value is in the same format as the PATH envariable, i.e. 1076 * <directory>:<directory>:<directory>... 1077 */ 1078 if (Var_Exists("VPATH", VAR_CMD)) { 1079 char *vpath, savec; 1080 /* 1081 * GCC stores string constants in read-only memory, but 1082 * Var_Subst will want to write this thing, so store it 1083 * in an array 1084 */ 1085 static char VPATH[] = "${VPATH}"; 1086 1087 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE); 1088 path = vpath; 1089 do { 1090 /* skip to end of directory */ 1091 for (cp = path; *cp != ':' && *cp != '\0'; cp++) 1092 continue; 1093 /* Save terminator character so know when to stop */ 1094 savec = *cp; 1095 *cp = '\0'; 1096 /* Add directory to search path */ 1097 (void)Dir_AddDir(dirSearchPath, path); 1098 *cp = savec; 1099 path = cp + 1; 1100 } while (savec == ':'); 1101 free(vpath); 1102 } 1103 1104 /* 1105 * Now that all search paths have been read for suffixes et al, it's 1106 * time to add the default search path to their lists... 1107 */ 1108 Suff_DoPaths(); 1109 1110 /* 1111 * Propagate attributes through :: dependency lists. 1112 */ 1113 Targ_Propagate(); 1114 1115 /* print the initial graph, if the user requested it */ 1116 if (DEBUG(GRAPH1)) 1117 Targ_PrintGraph(1); 1118 1119 /* print the values of any variables requested by the user */ 1120 if (printVars) { 1121 LstNode ln; 1122 1123 for (ln = Lst_First(variables); ln != NULL; 1124 ln = Lst_Succ(ln)) { 1125 char *var = (char *)Lst_Datum(ln); 1126 char *value; 1127 1128 if (strchr(var, '$')) { 1129 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0); 1130 } else { 1131 value = Var_Value(var, VAR_GLOBAL, &p1); 1132 } 1133 printf("%s\n", value ? value : ""); 1134 if (p1) 1135 free(p1); 1136 } 1137 } else { 1138 /* 1139 * Have now read the entire graph and need to make a list of 1140 * targets to create. If none was given on the command line, 1141 * we consult the parsing module to find the main target(s) 1142 * to create. 1143 */ 1144 if (Lst_IsEmpty(create)) 1145 targs = Parse_MainName(); 1146 else 1147 targs = Targ_FindList(create, TARG_CREATE); 1148 1149 if (!compatMake) { 1150 /* 1151 * Initialize job module before traversing the graph 1152 * now that any .BEGIN and .END targets have been read. 1153 * This is done only if the -q flag wasn't given 1154 * (to prevent the .BEGIN from being executed should 1155 * it exist). 1156 */ 1157 if (!queryFlag) { 1158 Job_Init(); 1159 jobsRunning = TRUE; 1160 } 1161 1162 /* Traverse the graph, checking on all the targets */ 1163 outOfDate = Make_Run(targs); 1164 } else { 1165 /* 1166 * Compat_Init will take care of creating all the 1167 * targets as well as initializing the module. 1168 */ 1169 Compat_Run(targs); 1170 } 1171 } 1172 1173 #ifdef CLEANUP 1174 Lst_Destroy(targs, NULL); 1175 Lst_Destroy(variables, NULL); 1176 Lst_Destroy(makefiles, NULL); 1177 Lst_Destroy(create, (FreeProc *)free); 1178 #endif 1179 1180 /* print the graph now it's been processed if the user requested it */ 1181 if (DEBUG(GRAPH2)) 1182 Targ_PrintGraph(2); 1183 1184 Trace_Log(MAKEEND, 0); 1185 1186 Suff_End(); 1187 Targ_End(); 1188 Arch_End(); 1189 Var_End(); 1190 Parse_End(); 1191 Dir_End(); 1192 Job_End(); 1193 Trace_End(); 1194 1195 return outOfDate ? 1 : 0; 1196 } 1197 1198 /*- 1199 * ReadMakefile -- 1200 * Open and parse the given makefile. 1201 * 1202 * Results: 1203 * 0 if ok. -1 if couldn't open file. 1204 * 1205 * Side Effects: 1206 * lots 1207 */ 1208 static int 1209 ReadMakefile(const void *p, const void *q __unused) 1210 { 1211 const char *fname = p; /* makefile to read */ 1212 int fd; 1213 size_t len = MAXPATHLEN; 1214 char *name, *path = bmake_malloc(len); 1215 int setMAKEFILE; 1216 1217 if (!strcmp(fname, "-")) { 1218 Parse_File("(stdin)", dup(fileno(stdin))); 1219 Var_Set("MAKEFILE", "", VAR_GLOBAL, 0); 1220 } else { 1221 setMAKEFILE = strcmp(fname, ".depend"); 1222 1223 /* if we've chdir'd, rebuild the path name */ 1224 if (strcmp(curdir, objdir) && *fname != '/') { 1225 size_t plen = strlen(curdir) + strlen(fname) + 2; 1226 if (len < plen) 1227 path = bmake_realloc(path, len = 2 * plen); 1228 1229 (void)snprintf(path, len, "%s/%s", curdir, fname); 1230 fd = open(path, O_RDONLY); 1231 if (fd != -1) { 1232 fname = path; 1233 goto found; 1234 } 1235 1236 /* If curdir failed, try objdir (ala .depend) */ 1237 plen = strlen(objdir) + strlen(fname) + 2; 1238 if (len < plen) 1239 path = bmake_realloc(path, len = 2 * plen); 1240 (void)snprintf(path, len, "%s/%s", objdir, fname); 1241 fd = open(path, O_RDONLY); 1242 if (fd != -1) { 1243 fname = path; 1244 goto found; 1245 } 1246 } else { 1247 fd = open(fname, O_RDONLY); 1248 if (fd != -1) 1249 goto found; 1250 } 1251 /* look in -I and system include directories. */ 1252 name = Dir_FindFile(fname, parseIncPath); 1253 if (!name) 1254 name = Dir_FindFile(fname, 1255 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath); 1256 if (!name || (fd = open(name, O_RDONLY)) == -1) { 1257 if (name) 1258 free(name); 1259 free(path); 1260 return(-1); 1261 } 1262 fname = name; 1263 /* 1264 * set the MAKEFILE variable desired by System V fans -- the 1265 * placement of the setting here means it gets set to the last 1266 * makefile specified, as it is set by SysV make. 1267 */ 1268 found: 1269 if (setMAKEFILE) 1270 Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0); 1271 Parse_File(fname, fd); 1272 } 1273 free(path); 1274 return(0); 1275 } 1276 1277 1278 /* 1279 * If MAKEOBJDIRPREFIX is in use, make ends up not in .CURDIR 1280 * in situations that would not arrise with ./obj (links or not). 1281 * This tends to break things like: 1282 * 1283 * build: 1284 * ${MAKE} includes 1285 * 1286 * This function spots when ${.MAKE:T} or ${.MAKE} is a command (as 1287 * opposed to an argument) in a command line and if so returns 1288 * ${.CURDIR} so caller can chdir() so that the assumptions made by 1289 * the Makefile hold true. 1290 * 1291 * If ${.MAKE} does not contain any '/', then ${.MAKE:T} is skipped. 1292 * 1293 * The chdir() only happens in the child process, and does nothing if 1294 * MAKEOBJDIRPREFIX and MAKEOBJDIR are not in the environment so it 1295 * should not break anything. Also if NOCHECKMAKECHDIR is set we 1296 * do nothing - to ensure historic semantics can be retained. 1297 */ 1298 static int Check_Cwd_Off = 0; 1299 1300 static char * 1301 Check_Cwd_av(int ac, char **av, int copy) 1302 { 1303 static char *make[4]; 1304 static char *cur_dir = NULL; 1305 char **mp; 1306 char *cp; 1307 int is_cmd, next_cmd; 1308 int i; 1309 int n; 1310 1311 if (Check_Cwd_Off) { 1312 if (DEBUG(CWD)) 1313 fprintf(debug_file, "check_cwd: check is off.\n"); 1314 return NULL; 1315 } 1316 1317 if (make[0] == NULL) { 1318 if (Var_Exists("NOCHECKMAKECHDIR", VAR_GLOBAL)) { 1319 Check_Cwd_Off = 1; 1320 if (DEBUG(CWD)) 1321 fprintf(debug_file, "check_cwd: turning check off.\n"); 1322 return NULL; 1323 } 1324 1325 make[1] = Var_Value(".MAKE", VAR_GLOBAL, &cp); 1326 if ((make[0] = strrchr(make[1], '/')) == NULL) { 1327 make[0] = make[1]; 1328 make[1] = NULL; 1329 } else 1330 ++make[0]; 1331 make[2] = NULL; 1332 cur_dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp); 1333 } 1334 if (ac == 0 || av == NULL) { 1335 if (DEBUG(CWD)) 1336 fprintf(debug_file, "check_cwd: empty command.\n"); 1337 return NULL; /* initialization only */ 1338 } 1339 1340 if (getenv("MAKEOBJDIR") == NULL && 1341 getenv("MAKEOBJDIRPREFIX") == NULL) { 1342 if (DEBUG(CWD)) 1343 fprintf(debug_file, "check_cwd: no obj dirs.\n"); 1344 return NULL; 1345 } 1346 1347 1348 next_cmd = 1; 1349 for (i = 0; i < ac; ++i) { 1350 is_cmd = next_cmd; 1351 1352 n = strlen(av[i]); 1353 cp = &(av[i])[n - 1]; 1354 if (strspn(av[i], "|&;") == (size_t)n) { 1355 next_cmd = 1; 1356 continue; 1357 } else if (*cp == ';' || *cp == '&' || *cp == '|' || *cp == ')') { 1358 next_cmd = 1; 1359 if (copy) { 1360 do { 1361 *cp-- = '\0'; 1362 } while (*cp == ';' || *cp == '&' || *cp == '|' || 1363 *cp == ')' || *cp == '}') ; 1364 } else { 1365 /* 1366 * XXX this should not happen. 1367 */ 1368 fprintf(stderr, "%s: WARNING: raw arg ends in shell meta '%s'\n", 1369 progname, av[i]); 1370 } 1371 } else 1372 next_cmd = 0; 1373 1374 cp = av[i]; 1375 if (*cp == ';' || *cp == '&' || *cp == '|') 1376 is_cmd = 1; 1377 1378 if (DEBUG(CWD)) 1379 fprintf(debug_file, "av[%d] == %s '%s'", 1380 i, (is_cmd) ? "cmd" : "arg", av[i]); 1381 if (is_cmd != 0) { 1382 if (*cp == '(' || *cp == '{' || 1383 *cp == ';' || *cp == '&' || *cp == '|') { 1384 do { 1385 ++cp; 1386 } while (*cp == '(' || *cp == '{' || 1387 *cp == ';' || *cp == '&' || *cp == '|'); 1388 if (*cp == '\0') { 1389 next_cmd = 1; 1390 continue; 1391 } 1392 } 1393 if (strcmp(cp, "cd") == 0 || strcmp(cp, "chdir") == 0) { 1394 if (DEBUG(CWD)) 1395 fprintf(debug_file, " == cd, done.\n"); 1396 return NULL; 1397 } 1398 for (mp = make; *mp != NULL; ++mp) { 1399 n = strlen(*mp); 1400 if (strcmp(cp, *mp) == 0) { 1401 if (DEBUG(CWD)) 1402 fprintf(debug_file, " %s == '%s', chdir(%s)\n", 1403 cp, *mp, cur_dir); 1404 return cur_dir; 1405 } 1406 } 1407 } 1408 if (DEBUG(CWD)) 1409 fprintf(debug_file, "\n"); 1410 } 1411 return NULL; 1412 } 1413 1414 char * 1415 Check_Cwd_Cmd(const char *cmd) 1416 { 1417 char *cp, *bp; 1418 char **av; 1419 int ac; 1420 1421 if (Check_Cwd_Off) 1422 return NULL; 1423 1424 if (cmd) { 1425 av = brk_string(cmd, &ac, TRUE, &bp); 1426 if (DEBUG(CWD)) 1427 fprintf(debug_file, "splitting: '%s' -> %d words\n", 1428 cmd, ac); 1429 } else { 1430 ac = 0; 1431 av = NULL; 1432 bp = NULL; 1433 } 1434 cp = Check_Cwd_av(ac, av, 1); 1435 if (bp) 1436 free(bp); 1437 if (av) 1438 free(av); 1439 return cp; 1440 } 1441 1442 void 1443 Check_Cwd(const char **argv) 1444 { 1445 char *cp; 1446 int ac; 1447 1448 if (Check_Cwd_Off) 1449 return; 1450 1451 for (ac = 0; argv[ac] != NULL; ++ac) 1452 /* NOTHING */; 1453 if (ac == 3 && *argv[1] == '-') { 1454 cp = Check_Cwd_Cmd(argv[2]); 1455 } else { 1456 cp = Check_Cwd_av(ac, UNCONST(argv), 0); 1457 } 1458 if (cp) { 1459 chdir(cp); 1460 } 1461 } 1462 1463 /*- 1464 * Cmd_Exec -- 1465 * Execute the command in cmd, and return the output of that command 1466 * in a string. 1467 * 1468 * Results: 1469 * A string containing the output of the command, or the empty string 1470 * If errnum is not NULL, it contains the reason for the command failure 1471 * 1472 * Side Effects: 1473 * The string must be freed by the caller. 1474 */ 1475 char * 1476 Cmd_Exec(const char *cmd, const char **errnum) 1477 { 1478 const char *args[4]; /* Args for invoking the shell */ 1479 int fds[2]; /* Pipe streams */ 1480 int cpid; /* Child PID */ 1481 int pid; /* PID from wait() */ 1482 char *res; /* result */ 1483 int status; /* command exit status */ 1484 Buffer buf; /* buffer to store the result */ 1485 char *cp; 1486 int cc; 1487 1488 1489 *errnum = NULL; 1490 1491 if (!shellName) 1492 Shell_Init(); 1493 /* 1494 * Set up arguments for shell 1495 */ 1496 args[0] = shellName; 1497 args[1] = "-c"; 1498 args[2] = cmd; 1499 args[3] = NULL; 1500 1501 /* 1502 * Open a pipe for fetching its output 1503 */ 1504 if (pipe(fds) == -1) { 1505 *errnum = "Couldn't create pipe for \"%s\""; 1506 goto bad; 1507 } 1508 1509 /* 1510 * Fork 1511 */ 1512 switch (cpid = vfork()) { 1513 case 0: 1514 /* 1515 * Close input side of pipe 1516 */ 1517 (void)close(fds[0]); 1518 1519 /* 1520 * Duplicate the output stream to the shell's output, then 1521 * shut the extra thing down. Note we don't fetch the error 1522 * stream...why not? Why? 1523 */ 1524 (void)dup2(fds[1], 1); 1525 (void)close(fds[1]); 1526 1527 Var_ExportVars(); 1528 1529 (void)execv(shellPath, UNCONST(args)); 1530 _exit(1); 1531 /*NOTREACHED*/ 1532 1533 case -1: 1534 *errnum = "Couldn't exec \"%s\""; 1535 goto bad; 1536 1537 default: 1538 /* 1539 * No need for the writing half 1540 */ 1541 (void)close(fds[1]); 1542 1543 Buf_Init(&buf, 0); 1544 1545 do { 1546 char result[BUFSIZ]; 1547 cc = read(fds[0], result, sizeof(result)); 1548 if (cc > 0) 1549 Buf_AddBytes(&buf, cc, result); 1550 } 1551 while (cc > 0 || (cc == -1 && errno == EINTR)); 1552 1553 /* 1554 * Close the input side of the pipe. 1555 */ 1556 (void)close(fds[0]); 1557 1558 /* 1559 * Wait for the process to exit. 1560 */ 1561 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) 1562 continue; 1563 1564 cc = Buf_Size(&buf); 1565 res = Buf_Destroy(&buf, FALSE); 1566 1567 if (cc == 0) 1568 *errnum = "Couldn't read shell's output for \"%s\""; 1569 1570 if (WIFSIGNALED(status)) 1571 *errnum = "\"%s\" exited on a signal"; 1572 else if (WEXITSTATUS(status) != 0) 1573 *errnum = "\"%s\" returned non-zero status"; 1574 1575 /* 1576 * Null-terminate the result, convert newlines to spaces and 1577 * install it in the variable. 1578 */ 1579 res[cc] = '\0'; 1580 cp = &res[cc]; 1581 1582 if (cc > 0 && *--cp == '\n') { 1583 /* 1584 * A final newline is just stripped 1585 */ 1586 *cp-- = '\0'; 1587 } 1588 while (cp >= res) { 1589 if (*cp == '\n') { 1590 *cp = ' '; 1591 } 1592 cp--; 1593 } 1594 break; 1595 } 1596 return res; 1597 bad: 1598 res = bmake_malloc(1); 1599 *res = '\0'; 1600 return res; 1601 } 1602 1603 /*- 1604 * Error -- 1605 * Print an error message given its format. 1606 * 1607 * Results: 1608 * None. 1609 * 1610 * Side Effects: 1611 * The message is printed. 1612 */ 1613 /* VARARGS */ 1614 void 1615 Error(const char *fmt, ...) 1616 { 1617 va_list ap; 1618 FILE *err_file; 1619 1620 err_file = debug_file; 1621 if (err_file == stdout) 1622 err_file = stderr; 1623 for (;;) { 1624 va_start(ap, fmt); 1625 fprintf(err_file, "%s: ", progname); 1626 (void)vfprintf(err_file, fmt, ap); 1627 va_end(ap); 1628 (void)fprintf(err_file, "\n"); 1629 (void)fflush(err_file); 1630 if (err_file == stderr) 1631 break; 1632 err_file = stderr; 1633 } 1634 } 1635 1636 /*- 1637 * Fatal -- 1638 * Produce a Fatal error message. If jobs are running, waits for them 1639 * to finish. 1640 * 1641 * Results: 1642 * None 1643 * 1644 * Side Effects: 1645 * The program exits 1646 */ 1647 /* VARARGS */ 1648 void 1649 Fatal(const char *fmt, ...) 1650 { 1651 va_list ap; 1652 1653 va_start(ap, fmt); 1654 if (jobsRunning) 1655 Job_Wait(); 1656 1657 (void)vfprintf(stderr, fmt, ap); 1658 va_end(ap); 1659 (void)fprintf(stderr, "\n"); 1660 (void)fflush(stderr); 1661 1662 PrintOnError(NULL); 1663 1664 if (DEBUG(GRAPH2) || DEBUG(GRAPH3)) 1665 Targ_PrintGraph(2); 1666 Trace_Log(MAKEERROR, 0); 1667 exit(2); /* Not 1 so -q can distinguish error */ 1668 } 1669 1670 /* 1671 * Punt -- 1672 * Major exception once jobs are being created. Kills all jobs, prints 1673 * a message and exits. 1674 * 1675 * Results: 1676 * None 1677 * 1678 * Side Effects: 1679 * All children are killed indiscriminately and the program Lib_Exits 1680 */ 1681 /* VARARGS */ 1682 void 1683 Punt(const char *fmt, ...) 1684 { 1685 va_list ap; 1686 1687 va_start(ap, fmt); 1688 (void)fprintf(stderr, "%s: ", progname); 1689 (void)vfprintf(stderr, fmt, ap); 1690 va_end(ap); 1691 (void)fprintf(stderr, "\n"); 1692 (void)fflush(stderr); 1693 1694 PrintOnError(NULL); 1695 1696 DieHorribly(); 1697 } 1698 1699 /*- 1700 * DieHorribly -- 1701 * Exit without giving a message. 1702 * 1703 * Results: 1704 * None 1705 * 1706 * Side Effects: 1707 * A big one... 1708 */ 1709 void 1710 DieHorribly(void) 1711 { 1712 if (jobsRunning) 1713 Job_AbortAll(); 1714 if (DEBUG(GRAPH2)) 1715 Targ_PrintGraph(2); 1716 Trace_Log(MAKEERROR, 0); 1717 exit(2); /* Not 1, so -q can distinguish error */ 1718 } 1719 1720 /* 1721 * Finish -- 1722 * Called when aborting due to errors in child shell to signal 1723 * abnormal exit. 1724 * 1725 * Results: 1726 * None 1727 * 1728 * Side Effects: 1729 * The program exits 1730 */ 1731 void 1732 Finish(int errors) 1733 /* number of errors encountered in Make_Make */ 1734 { 1735 Fatal("%d error%s", errors, errors == 1 ? "" : "s"); 1736 } 1737 1738 /* 1739 * enunlink -- 1740 * Remove a file carefully, avoiding directories. 1741 */ 1742 int 1743 eunlink(const char *file) 1744 { 1745 struct stat st; 1746 1747 if (lstat(file, &st) == -1) 1748 return -1; 1749 1750 if (S_ISDIR(st.st_mode)) { 1751 errno = EISDIR; 1752 return -1; 1753 } 1754 return unlink(file); 1755 } 1756 1757 /* 1758 * execError -- 1759 * Print why exec failed, avoiding stdio. 1760 */ 1761 void 1762 execError(const char *af, const char *av) 1763 { 1764 #ifdef USE_IOVEC 1765 int i = 0; 1766 struct iovec iov[8]; 1767 #define IOADD(s) \ 1768 (void)(iov[i].iov_base = UNCONST(s), \ 1769 iov[i].iov_len = strlen(iov[i].iov_base), \ 1770 i++) 1771 #else 1772 #define IOADD(void)write(2, s, strlen(s)) 1773 #endif 1774 1775 IOADD(progname); 1776 IOADD(": "); 1777 IOADD(af); 1778 IOADD("("); 1779 IOADD(av); 1780 IOADD(") failed ("); 1781 IOADD(strerror(errno)); 1782 IOADD(")\n"); 1783 1784 #ifdef USE_IOVEC 1785 (void)writev(2, iov, 8); 1786 #endif 1787 } 1788 1789 /* 1790 * usage -- 1791 * exit with usage message 1792 */ 1793 static void 1794 usage(void) 1795 { 1796 (void)fprintf(stderr, 1797 "usage: %s [-BeikNnqrstWX] \n\ 1798 [-C directory] [-D variable] [-d flags] [-f makefile]\n\ 1799 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\ 1800 [-V variable] [variable=value] [target ...]\n", progname); 1801 exit(2); 1802 } 1803 1804 1805 int 1806 PrintAddr(void *a, void *b) 1807 { 1808 printf("%lx ", (unsigned long) a); 1809 return b ? 0 : 0; 1810 } 1811 1812 1813 1814 void 1815 PrintOnError(const char *s) 1816 { 1817 char tmp[64]; 1818 char *cp; 1819 1820 if (s) 1821 printf("%s", s); 1822 1823 printf("\n%s: stopped in %s\n", progname, curdir); 1824 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}", 1825 sizeof(tmp) - 1); 1826 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0); 1827 if (cp) { 1828 if (*cp) 1829 printf("%s", cp); 1830 free(cp); 1831 } 1832 } 1833 1834 void 1835 Main_ExportMAKEFLAGS(Boolean first) 1836 { 1837 static int once = 1; 1838 char tmp[64]; 1839 char *s; 1840 1841 if (once != first) 1842 return; 1843 once = 0; 1844 1845 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}", 1846 sizeof(tmp)); 1847 s = Var_Subst(NULL, tmp, VAR_CMD, 0); 1848 if (s && *s) { 1849 #ifdef POSIX 1850 setenv("MAKEFLAGS", s, 1); 1851 #else 1852 setenv("MAKE", s, 1); 1853 #endif 1854 } 1855 } 1856