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