main.c revision 187995
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 187995 2009-02-02 02:05:58Z 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/sysctl.h> 67#include <sys/time.h> 68#include <sys/queue.h> 69#include <sys/resource.h> 70#include <sys/utsname.h> 71#include <sys/wait.h> 72#include <err.h> 73#include <errno.h> 74#include <stdlib.h> 75#include <string.h> 76#include <unistd.h> 77 78#include "arch.h" 79#include "buf.h" 80#include "config.h" 81#include "dir.h" 82#include "globals.h" 83#include "GNode.h" 84#include "job.h" 85#include "make.h" 86#include "parse.h" 87#include "pathnames.h" 88#include "shell.h" 89#include "str.h" 90#include "suff.h" 91#include "targ.h" 92#include "util.h" 93#include "var.h" 94 95extern char **environ; /* XXX what header declares this variable? */ 96 97#define WANT_ENV_MKLVL 1 98#define MKLVL_MAXVAL 500 99#define MKLVL_ENVVAR "__MKLVL__" 100 101/* ordered list of makefiles to read */ 102static Lst makefiles = Lst_Initializer(makefiles); 103 104/* ordered list of source makefiles */ 105static Lst source_makefiles = Lst_Initializer(source_makefiles); 106 107/* list of variables to print */ 108static Lst variables = Lst_Initializer(variables); 109 110static Boolean expandVars; /* fully expand printed variables */ 111static Boolean noBuiltins; /* -r flag */ 112static Boolean forceJobs; /* -j argument given */ 113static char *curdir; /* startup directory */ 114static char *objdir; /* where we chdir'ed to */ 115static char **save_argv; /* saved argv */ 116static char *save_makeflags;/* saved MAKEFLAGS */ 117 118/* (-E) vars to override from env */ 119Lst envFirstVars = Lst_Initializer(envFirstVars); 120 121/* Targets to be made */ 122Lst create = Lst_Initializer(create); 123 124Boolean allPrecious; /* .PRECIOUS given on line by itself */ 125Boolean is_posix; /* .POSIX target seen */ 126Boolean mfAutoDeps; /* .MAKEFILEDEPS target seen */ 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 371rearg: 372 optind = 1; /* since we're called more than once */ 373 optreset = 1; 374#define OPTFLAGS "ABC:D:E:I:PSV:Xd:ef:ij:km:nQpqrstvx:" 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 break; 398 case 'D': 399 Var_SetGlobal(optarg, "1"); 400 MFLAGS_append("-D", optarg); 401 break; 402 case 'd': { 403 char *modules = optarg; 404 405 for (; *modules; ++modules) 406 switch (*modules) { 407 case 'A': 408 debug = ~0; 409 break; 410 case 'a': 411 debug |= DEBUG_ARCH; 412 break; 413 case 'c': 414 debug |= DEBUG_COND; 415 break; 416 case 'd': 417 debug |= DEBUG_DIR; 418 break; 419 case 'f': 420 debug |= DEBUG_FOR; 421 break; 422 case 'g': 423 if (modules[1] == '1') { 424 debug |= DEBUG_GRAPH1; 425 ++modules; 426 } 427 else if (modules[1] == '2') { 428 debug |= DEBUG_GRAPH2; 429 ++modules; 430 } 431 break; 432 case 'j': 433 debug |= DEBUG_JOB; 434 break; 435 case 'l': 436 debug |= DEBUG_LOUD; 437 break; 438 case 'm': 439 debug |= DEBUG_MAKE; 440 break; 441 case 's': 442 debug |= DEBUG_SUFF; 443 break; 444 case 't': 445 debug |= DEBUG_TARG; 446 break; 447 case 'v': 448 debug |= DEBUG_VAR; 449 break; 450 default: 451 warnx("illegal argument to d option " 452 "-- %c", *modules); 453 usage(); 454 } 455 MFLAGS_append("-d", optarg); 456 break; 457 } 458 case 'E': 459 Lst_AtEnd(&envFirstVars, estrdup(optarg)); 460 MFLAGS_append("-E", optarg); 461 break; 462 case 'e': 463 checkEnvFirst = TRUE; 464 MFLAGS_append("-e", NULL); 465 break; 466 case 'f': 467 Lst_AtEnd(&makefiles, estrdup(optarg)); 468 break; 469 case 'I': 470 Parse_AddIncludeDir(optarg); 471 MFLAGS_append("-I", optarg); 472 break; 473 case 'i': 474 ignoreErrors = TRUE; 475 MFLAGS_append("-i", NULL); 476 break; 477 case 'j': { 478 char *endptr; 479 480 forceJobs = TRUE; 481 jobLimit = strtol(optarg, &endptr, 10); 482 if (jobLimit <= 0 || *endptr != '\0') { 483 warnx("illegal number, -j argument -- %s", 484 optarg); 485 usage(); 486 } 487 MFLAGS_append("-j", optarg); 488 break; 489 } 490 case 'k': 491 keepgoing = TRUE; 492 MFLAGS_append("-k", NULL); 493 break; 494 case 'm': 495 Path_AddDir(&sysIncPath, optarg); 496 MFLAGS_append("-m", optarg); 497 break; 498 case 'n': 499 noExecute = TRUE; 500 MFLAGS_append("-n", NULL); 501 break; 502 case 'P': 503 usePipes = FALSE; 504 MFLAGS_append("-P", NULL); 505 break; 506 case 'p': 507 printGraphOnly = TRUE; 508 debug |= DEBUG_GRAPH1; 509 break; 510 case 'Q': 511 beQuiet = TRUE; 512 beVerbose = FALSE; 513 MFLAGS_append("-Q", NULL); 514 break; 515 case 'q': 516 queryFlag = TRUE; 517 /* Kind of nonsensical, wot? */ 518 MFLAGS_append("-q", NULL); 519 break; 520 case 'r': 521 noBuiltins = TRUE; 522 MFLAGS_append("-r", NULL); 523 break; 524 case 'S': 525 keepgoing = FALSE; 526 MFLAGS_append("-S", NULL); 527 break; 528 case 's': 529 beSilent = TRUE; 530 MFLAGS_append("-s", NULL); 531 break; 532 case 't': 533 touchFlag = TRUE; 534 MFLAGS_append("-t", NULL); 535 break; 536 case 'V': 537 Lst_AtEnd(&variables, estrdup(optarg)); 538 MFLAGS_append("-V", optarg); 539 break; 540 case 'v': 541 beVerbose = TRUE; 542 beQuiet = FALSE; 543 MFLAGS_append("-v", NULL); 544 break; 545 case 'X': 546 expandVars = FALSE; 547 break; 548 case 'x': 549 if (Main_ParseWarn(optarg, 1) != -1) 550 MFLAGS_append("-x", optarg); 551 break; 552 553 default: 554 case '?': 555 usage(); 556 } 557 } 558 argv += optind; 559 argc -= optind; 560 561 oldVars = TRUE; 562 563 /* 564 * Parse the rest of the arguments. 565 * o Check for variable assignments and perform them if so. 566 * o Check for more flags and restart getopt if so. 567 * o Anything else is taken to be a target and added 568 * to the end of the "create" list. 569 */ 570 for (; *argv != NULL; ++argv, --argc) { 571 if (Parse_IsVar(*argv)) { 572 char *ptr = MAKEFLAGS_quote(*argv); 573 char *v = estrdup(*argv); 574 575 Var_Append(".MAKEFLAGS", ptr, VAR_GLOBAL); 576 Parse_DoVar(v, VAR_CMD); 577 free(ptr); 578 free(v); 579 580 } else if ((*argv)[0] == '-') { 581 if ((*argv)[1] == '\0') { 582 /* 583 * (*argv) is a single dash, so we 584 * just ignore it. 585 */ 586 } else if (found_dd) { 587 /* 588 * Double dash has been found, ignore 589 * any more options. But what do we do 590 * with it? For now treat it like a target. 591 */ 592 Lst_AtEnd(&create, estrdup(*argv)); 593 } else { 594 /* 595 * (*argv) is a -flag, so backup argv and 596 * argc. getopt() expects options to start 597 * in the 2nd position. 598 */ 599 argc++; 600 argv--; 601 goto rearg; 602 } 603 604 } else if ((*argv)[0] == '\0') { 605 Punt("illegal (null) argument."); 606 607 } else { 608 Lst_AtEnd(&create, estrdup(*argv)); 609 } 610 } 611} 612 613/** 614 * Main_ParseArgLine 615 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target 616 * is encountered and by main() when reading the .MAKEFLAGS envariable. 617 * Takes a line of arguments and breaks it into its 618 * component words and passes those words and the number of them to the 619 * MainParseArgs function. 620 * The line should have all its leading whitespace removed. 621 * 622 * Side Effects: 623 * Only those that come from the various arguments. 624 */ 625void 626Main_ParseArgLine(char *line, int mflags) 627{ 628 ArgArray aa; 629 630 if (line == NULL) 631 return; 632 for (; *line == ' '; ++line) 633 continue; 634 if (!*line) 635 return; 636 637 if (mflags) 638 MAKEFLAGS_break(&aa, line); 639 else 640 brk_string(&aa, line, TRUE); 641 642 MainParseArgs(aa.argc, aa.argv); 643 ArgArray_Done(&aa); 644} 645 646static char * 647chdir_verify_path(const char *path, char *obpath) 648{ 649 struct stat sb; 650 651 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) { 652 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) { 653 warn("warning: %s", path); 654 return (NULL); 655 } 656 return (obpath); 657 } 658 659 return (NULL); 660} 661 662/** 663 * In lieu of a good way to prevent every possible looping in make(1), stop 664 * there from being more than MKLVL_MAXVAL processes forked by make(1), to 665 * prevent a forkbomb from happening, in a dumb and mechanical way. 666 * 667 * Side Effects: 668 * Creates or modifies enviornment variable MKLVL_ENVVAR via setenv(). 669 */ 670static void 671check_make_level(void) 672{ 673#ifdef WANT_ENV_MKLVL 674 char *value = getenv(MKLVL_ENVVAR); 675 int level = (value == NULL) ? 0 : atoi(value); 676 677 if (level < 0) { 678 errc(2, EAGAIN, "Invalid value for recursion level (%d).", 679 level); 680 } else if (level > MKLVL_MAXVAL) { 681 errc(2, EAGAIN, "Max recursion level (%d) exceeded.", 682 MKLVL_MAXVAL); 683 } else { 684 char new_value[32]; 685 sprintf(new_value, "%d", level + 1); 686 setenv(MKLVL_ENVVAR, new_value, 1); 687 } 688#endif /* WANT_ENV_MKLVL */ 689} 690 691/** 692 * Main_AddSourceMakefile 693 * Add a file to the list of source makefiles 694 */ 695void 696Main_AddSourceMakefile(const char *name) 697{ 698 699 Lst_AtEnd(&source_makefiles, estrdup(name)); 700} 701 702/** 703 * Remake_Makefiles 704 * Remake all the makefiles 705 */ 706static void 707Remake_Makefiles(void) 708{ 709 LstNode *ln; 710 int error_cnt = 0; 711 int remade_cnt = 0; 712 713 Compat_InstallSignalHandlers(); 714 if (curdir != objdir) { 715 if (chdir(curdir) < 0) 716 Fatal("Failed to change directory to %s.", curdir); 717 } 718 719 LST_FOREACH(ln, &source_makefiles) { 720 LstNode *ln2; 721 struct GNode *gn; 722 const char *name = Lst_Datum(ln); 723 Boolean saveTouchFlag = touchFlag; 724 Boolean saveQueryFlag = queryFlag; 725 Boolean saveNoExecute = noExecute; 726 int mtime; 727 728 /* 729 * Create node 730 */ 731 gn = Targ_FindNode(name, TARG_CREATE); 732 DEBUGF(MAKE, ("Checking %s...", gn->name)); 733 Suff_FindDeps(gn); 734 735 /* 736 * ! dependencies as well as 737 * dependencies with .FORCE, .EXEC and .PHONY attributes 738 * are skipped to prevent infinite loops 739 */ 740 if (gn->type & (OP_FORCE | OP_EXEC | OP_PHONY)) { 741 DEBUGF(MAKE, ("skipping (force, exec or phony).\n", 742 gn->name)); 743 continue; 744 } 745 746 /* 747 * Skip :: targets that have commands and no children 748 * because such targets are always out-of-date 749 */ 750 if ((gn->type & OP_DOUBLEDEP) && 751 !Lst_IsEmpty(&gn->commands) && 752 Lst_IsEmpty(&gn->children)) { 753 DEBUGF(MAKE, ("skipping (doubledep, no sources " 754 "and has commands).\n")); 755 continue; 756 } 757 758 /* 759 * Skip targets without sources and without commands 760 */ 761 if (Lst_IsEmpty(&gn->commands) && 762 Lst_IsEmpty(&gn->children)) { 763 DEBUGF(MAKE, 764 ("skipping (no sources and no commands).\n")); 765 continue; 766 } 767 768 DEBUGF(MAKE, ("\n")); 769 770 /* 771 * -t, -q and -n has no effect unless the makefile is 772 * specified as one of the targets explicitly in the 773 * command line 774 */ 775 LST_FOREACH(ln2, &create) { 776 if (!strcmp(gn->name, Lst_Datum(ln2))) { 777 /* found as a target */ 778 break; 779 } 780 } 781 if (ln2 == NULL) { 782 touchFlag = FALSE; 783 queryFlag = FALSE; 784 noExecute = FALSE; 785 } 786 787 /* 788 * Check and remake the makefile 789 */ 790 mtime = Dir_MTime(gn); 791 Compat_Make(gn, gn); 792 793 /* 794 * Restore -t, -q and -n behaviour 795 */ 796 touchFlag = saveTouchFlag; 797 queryFlag = saveQueryFlag; 798 noExecute = saveNoExecute; 799 800 /* 801 * Compat_Make will leave the 'made' field of gn 802 * in one of the following states: 803 * UPTODATE gn was already up-to-date 804 * MADE gn was recreated successfully 805 * ERROR An error occurred while gn was being created 806 * ABORTED gn was not remade because one of its inferiors 807 * could not be made due to errors. 808 */ 809 if (gn->made == MADE) { 810 if (mtime != Dir_MTime(gn)) { 811 DEBUGF(MAKE, 812 ("%s updated (%d -> %d).\n", 813 gn->name, mtime, gn->mtime)); 814 remade_cnt++; 815 } else { 816 DEBUGF(MAKE, 817 ("%s not updated: skipping restart.\n", 818 gn->name)); 819 } 820 } else if (gn->made == ERROR) 821 error_cnt++; 822 else if (gn->made == ABORTED) { 823 printf("`%s' not remade because of errors.\n", 824 gn->name); 825 error_cnt++; 826 } else if (gn->made == UPTODATE) { 827 Lst examine; 828 829 Lst_Init(&examine); 830 Lst_EnQueue(&examine, gn); 831 while (!Lst_IsEmpty(&examine)) { 832 LstNode *eln; 833 GNode *egn = Lst_DeQueue(&examine); 834 835 egn->make = FALSE; 836 LST_FOREACH(eln, &egn->children) { 837 GNode *cgn = Lst_Datum(eln); 838 839 Lst_EnQueue(&examine, cgn); 840 } 841 } 842 } 843 } 844 845 if (error_cnt > 0) 846 Fatal("Failed to remake Makefiles."); 847 if (remade_cnt > 0) { 848 DEBUGF(MAKE, ("Restarting `%s'.\n", save_argv[0])); 849 850 /* 851 * Some of makefiles were remade -- restart from clean state 852 */ 853 if (save_makeflags != NULL) 854 setenv("MAKEFLAGS", save_makeflags, 1); 855 else 856 unsetenv("MAKEFLAGS"); 857 if (execvp(save_argv[0], save_argv) < 0) { 858 Fatal("Can't restart `%s': %s.", 859 save_argv[0], strerror(errno)); 860 } 861 } 862 863 if (curdir != objdir) { 864 if (chdir(objdir) < 0) 865 Fatal("Failed to change directory to %s.", objdir); 866 } 867} 868 869/** 870 * main 871 * The main function, for obvious reasons. Initializes variables 872 * and a few modules, then parses the arguments give it in the 873 * environment and on the command line. Reads the system makefile 874 * followed by either Makefile, makefile or the file given by the 875 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the 876 * flags it has received by then uses either the Make or the Compat 877 * module to create the initial list of targets. 878 * 879 * Results: 880 * If -q was given, exits -1 if anything was out-of-date. Else it exits 881 * 0. 882 * 883 * Side Effects: 884 * The program exits when done. Targets are created. etc. etc. etc. 885 */ 886int 887main(int argc, char **argv) 888{ 889 const char *machine; 890 const char *machine_arch; 891 const char *machine_cpu; 892 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */ 893 const char *p; 894 const char *pathp; 895 const char *path; 896 char mdpath[MAXPATHLEN]; 897 char obpath[MAXPATHLEN]; 898 char cdpath[MAXPATHLEN]; 899 char *cp = NULL, *start; 900 901 save_argv = argv; 902 save_makeflags = getenv("MAKEFLAGS"); 903 if (save_makeflags != NULL) 904 save_makeflags = estrdup(save_makeflags); 905 906 /* 907 * Initialize file global variables. 908 */ 909 expandVars = TRUE; 910 noBuiltins = FALSE; /* Read the built-in rules */ 911 forceJobs = FALSE; /* No -j flag */ 912 curdir = cdpath; 913 914 /* 915 * Initialize program global variables. 916 */ 917 beSilent = FALSE; /* Print commands as executed */ 918 ignoreErrors = FALSE; /* Pay attention to non-zero returns */ 919 noExecute = FALSE; /* Execute all commands */ 920 printGraphOnly = FALSE; /* Don't stop after printing graph */ 921 keepgoing = FALSE; /* Stop on error */ 922 allPrecious = FALSE; /* Remove targets when interrupted */ 923 queryFlag = FALSE; /* This is not just a check-run */ 924 touchFlag = FALSE; /* Actually update targets */ 925 usePipes = TRUE; /* Catch child output in pipes */ 926 debug = 0; /* No debug verbosity, please. */ 927 jobsRunning = FALSE; 928 929 jobLimit = DEFMAXJOBS; 930 compatMake = FALSE; /* No compat mode */ 931 932 check_make_level(); 933 934#ifdef RLIMIT_NOFILE 935 /* 936 * get rid of resource limit on file descriptors 937 */ 938 { 939 struct rlimit rl; 940 if (getrlimit(RLIMIT_NOFILE, &rl) == -1) { 941 err(2, "getrlimit"); 942 } 943 rl.rlim_cur = rl.rlim_max; 944 if (setrlimit(RLIMIT_NOFILE, &rl) == -1) { 945 err(2, "setrlimit"); 946 } 947 } 948#endif 949 950 /* 951 * Prior to 7.0, FreeBSD/pc98 kernel used to set the 952 * utsname.machine to "i386", and MACHINE was defined as 953 * "i386", so it could not be distinguished from FreeBSD/i386. 954 * Therefore, we had to check machine.ispc98 and adjust the 955 * MACHINE variable. NOTE: The code is still here to be able 956 * to compile new make binary on old FreeBSD/pc98 systems, and 957 * have the MACHINE variable set properly. 958 */ 959 if ((machine = getenv("MACHINE")) == NULL) { 960 int ispc98; 961 size_t len; 962 963 len = sizeof(ispc98); 964 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) { 965 if (ispc98) 966 machine = "pc98"; 967 } 968 } 969 970 /* 971 * Get the name of this type of MACHINE from utsname 972 * so we can share an executable for similar machines. 973 * (i.e. m68k: amiga hp300, mac68k, sun3, ...) 974 * 975 * Note that both MACHINE and MACHINE_ARCH are decided at 976 * run-time. 977 */ 978 if (machine == NULL) { 979 static struct utsname utsname; 980 981 if (uname(&utsname) == -1) 982 err(2, "uname"); 983 machine = utsname.machine; 984 } 985 986 if ((machine_arch = getenv("MACHINE_ARCH")) == NULL) { 987#ifdef MACHINE_ARCH 988 machine_arch = MACHINE_ARCH; 989#else 990 machine_arch = "unknown"; 991#endif 992 } 993 994 /* 995 * Set machine_cpu to the minumum supported CPU revision based 996 * on the target architecture, if not already set. 997 */ 998 if ((machine_cpu = getenv("MACHINE_CPU")) == NULL) { 999 if (!strcmp(machine_arch, "i386")) 1000 machine_cpu = "i386"; 1001 else if (!strcmp(machine_arch, "alpha")) 1002 machine_cpu = "ev4"; 1003 else 1004 machine_cpu = "unknown"; 1005 } 1006 1007 /* 1008 * Initialize the parsing, directory and variable modules to prepare 1009 * for the reading of inclusion paths and variable settings on the 1010 * command line 1011 */ 1012 Proc_Init(); 1013 1014 Dir_Init(); /* Initialize directory structures so -I flags 1015 * can be processed correctly */ 1016 Var_Init(environ); /* As well as the lists of variables for 1017 * parsing arguments */ 1018 1019 /* 1020 * Initialize the Shell so that we have a shell for != assignments 1021 * on the command line. 1022 */ 1023 Shell_Init(); 1024 1025 /* 1026 * Initialize various variables. 1027 * MAKE also gets this name, for compatibility 1028 * .MAKEFLAGS gets set to the empty string just in case. 1029 * MFLAGS also gets initialized empty, for compatibility. 1030 */ 1031 Var_SetGlobal("MAKE", argv[0]); 1032 Var_SetGlobal(".MAKEFLAGS", ""); 1033 Var_SetGlobal("MFLAGS", ""); 1034 Var_SetGlobal("MACHINE", machine); 1035 Var_SetGlobal("MACHINE_ARCH", machine_arch); 1036 Var_SetGlobal("MACHINE_CPU", machine_cpu); 1037#ifdef MAKE_VERSION 1038 Var_SetGlobal("MAKE_VERSION", MAKE_VERSION); 1039#endif 1040 Var_SetGlobal(".newline", "\n"); /* handy for :@ loops */ 1041 { 1042 char tmp[64]; 1043 1044 snprintf(tmp, sizeof(tmp), "%u", getpid()); 1045 Var_SetGlobal(".MAKE.PID", tmp); 1046 snprintf(tmp, sizeof(tmp), "%u", getppid()); 1047 Var_SetGlobal(".MAKE.PPID", tmp); 1048 } 1049 Job_SetPrefix(); 1050 1051 /* 1052 * First snag things out of the MAKEFLAGS environment 1053 * variable. Then parse the command line arguments. 1054 */ 1055 Main_ParseArgLine(getenv("MAKEFLAGS"), 1); 1056 1057 MainParseArgs(argc, argv); 1058 1059 /* 1060 * Find where we are... 1061 */ 1062 if (getcwd(curdir, MAXPATHLEN) == NULL) 1063 err(2, NULL); 1064 1065 { 1066 struct stat sa; 1067 1068 if (stat(curdir, &sa) == -1) 1069 err(2, "%s", curdir); 1070 } 1071 1072 /* 1073 * The object directory location is determined using the 1074 * following order of preference: 1075 * 1076 * 1. MAKEOBJDIRPREFIX`cwd` 1077 * 2. MAKEOBJDIR 1078 * 3. PATH_OBJDIR.${MACHINE} 1079 * 4. PATH_OBJDIR 1080 * 5. PATH_OBJDIRPREFIX`cwd` 1081 * 1082 * If one of the first two fails, use the current directory. 1083 * If the remaining three all fail, use the current directory. 1084 * 1085 * Once things are initted, 1086 * have to add the original directory to the search path, 1087 * and modify the paths for the Makefiles apropriately. The 1088 * current directory is also placed as a variable for make scripts. 1089 */ 1090 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) { 1091 if (!(path = getenv("MAKEOBJDIR"))) { 1092 path = PATH_OBJDIR; 1093 pathp = PATH_OBJDIRPREFIX; 1094 snprintf(mdpath, MAXPATHLEN, "%s.%s", path, machine); 1095 if (!(objdir = chdir_verify_path(mdpath, obpath))) 1096 if (!(objdir=chdir_verify_path(path, obpath))) { 1097 snprintf(mdpath, MAXPATHLEN, 1098 "%s%s", pathp, curdir); 1099 if (!(objdir=chdir_verify_path(mdpath, 1100 obpath))) 1101 objdir = curdir; 1102 } 1103 } 1104 else if (!(objdir = chdir_verify_path(path, obpath))) 1105 objdir = curdir; 1106 } 1107 else { 1108 snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir); 1109 if (!(objdir = chdir_verify_path(mdpath, obpath))) 1110 objdir = curdir; 1111 } 1112 Dir_InitDot(); /* Initialize the "." directory */ 1113 if (objdir != curdir) 1114 Path_AddDir(&dirSearchPath, curdir); 1115 Var_SetGlobal(".ST_EXPORTVAR", "YES"); 1116 Var_SetGlobal(".CURDIR", curdir); 1117 Var_SetGlobal(".OBJDIR", objdir); 1118 1119 if (getenv("MAKE_JOBS_FIFO") != NULL) 1120 forceJobs = TRUE; 1121 /* 1122 * Be compatible if user did not specify -j and did not explicitly 1123 * turned compatibility on 1124 */ 1125 if (!compatMake && !forceJobs) 1126 compatMake = TRUE; 1127 1128 /* 1129 * Initialize target and suffix modules in preparation for 1130 * parsing the makefile(s) 1131 */ 1132 Targ_Init(); 1133 Suff_Init(); 1134 1135 DEFAULT = NULL; 1136 time(&now); 1137 1138 /* 1139 * Set up the .TARGETS variable to contain the list of targets to be 1140 * created. If none specified, make the variable empty -- the parser 1141 * will fill the thing in with the default or .MAIN target. 1142 */ 1143 if (Lst_IsEmpty(&create)) { 1144 Var_SetGlobal(".TARGETS", ""); 1145 } else { 1146 LstNode *ln; 1147 1148 for (ln = Lst_First(&create); ln != NULL; ln = Lst_Succ(ln)) { 1149 char *name = Lst_Datum(ln); 1150 1151 Var_Append(".TARGETS", name, VAR_GLOBAL); 1152 } 1153 } 1154 1155 1156 /* 1157 * If no user-supplied system path was given (through the -m option) 1158 * add the directories from the DEFSYSPATH (more than one may be given 1159 * as dir1:...:dirn) to the system include path. 1160 */ 1161 if (TAILQ_EMPTY(&sysIncPath)) { 1162 char syspath[] = PATH_DEFSYSPATH; 1163 1164 for (start = syspath; *start != '\0'; start = cp) { 1165 for (cp = start; *cp != '\0' && *cp != ':'; cp++) 1166 continue; 1167 if (*cp == '\0') { 1168 Path_AddDir(&sysIncPath, start); 1169 } else { 1170 *cp++ = '\0'; 1171 Path_AddDir(&sysIncPath, start); 1172 } 1173 } 1174 } 1175 1176 /* 1177 * Read in the built-in rules first, followed by the specified 1178 * makefile, if it was (makefile != (char *) NULL), or the default 1179 * Makefile and makefile, in that order, if it wasn't. 1180 */ 1181 if (!noBuiltins) { 1182 /* Path of sys.mk */ 1183 Lst sysMkPath = Lst_Initializer(sysMkPath); 1184 LstNode *ln; 1185 char defsysmk[] = PATH_DEFSYSMK; 1186 1187 Path_Expand(defsysmk, &sysIncPath, &sysMkPath); 1188 if (Lst_IsEmpty(&sysMkPath)) 1189 Fatal("make: no system rules (%s).", PATH_DEFSYSMK); 1190 LST_FOREACH(ln, &sysMkPath) { 1191 if (!ReadMakefile(Lst_Datum(ln))) 1192 break; 1193 } 1194 if (ln != NULL) 1195 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln)); 1196 Lst_Destroy(&sysMkPath, free); 1197 } 1198 1199 if (!Lst_IsEmpty(&makefiles)) { 1200 LstNode *ln; 1201 1202 LST_FOREACH(ln, &makefiles) { 1203 if (!TryReadMakefile(Lst_Datum(ln))) 1204 break; 1205 } 1206 if (ln != NULL) 1207 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln)); 1208 } else if (!TryReadMakefile("BSDmakefile")) 1209 if (!TryReadMakefile("makefile")) 1210 TryReadMakefile("Makefile"); 1211 1212 ReadMakefile(".depend"); 1213 1214 /* Install all the flags into the MAKEFLAGS envariable. */ 1215 if (((p = Var_Value(".MAKEFLAGS", VAR_GLOBAL)) != NULL) && *p) 1216 setenv("MAKEFLAGS", p, 1); 1217 else 1218 setenv("MAKEFLAGS", "", 1); 1219 1220 /* 1221 * For compatibility, look at the directories in the VPATH variable 1222 * and add them to the search path, if the variable is defined. The 1223 * variable's value is in the same format as the PATH envariable, i.e. 1224 * <directory>:<directory>:<directory>... 1225 */ 1226 if (Var_Exists("VPATH", VAR_CMD)) { 1227 /* 1228 * GCC stores string constants in read-only memory, but 1229 * Var_Subst will want to write this thing, so store it 1230 * in an array 1231 */ 1232 static char VPATH[] = "${VPATH}"; 1233 Buffer *buf; 1234 char *vpath; 1235 char *ptr; 1236 char savec; 1237 1238 buf = Var_Subst(VPATH, VAR_CMD, FALSE); 1239 1240 vpath = Buf_Data(buf); 1241 do { 1242 /* skip to end of directory */ 1243 for (ptr = vpath; *ptr != ':' && *ptr != '\0'; ptr++) 1244 ; 1245 1246 /* Save terminator character so know when to stop */ 1247 savec = *ptr; 1248 *ptr = '\0'; 1249 1250 /* Add directory to search path */ 1251 Path_AddDir(&dirSearchPath, vpath); 1252 1253 vpath = ptr + 1; 1254 } while (savec != '\0'); 1255 1256 Buf_Destroy(buf, TRUE); 1257 } 1258 1259 /* 1260 * Now that all search paths have been read for suffixes et al, it's 1261 * time to add the default search path to their lists... 1262 */ 1263 Suff_DoPaths(); 1264 1265 /* print the initial graph, if the user requested it */ 1266 if (DEBUG(GRAPH1)) 1267 Targ_PrintGraph(1); 1268 1269 /* print the values of any variables requested by the user */ 1270 if (Lst_IsEmpty(&variables) && !printGraphOnly) { 1271 /* 1272 * Since the user has not requested that any variables 1273 * be printed, we can build targets. 1274 * 1275 * Have read the entire graph and need to make a list of targets 1276 * to create. If none was given on the command line, we consult 1277 * the parsing module to find the main target(s) to create. 1278 */ 1279 Lst targs = Lst_Initializer(targs); 1280 1281 if (!is_posix && mfAutoDeps) { 1282 /* 1283 * Check if any of the makefiles are out-of-date. 1284 */ 1285 Remake_Makefiles(); 1286 } 1287 1288 if (Lst_IsEmpty(&create)) 1289 Parse_MainName(&targs); 1290 else 1291 Targ_FindList(&targs, &create, TARG_CREATE); 1292 1293 if (compatMake) { 1294 /* 1295 * Compat_Init will take care of creating 1296 * all the targets as well as initializing 1297 * the module. 1298 */ 1299 Compat_Run(&targs); 1300 outOfDate = 0; 1301 } else { 1302 /* 1303 * Initialize job module before traversing 1304 * the graph, now that any .BEGIN and .END 1305 * targets have been read. This is done 1306 * only if the -q flag wasn't given (to 1307 * prevent the .BEGIN from being executed 1308 * should it exist). 1309 */ 1310 if (!queryFlag) { 1311 Job_Init(jobLimit); 1312 jobsRunning = TRUE; 1313 } 1314 1315 /* Traverse the graph, checking on all the targets */ 1316 outOfDate = Make_Run(&targs); 1317 } 1318 Lst_Destroy(&targs, NOFREE); 1319 1320 } else { 1321 Var_Print(&variables, expandVars); 1322 } 1323 1324 Lst_Destroy(&variables, free); 1325 Lst_Destroy(&makefiles, free); 1326 Lst_Destroy(&source_makefiles, free); 1327 Lst_Destroy(&create, free); 1328 1329 /* print the graph now it's been processed if the user requested it */ 1330 if (DEBUG(GRAPH2)) 1331 Targ_PrintGraph(2); 1332 1333 if (queryFlag) 1334 return (outOfDate); 1335 1336 if (makeErrors != 0) 1337 Finish(makeErrors); 1338 1339 return (0); 1340} 1341