main.c revision 213494
1/*- 2 * Copyright (c) 1988, 1989, 1990, 1993 3 * The Regents of the University of California. All rights reserved. 4 * Copyright (c) 1989 by Berkeley Softworks 5 * All rights reserved. 6 * 7 * This code is derived from software contributed to Berkeley by 8 * Adam de Boor. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 3. All advertising materials mentioning features or use of this software 19 * must display the following acknowledgement: 20 * This product includes software developed by the University of 21 * California, Berkeley and its contributors. 22 * 4. Neither the name of the University nor the names of its contributors 23 * may be used to endorse or promote products derived from this software 24 * without specific prior written permission. 25 * 26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 36 * SUCH DAMAGE. 37 * 38 * @(#)main.c 8.3 (Berkeley) 3/19/94 39 */ 40 41#ifndef lint 42#if 0 43static char copyright[] = 44"@(#) Copyright (c) 1988, 1989, 1990, 1993\n\ 45 The Regents of the University of California. All rights reserved.\n"; 46#endif 47#endif /* not lint */ 48#include <sys/cdefs.h> 49__FBSDID("$FreeBSD: head/usr.bin/make/main.c 213494 2010-10-06 20:54:17Z imp $"); 50 51/* 52 * main.c 53 * The main file for this entire program. Exit routines etc 54 * reside here. 55 * 56 * Utility functions defined in this file: 57 * Main_ParseArgLine 58 * Takes a line of arguments, breaks them and 59 * treats them as if they were given when first 60 * invoked. Used by the parse module to implement 61 * the .MFLAGS target. 62 */ 63 64#include <sys/param.h> 65#include <sys/stat.h> 66#include <sys/time.h> 67#include <sys/queue.h> 68#include <sys/resource.h> 69#include <sys/utsname.h> 70#include <sys/wait.h> 71#include <err.h> 72#include <errno.h> 73#include <stdlib.h> 74#include <string.h> 75#include <unistd.h> 76 77#include "arch.h" 78#include "buf.h" 79#include "config.h" 80#include "dir.h" 81#include "globals.h" 82#include "GNode.h" 83#include "job.h" 84#include "make.h" 85#include "parse.h" 86#include "pathnames.h" 87#include "shell.h" 88#include "str.h" 89#include "suff.h" 90#include "targ.h" 91#include "util.h" 92#include "var.h" 93 94extern char **environ; /* XXX what header declares this variable? */ 95 96#define WANT_ENV_MKLVL 1 97#define MKLVL_MAXVAL 500 98#define MKLVL_ENVVAR "__MKLVL__" 99 100/* ordered list of makefiles to read */ 101static Lst makefiles = Lst_Initializer(makefiles); 102 103/* ordered list of source makefiles */ 104static Lst source_makefiles = Lst_Initializer(source_makefiles); 105 106/* list of variables to print */ 107static Lst variables = Lst_Initializer(variables); 108 109static Boolean expandVars; /* fully expand printed variables */ 110static Boolean noBuiltins; /* -r flag */ 111static Boolean forceJobs; /* -j argument given */ 112static char *curdir; /* startup directory */ 113static char *objdir; /* where we chdir'ed to */ 114static char **save_argv; /* saved argv */ 115static char *save_makeflags;/* saved MAKEFLAGS */ 116 117/* (-E) vars to override from env */ 118Lst envFirstVars = Lst_Initializer(envFirstVars); 119 120/* Targets to be made */ 121Lst create = Lst_Initializer(create); 122 123Boolean allPrecious; /* .PRECIOUS given on line by itself */ 124Boolean is_posix; /* .POSIX target seen */ 125Boolean mfAutoDeps; /* .MAKEFILEDEPS target seen */ 126Boolean remakingMakefiles; /* True if remaking makefiles is in progress */ 127Boolean beSilent; /* -s flag */ 128Boolean beVerbose; /* -v flag */ 129Boolean beQuiet; /* -Q flag */ 130Boolean compatMake; /* -B argument */ 131int debug; /* -d flag */ 132Boolean ignoreErrors; /* -i flag */ 133int jobLimit; /* -j argument */ 134int makeErrors; /* Number of targets not remade due to errors */ 135Boolean jobsRunning; /* TRUE if the jobs might be running */ 136Boolean keepgoing; /* -k flag */ 137Boolean noExecute; /* -n flag */ 138Boolean printGraphOnly; /* -p flag */ 139Boolean queryFlag; /* -q flag */ 140Boolean touchFlag; /* -t flag */ 141Boolean usePipes; /* !-P flag */ 142uint32_t warn_cmd; /* command line warning flags */ 143uint32_t warn_flags; /* actual warning flags */ 144uint32_t warn_nocmd; /* command line no-warning flags */ 145 146time_t now; /* Time at start of make */ 147struct GNode *DEFAULT; /* .DEFAULT node */ 148 149/** 150 * Exit with usage message. 151 */ 152static void 153usage(void) 154{ 155 fprintf(stderr, 156 "usage: make [-BPSXeiknpqrstv] [-C directory] [-D variable]\n" 157 "\t[-d flags] [-E variable] [-f makefile] [-I directory]\n" 158 "\t[-j max_jobs] [-m directory] [-V variable]\n" 159 "\t[variable=value] [target ...]\n"); 160 exit(2); 161} 162 163/** 164 * MFLAGS_append 165 * Append a flag with an optional argument to MAKEFLAGS and MFLAGS 166 */ 167static void 168MFLAGS_append(const char *flag, char *arg) 169{ 170 char *str; 171 172 Var_Append(".MAKEFLAGS", flag, VAR_GLOBAL); 173 if (arg != NULL) { 174 str = MAKEFLAGS_quote(arg); 175 Var_Append(".MAKEFLAGS", str, VAR_GLOBAL); 176 free(str); 177 } 178 179 Var_Append("MFLAGS", flag, VAR_GLOBAL); 180 if (arg != NULL) { 181 str = MAKEFLAGS_quote(arg); 182 Var_Append("MFLAGS", str, VAR_GLOBAL); 183 free(str); 184 } 185} 186 187/** 188 * Main_ParseWarn 189 * 190 * Handle argument to warning option. 191 */ 192int 193Main_ParseWarn(const char *arg, int iscmd) 194{ 195 int i, neg; 196 197 static const struct { 198 const char *option; 199 uint32_t flag; 200 } options[] = { 201 { "dirsyntax", WARN_DIRSYNTAX }, 202 { NULL, 0 } 203 }; 204 205 neg = 0; 206 if (arg[0] == 'n' && arg[1] == 'o') { 207 neg = 1; 208 arg += 2; 209 } 210 211 for (i = 0; options[i].option != NULL; i++) 212 if (strcmp(arg, options[i].option) == 0) 213 break; 214 215 if (options[i].option == NULL) 216 /* unknown option */ 217 return (-1); 218 219 if (iscmd) { 220 if (!neg) { 221 warn_cmd |= options[i].flag; 222 warn_nocmd &= ~options[i].flag; 223 warn_flags |= options[i].flag; 224 } else { 225 warn_nocmd |= options[i].flag; 226 warn_cmd &= ~options[i].flag; 227 warn_flags &= ~options[i].flag; 228 } 229 } else { 230 if (!neg) { 231 warn_flags |= (options[i].flag & ~warn_nocmd); 232 } else { 233 warn_flags &= ~(options[i].flag | warn_cmd); 234 } 235 } 236 return (0); 237} 238 239/** 240 * Open and parse the given makefile. 241 * 242 * Results: 243 * TRUE if ok. FALSE if couldn't open file. 244 */ 245static Boolean 246ReadMakefile(const char p[]) 247{ 248 char *fname, *fnamesave; /* makefile to read */ 249 FILE *stream; 250 char *name, path[MAXPATHLEN]; 251 char *MAKEFILE; 252 int setMAKEFILE; 253 254 /* XXX - remove this once constification is done */ 255 fnamesave = fname = estrdup(p); 256 257 if (!strcmp(fname, "-")) { 258 Parse_File("(stdin)", stdin); 259 Var_SetGlobal("MAKEFILE", ""); 260 } else { 261 setMAKEFILE = strcmp(fname, ".depend"); 262 263 /* if we've chdir'd, rebuild the path name */ 264 if (curdir != objdir && *fname != '/') { 265 snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname); 266 /* 267 * XXX The realpath stuff breaks relative includes 268 * XXX in some cases. The problem likely is in 269 * XXX parse.c where it does special things in 270 * XXX ParseDoInclude if the file is relateive 271 * XXX or absolute and not a system file. There 272 * XXX it assumes that if the current file that's 273 * XXX being included is absolute, that any files 274 * XXX that it includes shouldn't do the -I path 275 * XXX stuff, which is inconsistant with historical 276 * XXX behavior. However, I can't pentrate the mists 277 * XXX further, so I'm putting this workaround in 278 * XXX here until such time as the underlying bug 279 * XXX can be fixed. 280 */ 281#if THIS_BREAKS_THINGS 282 if (realpath(path, path) != NULL && 283 (stream = fopen(path, "r")) != NULL) { 284 MAKEFILE = fname; 285 fname = path; 286 goto found; 287 } 288 } else if (realpath(fname, path) != NULL) { 289 MAKEFILE = fname; 290 fname = path; 291 if ((stream = fopen(fname, "r")) != NULL) 292 goto found; 293 } 294#else 295 if ((stream = fopen(path, "r")) != NULL) { 296 MAKEFILE = fname; 297 fname = path; 298 goto found; 299 } 300 } else { 301 MAKEFILE = fname; 302 if ((stream = fopen(fname, "r")) != NULL) 303 goto found; 304 } 305#endif 306 /* look in -I and system include directories. */ 307 name = Path_FindFile(fname, &parseIncPath); 308 if (!name) 309 name = Path_FindFile(fname, &sysIncPath); 310 if (!name || !(stream = fopen(name, "r"))) { 311 free(fnamesave); 312 return (FALSE); 313 } 314 MAKEFILE = fname = name; 315 /* 316 * set the MAKEFILE variable desired by System V fans -- the 317 * placement of the setting here means it gets set to the last 318 * makefile specified, as it is set by SysV make. 319 */ 320found: 321 if (setMAKEFILE) 322 Var_SetGlobal("MAKEFILE", MAKEFILE); 323 Parse_File(fname, stream); 324 } 325 free(fnamesave); 326 return (TRUE); 327} 328 329/** 330 * Open and parse the given makefile. 331 * If open is successful add it to the list of makefiles. 332 * 333 * Results: 334 * TRUE if ok. FALSE if couldn't open file. 335 */ 336static Boolean 337TryReadMakefile(const char p[]) 338{ 339 char *data; 340 LstNode *last = Lst_Last(&source_makefiles); 341 342 if (!ReadMakefile(p)) 343 return (FALSE); 344 345 data = estrdup(p); 346 if (last == NULL) { 347 LstNode *first = Lst_First(&source_makefiles); 348 Lst_Insert(&source_makefiles, first, data); 349 } else 350 Lst_Append(&source_makefiles, last, estrdup(p)); 351 return (TRUE); 352} 353 354/** 355 * MainParseArgs 356 * Parse a given argument vector. Called from main() and from 357 * Main_ParseArgLine() when the .MAKEFLAGS target is used. 358 * 359 * XXX: Deal with command line overriding .MAKEFLAGS in makefile 360 * 361 * Side Effects: 362 * Various global and local flags will be set depending on the flags 363 * given 364 */ 365static void 366MainParseArgs(int argc, char **argv) 367{ 368 int c; 369 Boolean found_dd = FALSE; 370 char found_dir[MAXPATHLEN + 1]; /* for searching for sys.mk */ 371 372rearg: 373 optind = 1; /* since we're called more than once */ 374 optreset = 1; 375#define OPTFLAGS "ABC:D:d:E:ef:I:ij:km:nPpQqrSstV:vXx:" 376 for (;;) { 377 if ((optind < argc) && strcmp(argv[optind], "--") == 0) { 378 found_dd = TRUE; 379 } 380 if ((c = getopt(argc, argv, OPTFLAGS)) == -1) { 381 break; 382 } 383 switch(c) { 384 385 case 'A': 386 arch_fatal = FALSE; 387 MFLAGS_append("-A", NULL); 388 break; 389 case 'B': 390 compatMake = TRUE; 391 MFLAGS_append("-B", NULL); 392 unsetenv("MAKE_JOBS_FIFO"); 393 break; 394 case 'C': 395 if (chdir(optarg) == -1) 396 err(1, "chdir %s", optarg); 397 if (getcwd(curdir, MAXPATHLEN) == NULL) 398 err(2, NULL); 399 break; 400 case 'D': 401 Var_SetGlobal(optarg, "1"); 402 MFLAGS_append("-D", optarg); 403 break; 404 case 'd': { 405 char *modules = optarg; 406 407 for (; *modules; ++modules) 408 switch (*modules) { 409 case 'A': 410 debug = ~0; 411 break; 412 case 'a': 413 debug |= DEBUG_ARCH; 414 break; 415 case 'c': 416 debug |= DEBUG_COND; 417 break; 418 case 'd': 419 debug |= DEBUG_DIR; 420 break; 421 case 'f': 422 debug |= DEBUG_FOR; 423 break; 424 case 'g': 425 if (modules[1] == '1') { 426 debug |= DEBUG_GRAPH1; 427 ++modules; 428 } 429 else if (modules[1] == '2') { 430 debug |= DEBUG_GRAPH2; 431 ++modules; 432 } 433 break; 434 case 'j': 435 debug |= DEBUG_JOB; 436 break; 437 case 'l': 438 debug |= DEBUG_LOUD; 439 break; 440 case 'm': 441 debug |= DEBUG_MAKE; 442 break; 443 case 's': 444 debug |= DEBUG_SUFF; 445 break; 446 case 't': 447 debug |= DEBUG_TARG; 448 break; 449 case 'v': 450 debug |= DEBUG_VAR; 451 break; 452 default: 453 warnx("illegal argument to d option " 454 "-- %c", *modules); 455 usage(); 456 } 457 MFLAGS_append("-d", optarg); 458 break; 459 } 460 case 'E': 461 Lst_AtEnd(&envFirstVars, estrdup(optarg)); 462 MFLAGS_append("-E", optarg); 463 break; 464 case 'e': 465 checkEnvFirst = TRUE; 466 MFLAGS_append("-e", NULL); 467 break; 468 case 'f': 469 Lst_AtEnd(&makefiles, estrdup(optarg)); 470 break; 471 case 'I': 472 Parse_AddIncludeDir(optarg); 473 MFLAGS_append("-I", optarg); 474 break; 475 case 'i': 476 ignoreErrors = TRUE; 477 MFLAGS_append("-i", NULL); 478 break; 479 case 'j': { 480 char *endptr; 481 482 forceJobs = TRUE; 483 jobLimit = strtol(optarg, &endptr, 10); 484 if (jobLimit <= 0 || *endptr != '\0') { 485 warnx("illegal number, -j argument -- %s", 486 optarg); 487 usage(); 488 } 489 MFLAGS_append("-j", optarg); 490 break; 491 } 492 case 'k': 493 keepgoing = TRUE; 494 MFLAGS_append("-k", NULL); 495 break; 496 case 'm': 497 /* look for magic parent directory search string */ 498 if (strncmp(".../", optarg, 4) == 0) { 499 if (!Dir_FindHereOrAbove(curdir, optarg + 4, 500 found_dir, sizeof(found_dir))) 501 break; /* nothing doing */ 502 Path_AddDir(&sysIncPath, found_dir); 503 } else { 504 Path_AddDir(&sysIncPath, optarg); 505 } 506 MFLAGS_append("-m", optarg); 507 break; 508 case 'n': 509 noExecute = TRUE; 510 MFLAGS_append("-n", NULL); 511 break; 512 case 'P': 513 usePipes = FALSE; 514 MFLAGS_append("-P", NULL); 515 break; 516 case 'p': 517 printGraphOnly = TRUE; 518 debug |= DEBUG_GRAPH1; 519 break; 520 case 'Q': 521 beQuiet = TRUE; 522 beVerbose = FALSE; 523 MFLAGS_append("-Q", NULL); 524 break; 525 case 'q': 526 queryFlag = TRUE; 527 /* Kind of nonsensical, wot? */ 528 MFLAGS_append("-q", NULL); 529 break; 530 case 'r': 531 noBuiltins = TRUE; 532 MFLAGS_append("-r", NULL); 533 break; 534 case 'S': 535 keepgoing = FALSE; 536 MFLAGS_append("-S", NULL); 537 break; 538 case 's': 539 beSilent = TRUE; 540 MFLAGS_append("-s", NULL); 541 break; 542 case 't': 543 touchFlag = TRUE; 544 MFLAGS_append("-t", NULL); 545 break; 546 case 'V': 547 Lst_AtEnd(&variables, estrdup(optarg)); 548 MFLAGS_append("-V", optarg); 549 break; 550 case 'v': 551 beVerbose = TRUE; 552 beQuiet = FALSE; 553 MFLAGS_append("-v", NULL); 554 break; 555 case 'X': 556 expandVars = FALSE; 557 break; 558 case 'x': 559 if (Main_ParseWarn(optarg, 1) != -1) 560 MFLAGS_append("-x", optarg); 561 break; 562 563 default: 564 case '?': 565 usage(); 566 } 567 } 568 argv += optind; 569 argc -= optind; 570 571 oldVars = TRUE; 572 573 /* 574 * Parse the rest of the arguments. 575 * o Check for variable assignments and perform them if so. 576 * o Check for more flags and restart getopt if so. 577 * o Anything else is taken to be a target and added 578 * to the end of the "create" list. 579 */ 580 for (; *argv != NULL; ++argv, --argc) { 581 if (Parse_IsVar(*argv)) { 582 char *ptr = MAKEFLAGS_quote(*argv); 583 char *v = estrdup(*argv); 584 585 Var_Append(".MAKEFLAGS", ptr, VAR_GLOBAL); 586 Parse_DoVar(v, VAR_CMD); 587 free(ptr); 588 free(v); 589 590 } else if ((*argv)[0] == '-') { 591 if ((*argv)[1] == '\0') { 592 /* 593 * (*argv) is a single dash, so we 594 * just ignore it. 595 */ 596 } else if (found_dd) { 597 /* 598 * Double dash has been found, ignore 599 * any more options. But what do we do 600 * with it? For now treat it like a target. 601 */ 602 Lst_AtEnd(&create, estrdup(*argv)); 603 } else { 604 /* 605 * (*argv) is a -flag, so backup argv and 606 * argc. getopt() expects options to start 607 * in the 2nd position. 608 */ 609 argc++; 610 argv--; 611 goto rearg; 612 } 613 614 } else if ((*argv)[0] == '\0') { 615 Punt("illegal (null) argument."); 616 617 } else { 618 Lst_AtEnd(&create, estrdup(*argv)); 619 } 620 } 621} 622 623/** 624 * Main_ParseArgLine 625 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target 626 * is encountered and by main() when reading the .MAKEFLAGS envariable. 627 * Takes a line of arguments and breaks it into its 628 * component words and passes those words and the number of them to the 629 * MainParseArgs function. 630 * The line should have all its leading whitespace removed. 631 * 632 * Side Effects: 633 * Only those that come from the various arguments. 634 */ 635void 636Main_ParseArgLine(char *line, int mflags) 637{ 638 ArgArray aa; 639 640 if (line == NULL) 641 return; 642 for (; *line == ' '; ++line) 643 continue; 644 if (!*line) 645 return; 646 647 if (mflags) 648 MAKEFLAGS_break(&aa, line); 649 else 650 brk_string(&aa, line, TRUE); 651 652 MainParseArgs(aa.argc, aa.argv); 653 ArgArray_Done(&aa); 654} 655 656static char * 657chdir_verify_path(const char *path, char *obpath) 658{ 659 struct stat sb; 660 661 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) { 662 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) { 663 warn("warning: %s", path); 664 return (NULL); 665 } 666 return (obpath); 667 } 668 669 return (NULL); 670} 671 672/** 673 * In lieu of a good way to prevent every possible looping in make(1), stop 674 * there from being more than MKLVL_MAXVAL processes forked by make(1), to 675 * prevent a forkbomb from happening, in a dumb and mechanical way. 676 * 677 * Side Effects: 678 * Creates or modifies enviornment variable MKLVL_ENVVAR via setenv(). 679 */ 680static void 681check_make_level(void) 682{ 683#ifdef WANT_ENV_MKLVL 684 char *value = getenv(MKLVL_ENVVAR); 685 int level = (value == NULL) ? 0 : atoi(value); 686 687 if (level < 0) { 688 errx(2, "Invalid value for recursion level (%d).", level); 689 } else if (level > MKLVL_MAXVAL) { 690 errx(2, "Max recursion level (%d) exceeded.", MKLVL_MAXVAL); 691 } else { 692 char new_value[32]; 693 sprintf(new_value, "%d", level + 1); 694 setenv(MKLVL_ENVVAR, new_value, 1); 695 } 696#endif /* WANT_ENV_MKLVL */ 697} 698 699/** 700 * Main_AddSourceMakefile 701 * Add a file to the list of source makefiles 702 */ 703void 704Main_AddSourceMakefile(const char *name) 705{ 706 707 Lst_AtEnd(&source_makefiles, estrdup(name)); 708} 709 710/** 711 * Remake_Makefiles 712 * Remake all the makefiles 713 */ 714static void 715Remake_Makefiles(void) 716{ 717 Lst cleanup; 718 LstNode *ln; 719 int error_cnt = 0; 720 int remade_cnt = 0; 721 722 Compat_InstallSignalHandlers(); 723 if (curdir != objdir) { 724 if (chdir(curdir) < 0) 725 Fatal("Failed to change directory to %s.", curdir); 726 } 727 728 Lst_Init(&cleanup); 729 LST_FOREACH(ln, &source_makefiles) { 730 LstNode *ln2; 731 struct GNode *gn; 732 const char *name = Lst_Datum(ln); 733 Boolean saveTouchFlag = touchFlag; 734 Boolean saveQueryFlag = queryFlag; 735 Boolean saveNoExecute = noExecute; 736 int mtime; 737 738 /* 739 * Create node 740 */ 741 gn = Targ_FindNode(name, TARG_CREATE); 742 DEBUGF(MAKE, ("Checking %s...", gn->name)); 743 Suff_FindDeps(gn); 744 745 /* 746 * -t, -q and -n has no effect unless the makefile is 747 * specified as one of the targets explicitly in the 748 * command line 749 */ 750 LST_FOREACH(ln2, &create) { 751 if (!strcmp(gn->name, Lst_Datum(ln2))) { 752 /* found as a target */ 753 break; 754 } 755 } 756 if (ln2 == NULL) { 757 touchFlag = FALSE; 758 queryFlag = FALSE; 759 noExecute = FALSE; 760 } 761 762 /* 763 * Check and remake the makefile 764 */ 765 mtime = Dir_MTime(gn); 766 remakingMakefiles = TRUE; 767 Compat_Make(gn, gn); 768 remakingMakefiles = FALSE; 769 770 /* 771 * Restore -t, -q and -n behaviour 772 */ 773 touchFlag = saveTouchFlag; 774 queryFlag = saveQueryFlag; 775 noExecute = saveNoExecute; 776 777 /* 778 * Compat_Make will leave the 'made' field of gn 779 * in one of the following states: 780 * UPTODATE gn was already up-to-date 781 * MADE gn was recreated successfully 782 * ERROR An error occurred while gn was being created 783 * ABORTED gn was not remade because one of its inferiors 784 * could not be made due to errors. 785 */ 786 if (gn->made == MADE) { 787 if (mtime != Dir_MTime(gn)) { 788 DEBUGF(MAKE, 789 ("%s updated (%d -> %d).\n", 790 gn->name, mtime, gn->mtime)); 791 remade_cnt++; 792 } else { 793 DEBUGF(MAKE, 794 ("%s not updated: skipping restart.\n", 795 gn->name)); 796 } 797 } else if (gn->made == ERROR) 798 error_cnt++; 799 else if (gn->made == ABORTED) { 800 printf("`%s' not remade because of errors.\n", 801 gn->name); 802 error_cnt++; 803 } else if (gn->made == UPTODATE) { 804 Lst_EnQueue(&cleanup, gn); 805 } 806 } 807 808 if (error_cnt > 0) 809 Fatal("Failed to remake Makefiles."); 810 if (remade_cnt > 0) { 811 DEBUGF(MAKE, ("Restarting `%s'.\n", save_argv[0])); 812 813 /* 814 * Some of makefiles were remade -- restart from clean state 815 */ 816 if (save_makeflags != NULL) 817 setenv("MAKEFLAGS", save_makeflags, 1); 818 else 819 unsetenv("MAKEFLAGS"); 820 if (execvp(save_argv[0], save_argv) < 0) { 821 Fatal("Can't restart `%s': %s.", 822 save_argv[0], strerror(errno)); 823 } 824 } 825 826 while (!Lst_IsEmpty(&cleanup)) { 827 GNode *gn = Lst_DeQueue(&cleanup); 828 829 gn->unmade = 0; 830 gn->make = FALSE; 831 gn->made = UNMADE; 832 gn->childMade = FALSE; 833 gn->mtime = gn->cmtime = 0; 834 gn->cmtime_gn = NULL; 835 836 LST_FOREACH(ln, &gn->children) { 837 GNode *cgn = Lst_Datum(ln); 838 839 gn->unmade++; 840 Lst_EnQueue(&cleanup, cgn); 841 } 842 } 843 844 if (curdir != objdir) { 845 if (chdir(objdir) < 0) 846 Fatal("Failed to change directory to %s.", objdir); 847 } 848} 849 850/** 851 * main 852 * The main function, for obvious reasons. Initializes variables 853 * and a few modules, then parses the arguments give it in the 854 * environment and on the command line. Reads the system makefile 855 * followed by either Makefile, makefile or the file given by the 856 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the 857 * flags it has received by then uses either the Make or the Compat 858 * module to create the initial list of targets. 859 * 860 * Results: 861 * If -q was given, exits -1 if anything was out-of-date. Else it exits 862 * 0. 863 * 864 * Side Effects: 865 * The program exits when done. Targets are created. etc. etc. etc. 866 */ 867int 868main(int argc, char **argv) 869{ 870 const char *machine; 871 const char *machine_arch; 872 const char *machine_cpu; 873 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */ 874 const char *p; 875 const char *pathp; 876 const char *path; 877 char mdpath[MAXPATHLEN]; 878 char obpath[MAXPATHLEN]; 879 char cdpath[MAXPATHLEN]; 880 char found_dir[MAXPATHLEN + 1]; /* for searching for sys.mk */ 881 char *cp = NULL, *start; 882 883 save_argv = argv; 884 save_makeflags = getenv("MAKEFLAGS"); 885 if (save_makeflags != NULL) 886 save_makeflags = estrdup(save_makeflags); 887 888 /* 889 * Initialize file global variables. 890 */ 891 expandVars = TRUE; 892 noBuiltins = FALSE; /* Read the built-in rules */ 893 forceJobs = FALSE; /* No -j flag */ 894 curdir = cdpath; 895 896 /* 897 * Initialize program global variables. 898 */ 899 beSilent = FALSE; /* Print commands as executed */ 900 ignoreErrors = FALSE; /* Pay attention to non-zero returns */ 901 noExecute = FALSE; /* Execute all commands */ 902 printGraphOnly = FALSE; /* Don't stop after printing graph */ 903 keepgoing = FALSE; /* Stop on error */ 904 allPrecious = FALSE; /* Remove targets when interrupted */ 905 queryFlag = FALSE; /* This is not just a check-run */ 906 touchFlag = FALSE; /* Actually update targets */ 907 usePipes = TRUE; /* Catch child output in pipes */ 908 debug = 0; /* No debug verbosity, please. */ 909 jobsRunning = FALSE; 910 911 jobLimit = DEFMAXJOBS; 912 compatMake = FALSE; /* No compat mode */ 913 914 check_make_level(); 915 916#ifdef RLIMIT_NOFILE 917 /* 918 * get rid of resource limit on file descriptors 919 */ 920 { 921 struct rlimit rl; 922 if (getrlimit(RLIMIT_NOFILE, &rl) == -1) { 923 err(2, "getrlimit"); 924 } 925 rl.rlim_cur = rl.rlim_max; 926 if (setrlimit(RLIMIT_NOFILE, &rl) == -1) { 927 err(2, "setrlimit"); 928 } 929 } 930#endif 931 932 /* 933 * Get the name of this type of MACHINE from utsname 934 * so we can share an executable for similar machines. 935 * (i.e. m68k: amiga hp300, mac68k, sun3, ...) 936 * 937 * Note that both MACHINE and MACHINE_ARCH are decided at 938 * run-time. 939 */ 940 if ((machine = getenv("MACHINE")) == NULL) { 941 static struct utsname utsname; 942 943 if (uname(&utsname) == -1) 944 err(2, "uname"); 945 machine = utsname.machine; 946 } 947 948 if ((machine_arch = getenv("MACHINE_ARCH")) == NULL) { 949#ifdef MACHINE_ARCH 950 machine_arch = MACHINE_ARCH; 951#else 952 machine_arch = "unknown"; 953#endif 954 } 955 956 /* 957 * Set machine_cpu to the minumum supported CPU revision based 958 * on the target architecture, if not already set. 959 */ 960 if ((machine_cpu = getenv("MACHINE_CPU")) == NULL) { 961 if (!strcmp(machine_arch, "i386")) 962 machine_cpu = "i386"; 963 else 964 machine_cpu = "unknown"; 965 } 966 967 /* 968 * Initialize the parsing, directory and variable modules to prepare 969 * for the reading of inclusion paths and variable settings on the 970 * command line 971 */ 972 Proc_Init(); 973 974 Dir_Init(); /* Initialize directory structures so -I flags 975 * can be processed correctly */ 976 Var_Init(environ); /* As well as the lists of variables for 977 * parsing arguments */ 978 979 /* 980 * Initialize the Shell so that we have a shell for != assignments 981 * on the command line. 982 */ 983 Shell_Init(); 984 985 /* 986 * Initialize various variables. 987 * MAKE also gets this name, for compatibility 988 * .MAKEFLAGS gets set to the empty string just in case. 989 * MFLAGS also gets initialized empty, for compatibility. 990 */ 991 Var_SetGlobal("MAKE", argv[0]); 992 Var_SetGlobal(".MAKEFLAGS", ""); 993 Var_SetGlobal("MFLAGS", ""); 994 Var_SetGlobal("MACHINE", machine); 995 Var_SetGlobal("MACHINE_ARCH", machine_arch); 996 Var_SetGlobal("MACHINE_CPU", machine_cpu); 997#ifdef MAKE_VERSION 998 Var_SetGlobal("MAKE_VERSION", MAKE_VERSION); 999#endif 1000 Var_SetGlobal(".newline", "\n"); /* handy for :@ loops */ 1001 { 1002 char tmp[64]; 1003 1004 snprintf(tmp, sizeof(tmp), "%u", getpid()); 1005 Var_SetGlobal(".MAKE.PID", tmp); 1006 snprintf(tmp, sizeof(tmp), "%u", getppid()); 1007 Var_SetGlobal(".MAKE.PPID", tmp); 1008 } 1009 Job_SetPrefix(); 1010 1011 /* 1012 * Find where we are... 1013 */ 1014 if (getcwd(curdir, MAXPATHLEN) == NULL) 1015 err(2, NULL); 1016 1017 /* 1018 * First snag things out of the MAKEFLAGS environment 1019 * variable. Then parse the command line arguments. 1020 */ 1021 Main_ParseArgLine(getenv("MAKEFLAGS"), 1); 1022 1023 MainParseArgs(argc, argv); 1024 1025 /* 1026 * Verify that cwd is sane (after -C may have changed it). 1027 */ 1028 { 1029 struct stat sa; 1030 1031 if (stat(curdir, &sa) == -1) 1032 err(2, "%s", curdir); 1033 } 1034 1035 /* 1036 * The object directory location is determined using the 1037 * following order of preference: 1038 * 1039 * 1. MAKEOBJDIRPREFIX`cwd` 1040 * 2. MAKEOBJDIR 1041 * 3. PATH_OBJDIR.${MACHINE} 1042 * 4. PATH_OBJDIR 1043 * 5. PATH_OBJDIRPREFIX`cwd` 1044 * 1045 * If one of the first two fails, use the current directory. 1046 * If the remaining three all fail, use the current directory. 1047 * 1048 * Once things are initted, 1049 * have to add the original directory to the search path, 1050 * and modify the paths for the Makefiles apropriately. The 1051 * current directory is also placed as a variable for make scripts. 1052 */ 1053 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) { 1054 if (!(path = getenv("MAKEOBJDIR"))) { 1055 path = PATH_OBJDIR; 1056 pathp = PATH_OBJDIRPREFIX; 1057 snprintf(mdpath, MAXPATHLEN, "%s.%s", path, machine); 1058 if (!(objdir = chdir_verify_path(mdpath, obpath))) 1059 if (!(objdir=chdir_verify_path(path, obpath))) { 1060 snprintf(mdpath, MAXPATHLEN, 1061 "%s%s", pathp, curdir); 1062 if (!(objdir=chdir_verify_path(mdpath, 1063 obpath))) 1064 objdir = curdir; 1065 } 1066 } 1067 else if (!(objdir = chdir_verify_path(path, obpath))) 1068 objdir = curdir; 1069 } 1070 else { 1071 snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir); 1072 if (!(objdir = chdir_verify_path(mdpath, obpath))) 1073 objdir = curdir; 1074 } 1075 Dir_InitDot(); /* Initialize the "." directory */ 1076 if (objdir != curdir) 1077 Path_AddDir(&dirSearchPath, curdir); 1078 Var_SetGlobal(".ST_EXPORTVAR", "YES"); 1079 Var_SetGlobal(".CURDIR", curdir); 1080 Var_SetGlobal(".OBJDIR", objdir); 1081 1082 if (getenv("MAKE_JOBS_FIFO") != NULL) 1083 forceJobs = TRUE; 1084 /* 1085 * Be compatible if user did not specify -j and did not explicitly 1086 * turned compatibility on 1087 */ 1088 if (!compatMake && !forceJobs) 1089 compatMake = TRUE; 1090 1091 /* 1092 * Initialize target and suffix modules in preparation for 1093 * parsing the makefile(s) 1094 */ 1095 Targ_Init(); 1096 Suff_Init(); 1097 1098 DEFAULT = NULL; 1099 time(&now); 1100 1101 /* 1102 * Set up the .TARGETS variable to contain the list of targets to be 1103 * created. If none specified, make the variable empty -- the parser 1104 * will fill the thing in with the default or .MAIN target. 1105 */ 1106 if (Lst_IsEmpty(&create)) { 1107 Var_SetGlobal(".TARGETS", ""); 1108 } else { 1109 LstNode *ln; 1110 1111 for (ln = Lst_First(&create); ln != NULL; ln = Lst_Succ(ln)) { 1112 char *name = Lst_Datum(ln); 1113 1114 Var_Append(".TARGETS", name, VAR_GLOBAL); 1115 } 1116 } 1117 1118 1119 /* 1120 * If no user-supplied system path was given (through the -m option) 1121 * add the directories from the DEFSYSPATH (more than one may be given 1122 * as dir1:...:dirn) to the system include path. 1123 */ 1124 if (TAILQ_EMPTY(&sysIncPath)) { 1125 char defsyspath[] = PATH_DEFSYSPATH; 1126 char *syspath = getenv("MAKESYSPATH"); 1127 1128 /* 1129 * If no user-supplied system path was given (thru -m option) 1130 * add the directories from the DEFSYSPATH (more than one may 1131 * be given as dir1:...:dirn) to the system include path. 1132 */ 1133 if (syspath == NULL || *syspath == '\0') 1134 syspath = defsyspath; 1135 else 1136 syspath = estrdup(syspath); 1137 1138 for (start = syspath; *start != '\0'; start = cp) { 1139 for (cp = start; *cp != '\0' && *cp != ':'; cp++) 1140 continue; 1141 if (*cp == ':') { 1142 *cp++ = '\0'; 1143 } 1144 /* look for magic parent directory search string */ 1145 if (strncmp(".../", start, 4) == 0) { 1146 if (Dir_FindHereOrAbove(curdir, start + 4, 1147 found_dir, sizeof(found_dir))) { 1148 Path_AddDir(&sysIncPath, found_dir); 1149 } 1150 } else { 1151 Path_AddDir(&sysIncPath, start); 1152 } 1153 } 1154 if (syspath != defsyspath) 1155 free(syspath); 1156 } 1157 1158 /* 1159 * Read in the built-in rules first, followed by the specified 1160 * makefile, if it was (makefile != (char *) NULL), or the default 1161 * Makefile and makefile, in that order, if it wasn't. 1162 */ 1163 if (!noBuiltins) { 1164 /* Path of sys.mk */ 1165 Lst sysMkPath = Lst_Initializer(sysMkPath); 1166 LstNode *ln; 1167 char defsysmk[] = PATH_DEFSYSMK; 1168 1169 Path_Expand(defsysmk, &sysIncPath, &sysMkPath); 1170 if (Lst_IsEmpty(&sysMkPath)) 1171 Fatal("make: no system rules (%s).", PATH_DEFSYSMK); 1172 LST_FOREACH(ln, &sysMkPath) { 1173 if (!ReadMakefile(Lst_Datum(ln))) 1174 break; 1175 } 1176 if (ln != NULL) 1177 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln)); 1178 Lst_Destroy(&sysMkPath, free); 1179 } 1180 1181 if (!Lst_IsEmpty(&makefiles)) { 1182 LstNode *ln; 1183 1184 LST_FOREACH(ln, &makefiles) { 1185 if (!TryReadMakefile(Lst_Datum(ln))) 1186 break; 1187 } 1188 if (ln != NULL) 1189 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln)); 1190 } else if (!TryReadMakefile("BSDmakefile")) 1191 if (!TryReadMakefile("makefile")) 1192 TryReadMakefile("Makefile"); 1193 1194 ReadMakefile(".depend"); 1195 1196 /* Install all the flags into the MAKEFLAGS envariable. */ 1197 if (((p = Var_Value(".MAKEFLAGS", VAR_GLOBAL)) != NULL) && *p) 1198 setenv("MAKEFLAGS", p, 1); 1199 else 1200 setenv("MAKEFLAGS", "", 1); 1201 1202 /* 1203 * For compatibility, look at the directories in the VPATH variable 1204 * and add them to the search path, if the variable is defined. The 1205 * variable's value is in the same format as the PATH envariable, i.e. 1206 * <directory>:<directory>:<directory>... 1207 */ 1208 if (Var_Exists("VPATH", VAR_CMD)) { 1209 /* 1210 * GCC stores string constants in read-only memory, but 1211 * Var_Subst will want to write this thing, so store it 1212 * in an array 1213 */ 1214 static char VPATH[] = "${VPATH}"; 1215 Buffer *buf; 1216 char *vpath; 1217 char *ptr; 1218 char savec; 1219 1220 buf = Var_Subst(VPATH, VAR_CMD, FALSE); 1221 1222 vpath = Buf_Data(buf); 1223 do { 1224 /* skip to end of directory */ 1225 for (ptr = vpath; *ptr != ':' && *ptr != '\0'; ptr++) 1226 ; 1227 1228 /* Save terminator character so know when to stop */ 1229 savec = *ptr; 1230 *ptr = '\0'; 1231 1232 /* Add directory to search path */ 1233 Path_AddDir(&dirSearchPath, vpath); 1234 1235 vpath = ptr + 1; 1236 } while (savec != '\0'); 1237 1238 Buf_Destroy(buf, TRUE); 1239 } 1240 1241 /* 1242 * Now that all search paths have been read for suffixes et al, it's 1243 * time to add the default search path to their lists... 1244 */ 1245 Suff_DoPaths(); 1246 1247 /* print the initial graph, if the user requested it */ 1248 if (DEBUG(GRAPH1)) 1249 Targ_PrintGraph(1); 1250 1251 /* print the values of any variables requested by the user */ 1252 if (Lst_IsEmpty(&variables) && !printGraphOnly) { 1253 /* 1254 * Since the user has not requested that any variables 1255 * be printed, we can build targets. 1256 * 1257 * Have read the entire graph and need to make a list of targets 1258 * to create. If none was given on the command line, we consult 1259 * the parsing module to find the main target(s) to create. 1260 */ 1261 Lst targs = Lst_Initializer(targs); 1262 1263 if (!is_posix && mfAutoDeps) { 1264 /* 1265 * Check if any of the makefiles are out-of-date. 1266 */ 1267 Remake_Makefiles(); 1268 } 1269 1270 if (Lst_IsEmpty(&create)) 1271 Parse_MainName(&targs); 1272 else 1273 Targ_FindList(&targs, &create, TARG_CREATE); 1274 1275 if (compatMake) { 1276 /* 1277 * Compat_Init will take care of creating 1278 * all the targets as well as initializing 1279 * the module. 1280 */ 1281 Compat_Run(&targs); 1282 outOfDate = 0; 1283 } else { 1284 /* 1285 * Initialize job module before traversing 1286 * the graph, now that any .BEGIN and .END 1287 * targets have been read. This is done 1288 * only if the -q flag wasn't given (to 1289 * prevent the .BEGIN from being executed 1290 * should it exist). 1291 */ 1292 if (!queryFlag) { 1293 Job_Init(jobLimit); 1294 jobsRunning = TRUE; 1295 } 1296 1297 /* Traverse the graph, checking on all the targets */ 1298 outOfDate = Make_Run(&targs); 1299 } 1300 Lst_Destroy(&targs, NOFREE); 1301 1302 } else { 1303 Var_Print(&variables, expandVars); 1304 } 1305 1306 Lst_Destroy(&variables, free); 1307 Lst_Destroy(&makefiles, free); 1308 Lst_Destroy(&source_makefiles, free); 1309 Lst_Destroy(&create, free); 1310 1311 /* print the graph now it's been processed if the user requested it */ 1312 if (DEBUG(GRAPH2)) 1313 Targ_PrintGraph(2); 1314 1315 if (queryFlag) 1316 return (outOfDate); 1317 1318 if (makeErrors != 0) 1319 Finish(makeErrors); 1320 1321 return (0); 1322} 1323