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