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