main.c revision 104395
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 104395 2002-10-03 04:32:47Z jmallett $"); 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 Takes a line of arguments, breaks them and 58 * treats them as if they were given when first 59 * invoked. Used by the parse module to implement 60 * the .MFLAGS target. 61 * 62 * Error Print a tagged error message. The global 63 * MAKE variable must have been defined. This 64 * takes a format string and two optional 65 * arguments for it. 66 * 67 * Fatal Print an error message and exit. Also takes 68 * a format string and two arguments. 69 * 70 * Punt Aborts all jobs and exits with a message. Also 71 * takes a format string and two arguments. 72 * 73 * Finish Finish things up by printing the number of 74 * errors which occured, as passed to it, and 75 * exiting. 76 */ 77 78#include <sys/types.h> 79#include <sys/time.h> 80#include <sys/param.h> 81#include <sys/resource.h> 82#include <sys/signal.h> 83#include <sys/stat.h> 84#if defined(__i386__) 85#include <sys/sysctl.h> 86#endif 87#ifndef MACHINE 88#include <sys/utsname.h> 89#endif 90#include <sys/wait.h> 91#include <err.h> 92#include <stdlib.h> 93#include <errno.h> 94#include <fcntl.h> 95#include <stdio.h> 96#include <sysexits.h> 97#include <stdarg.h> 98#include <unistd.h> 99#include "make.h" 100#include "hash.h" 101#include "dir.h" 102#include "job.h" 103#include "pathnames.h" 104 105#define WANT_ENV_MKLVL 1 106 107#ifndef DEFMAXLOCAL 108#define DEFMAXLOCAL DEFMAXJOBS 109#endif /* DEFMAXLOCAL */ 110 111#define MAKEFLAGS ".MAKEFLAGS" 112 113Lst create; /* Targets to be made */ 114time_t now; /* Time at start of make */ 115GNode *DEFAULT; /* .DEFAULT node */ 116Boolean allPrecious; /* .PRECIOUS given on line by itself */ 117 118static Boolean noBuiltins; /* -r flag */ 119static Lst makefiles; /* ordered list of makefiles to read */ 120static Boolean expandVars; /* fully expand printed variables */ 121static Lst variables; /* list of variables to print */ 122int maxJobs; /* -j argument */ 123static Boolean forceJobs; /* -j argument given */ 124static int maxLocal; /* -L argument */ 125Boolean compatMake; /* -B argument */ 126Boolean debug; /* -d flag */ 127Boolean noExecute; /* -n flag */ 128Boolean keepgoing; /* -k flag */ 129Boolean queryFlag; /* -q flag */ 130Boolean touchFlag; /* -t flag */ 131Boolean usePipes; /* !-P flag */ 132Boolean ignoreErrors; /* -i flag */ 133Boolean beSilent; /* -s flag */ 134Boolean beVerbose; /* -v flag */ 135Boolean oldVars; /* variable substitution style */ 136Boolean checkEnvFirst; /* -e flag */ 137Lst envFirstVars; /* (-E) vars to override from env */ 138static Boolean jobsRunning; /* TRUE if the jobs might be running */ 139 140static void MainParseArgs(int, char **); 141char * chdir_verify_path(char *, char *); 142static int ReadMakefile(void *, void *); 143static void usage(void); 144 145static char *curdir; /* startup directory */ 146static char *objdir; /* where we chdir'ed to */ 147 148/*- 149 * MainParseArgs -- 150 * Parse a given argument vector. Called from main() and from 151 * Main_ParseArgLine() when the .MAKEFLAGS target is used. 152 * 153 * XXX: Deal with command line overriding .MAKEFLAGS in makefile 154 * 155 * Results: 156 * None 157 * 158 * Side Effects: 159 * Various global and local flags will be set depending on the flags 160 * given 161 */ 162static void 163MainParseArgs(argc, argv) 164 int argc; 165 char **argv; 166{ 167 char *p; 168 int c; 169 170 optind = 1; /* since we're called more than once */ 171#ifdef REMOTE 172# define OPTFLAGS "BC:D:E:I:L:PSV:Xd:ef:ij:km:nqrstv" 173#else 174# define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv" 175#endif 176rearg: while((c = getopt(argc, argv, OPTFLAGS)) != -1) { 177 switch(c) { 178 case 'C': 179 chdir(optarg); 180 break; 181 case 'D': 182 Var_Set(optarg, "1", VAR_GLOBAL); 183 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL); 184 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL); 185 break; 186 case 'I': 187 Parse_AddIncludeDir(optarg); 188 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL); 189 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL); 190 break; 191 case 'V': 192 (void)Lst_AtEnd(variables, (void *)optarg); 193 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL); 194 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL); 195 break; 196 case 'X': 197 expandVars = FALSE; 198 break; 199 case 'B': 200 compatMake = TRUE; 201 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL); 202 break; 203#ifdef REMOTE 204 case 'L': { 205 char *endptr; 206 207 maxLocal = strtol(optarg, &endptr, 10); 208 if (maxLocal < 0 || *endptr != '\0') { 209 warnx("illegal number, -L argument -- %s", 210 optarg); 211 usage(); 212 } 213 Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL); 214 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL); 215 break; 216 } 217#endif 218 case 'P': 219 usePipes = FALSE; 220 Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL); 221 break; 222 case 'S': 223 keepgoing = FALSE; 224 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL); 225 break; 226 case 'd': { 227 char *modules = optarg; 228 229 for (; *modules; ++modules) 230 switch (*modules) { 231 case 'A': 232 debug = ~0; 233 break; 234 case 'a': 235 debug |= DEBUG_ARCH; 236 break; 237 case 'c': 238 debug |= DEBUG_COND; 239 break; 240 case 'd': 241 debug |= DEBUG_DIR; 242 break; 243 case 'f': 244 debug |= DEBUG_FOR; 245 break; 246 case 'g': 247 if (modules[1] == '1') { 248 debug |= DEBUG_GRAPH1; 249 ++modules; 250 } 251 else if (modules[1] == '2') { 252 debug |= DEBUG_GRAPH2; 253 ++modules; 254 } 255 break; 256 case 'j': 257 debug |= DEBUG_JOB; 258 break; 259 case 'l': 260 debug |= DEBUG_LOUD; 261 break; 262 case 'm': 263 debug |= DEBUG_MAKE; 264 break; 265 case 's': 266 debug |= DEBUG_SUFF; 267 break; 268 case 't': 269 debug |= DEBUG_TARG; 270 break; 271 case 'v': 272 debug |= DEBUG_VAR; 273 break; 274 default: 275 warnx("illegal argument to d option -- %c", *modules); 276 usage(); 277 } 278 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL); 279 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL); 280 break; 281 } 282 case 'E': 283 p = emalloc(strlen(optarg) + 1); 284 (void)strcpy(p, optarg); 285 (void)Lst_AtEnd(envFirstVars, (void *)p); 286 Var_Append(MAKEFLAGS, "-E", VAR_GLOBAL); 287 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL); 288 break; 289 case 'e': 290 checkEnvFirst = TRUE; 291 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL); 292 break; 293 case 'f': 294 (void)Lst_AtEnd(makefiles, (void *)optarg); 295 break; 296 case 'i': 297 ignoreErrors = TRUE; 298 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL); 299 break; 300 case 'j': { 301 char *endptr; 302 303 forceJobs = TRUE; 304 maxJobs = strtol(optarg, &endptr, 10); 305 if (maxJobs <= 0 || *endptr != '\0') { 306 warnx("illegal number, -j argument -- %s", 307 optarg); 308 usage(); 309 } 310#ifndef REMOTE 311 maxLocal = maxJobs; 312#endif 313 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL); 314 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL); 315 break; 316 } 317 case 'k': 318 keepgoing = TRUE; 319 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL); 320 break; 321 case 'm': 322 Dir_AddDir(sysIncPath, optarg); 323 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL); 324 Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL); 325 break; 326 case 'n': 327 noExecute = TRUE; 328 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL); 329 break; 330 case 'q': 331 queryFlag = TRUE; 332 /* Kind of nonsensical, wot? */ 333 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL); 334 break; 335 case 'r': 336 noBuiltins = TRUE; 337 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL); 338 break; 339 case 's': 340 beSilent = TRUE; 341 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL); 342 break; 343 case 't': 344 touchFlag = TRUE; 345 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL); 346 break; 347 case 'v': 348 beVerbose = TRUE; 349 Var_Append(MAKEFLAGS, "-v", VAR_GLOBAL); 350 break; 351 default: 352 case '?': 353 usage(); 354 } 355 } 356 357 oldVars = TRUE; 358 359 /* 360 * See if the rest of the arguments are variable assignments and 361 * perform them if so. Else take them to be targets and stuff them 362 * on the end of the "create" list. 363 */ 364 for (argv += optind, argc -= optind; *argv; ++argv, --argc) 365 if (Parse_IsVar(*argv)) 366 Parse_DoVar(*argv, VAR_CMD); 367 else { 368 if (!**argv) 369 Punt("illegal (null) argument."); 370 if (**argv == '-') { 371 if ((*argv)[1]) 372 optind = 0; /* -flag... */ 373 else 374 optind = 1; /* - */ 375 goto rearg; 376 } 377 (void)Lst_AtEnd(create, (void *)estrdup(*argv)); 378 } 379} 380 381/*- 382 * Main_ParseArgLine -- 383 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target 384 * is encountered and by main() when reading the .MAKEFLAGS envariable. 385 * Takes a line of arguments and breaks it into its 386 * component words and passes those words and the number of them to the 387 * MainParseArgs function. 388 * The line should have all its leading whitespace removed. 389 * 390 * Results: 391 * None 392 * 393 * Side Effects: 394 * Only those that come from the various arguments. 395 */ 396void 397Main_ParseArgLine(line) 398 char *line; /* Line to fracture */ 399{ 400 char **argv; /* Manufactured argument vector */ 401 int argc; /* Number of arguments in argv */ 402 403 if (line == NULL) 404 return; 405 for (; *line == ' '; ++line) 406 continue; 407 if (!*line) 408 return; 409 410 argv = brk_string(line, &argc, TRUE); 411 MainParseArgs(argc, argv); 412} 413 414char * 415chdir_verify_path(path, obpath) 416 char *path; 417 char *obpath; 418{ 419 struct stat sb; 420 421 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) { 422 if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) { 423 warn("warning: %s", path); 424 return 0; 425 } 426 return obpath; 427 } 428 429 return 0; 430} 431 432 433/*- 434 * main -- 435 * The main function, for obvious reasons. Initializes variables 436 * and a few modules, then parses the arguments give it in the 437 * environment and on the command line. Reads the system makefile 438 * followed by either Makefile, makefile or the file given by the 439 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the 440 * flags it has received by then uses either the Make or the Compat 441 * module to create the initial list of targets. 442 * 443 * Results: 444 * If -q was given, exits -1 if anything was out-of-date. Else it exits 445 * 0. 446 * 447 * Side Effects: 448 * The program exits when done. Targets are created. etc. etc. etc. 449 */ 450int 451main(argc, argv) 452 int argc; 453 char **argv; 454{ 455 Lst targs; /* target nodes to create -- passed to Make_Init */ 456 Boolean outOfDate = TRUE; /* FALSE if all targets up to date */ 457 struct stat sa; 458 char *p, *p1, *path, *pathp; 459#ifdef WANT_ENV_MKLVL 460#define MKLVL_MAXVAL 500 461#define MKLVL_ENVVAR "__MKLVL__" 462 int iMkLvl = 0; 463 char *szMkLvl = getenv(MKLVL_ENVVAR); 464#endif /* WANT_ENV_MKLVL */ 465 char mdpath[MAXPATHLEN]; 466 char obpath[MAXPATHLEN]; 467 char cdpath[MAXPATHLEN]; 468 char *machine = getenv("MACHINE"); 469 char *machine_arch = getenv("MACHINE_ARCH"); 470 char *machine_cpu = getenv("MACHINE_CPU"); 471 Lst sysMkPath; /* Path of sys.mk */ 472 char *cp = NULL, *start; 473 /* avoid faults on read-only strings */ 474 static char syspath[] = _PATH_DEFSYSPATH; 475 476#ifdef WANT_ENV_MKLVL 477 if ((iMkLvl = szMkLvl ? atoi(szMkLvl) : 0) < 0) { 478 iMkLvl = 0; 479 } 480 if (iMkLvl++ > MKLVL_MAXVAL) { 481 errc(2, EAGAIN, 482 "Max recursion level (%d) exceeded.", MKLVL_MAXVAL); 483 } 484 bzero(szMkLvl = emalloc(32), 32); 485 sprintf(szMkLvl, "%d", iMkLvl); 486 setenv(MKLVL_ENVVAR, szMkLvl, 1); 487#endif /* WANT_ENV_MKLVL */ 488 489#if DEFSHELL == 2 490 /* 491 * Turn off ENV to make ksh happier. 492 */ 493 unsetenv("ENV"); 494#endif 495 496#ifdef RLIMIT_NOFILE 497 /* 498 * get rid of resource limit on file descriptors 499 */ 500 { 501 struct rlimit rl; 502 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 && 503 rl.rlim_cur != rl.rlim_max) { 504 rl.rlim_cur = rl.rlim_max; 505 (void) setrlimit(RLIMIT_NOFILE, &rl); 506 } 507 } 508#endif 509 /* 510 * Find where we are... 511 * All this code is so that we know where we are when we start up 512 * on a different machine with pmake. 513 */ 514 curdir = cdpath; 515 if (getcwd(curdir, MAXPATHLEN) == NULL) 516 err(2, NULL); 517 518 if (stat(curdir, &sa) == -1) 519 err(2, "%s", curdir); 520 521#if defined(__i386__) && defined(__FreeBSD_version) && \ 522 __FreeBSD_version > 300003 523 /* 524 * PC-98 kernel sets the `i386' string to the utsname.machine and 525 * it cannot be distinguished from IBM-PC by uname(3). Therefore, 526 * we check machine.ispc98 and adjust the machine variable before 527 * using usname(3) below. 528 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time, 529 * __FreeBSD_version was defined as 300003. So, this check can 530 * safely be done with any kernel with version > 300003. 531 */ 532 if (!machine) { 533 int ispc98; 534 size_t len; 535 536 len = sizeof(ispc98); 537 if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) { 538 if (ispc98) 539 machine = "pc98"; 540 } 541 } 542#endif 543 544 /* 545 * Get the name of this type of MACHINE from utsname 546 * so we can share an executable for similar machines. 547 * (i.e. m68k: amiga hp300, mac68k, sun3, ...) 548 * 549 * Note that while MACHINE is decided at run-time, 550 * MACHINE_ARCH is always known at compile time. 551 */ 552 if (!machine) { 553#ifndef MACHINE 554 struct utsname utsname; 555 556 if (uname(&utsname) == -1) 557 err(2, "uname"); 558 machine = utsname.machine; 559#else 560 machine = MACHINE; 561#endif 562 } 563 564 if (!machine_arch) { 565#ifndef MACHINE_ARCH 566 machine_arch = "unknown"; 567#else 568 machine_arch = MACHINE_ARCH; 569#endif 570 } 571 572 /* 573 * Set machine_cpu to the minumum supported CPU revision based 574 * on the target architecture, if not already set. 575 */ 576 if (!machine_cpu) { 577 if (!strcmp(machine_arch, "i386")) 578 machine_cpu = "i386"; 579 else if (!strcmp(machine_arch, "alpha")) 580 machine_cpu = "ev4"; 581 else 582 machine_cpu = "unknown"; 583 } 584 585 /* 586 * The object directory location is determined using the 587 * following order of preference: 588 * 589 * 1. MAKEOBJDIRPREFIX`cwd` 590 * 2. MAKEOBJDIR 591 * 3. _PATH_OBJDIR.${MACHINE} 592 * 4. _PATH_OBJDIR 593 * 5. _PATH_OBJDIRPREFIX`cwd` 594 * 595 * If one of the first two fails, use the current directory. 596 * If the remaining three all fail, use the current directory. 597 * 598 * Once things are initted, 599 * have to add the original directory to the search path, 600 * and modify the paths for the Makefiles apropriately. The 601 * current directory is also placed as a variable for make scripts. 602 */ 603 if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) { 604 if (!(path = getenv("MAKEOBJDIR"))) { 605 path = _PATH_OBJDIR; 606 pathp = _PATH_OBJDIRPREFIX; 607 (void) snprintf(mdpath, MAXPATHLEN, "%s.%s", 608 path, machine); 609 if (!(objdir = chdir_verify_path(mdpath, obpath))) 610 if (!(objdir=chdir_verify_path(path, obpath))) { 611 (void) snprintf(mdpath, MAXPATHLEN, 612 "%s%s", pathp, curdir); 613 if (!(objdir=chdir_verify_path(mdpath, 614 obpath))) 615 objdir = curdir; 616 } 617 } 618 else if (!(objdir = chdir_verify_path(path, obpath))) 619 objdir = curdir; 620 } 621 else { 622 (void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir); 623 if (!(objdir = chdir_verify_path(mdpath, obpath))) 624 objdir = curdir; 625 } 626 627 create = Lst_Init(FALSE); 628 makefiles = Lst_Init(FALSE); 629 envFirstVars = Lst_Init(FALSE); 630 expandVars = TRUE; 631 variables = Lst_Init(FALSE); 632 beSilent = FALSE; /* Print commands as executed */ 633 ignoreErrors = FALSE; /* Pay attention to non-zero returns */ 634 noExecute = FALSE; /* Execute all commands */ 635 keepgoing = FALSE; /* Stop on error */ 636 allPrecious = FALSE; /* Remove targets when interrupted */ 637 queryFlag = FALSE; /* This is not just a check-run */ 638 noBuiltins = FALSE; /* Read the built-in rules */ 639 touchFlag = FALSE; /* Actually update targets */ 640 usePipes = TRUE; /* Catch child output in pipes */ 641 debug = 0; /* No debug verbosity, please. */ 642 jobsRunning = FALSE; 643 644 maxLocal = DEFMAXLOCAL; /* Set default local max concurrency */ 645#ifdef REMOTE 646 maxJobs = DEFMAXJOBS; /* Set default max concurrency */ 647#else 648 maxJobs = maxLocal; 649#endif 650 forceJobs = FALSE; /* No -j flag */ 651 compatMake = FALSE; /* No compat mode */ 652 653 654 /* 655 * Initialize the parsing, directory and variable modules to prepare 656 * for the reading of inclusion paths and variable settings on the 657 * command line 658 */ 659 Dir_Init(); /* Initialize directory structures so -I flags 660 * can be processed correctly */ 661 Parse_Init(); /* Need to initialize the paths of #include 662 * directories */ 663 Var_Init(); /* As well as the lists of variables for 664 * parsing arguments */ 665 str_init(); 666 if (objdir != curdir) 667 Dir_AddDir(dirSearchPath, curdir); 668 Var_Set(".CURDIR", curdir, VAR_GLOBAL); 669 Var_Set(".OBJDIR", objdir, VAR_GLOBAL); 670 671 /* 672 * Initialize various variables. 673 * MAKE also gets this name, for compatibility 674 * .MAKEFLAGS gets set to the empty string just in case. 675 * MFLAGS also gets initialized empty, for compatibility. 676 */ 677 Var_Set("MAKE", argv[0], VAR_GLOBAL); 678 Var_Set(MAKEFLAGS, "", VAR_GLOBAL); 679 Var_Set("MFLAGS", "", VAR_GLOBAL); 680 Var_Set("MACHINE", machine, VAR_GLOBAL); 681 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL); 682 Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL); 683#ifdef MAKE_VERSION 684 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL); 685#endif 686 687 /* 688 * First snag any flags out of the MAKE environment variable. 689 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's 690 * in a different format). 691 */ 692#ifdef POSIX 693 Main_ParseArgLine(getenv("MAKEFLAGS")); 694#else 695 Main_ParseArgLine(getenv("MAKE")); 696#endif 697 698 MainParseArgs(argc, argv); 699 700 /* 701 * Be compatible if user did not specify -j and did not explicitly 702 * turned compatibility on 703 */ 704 if (!compatMake && !forceJobs) 705 compatMake = TRUE; 706 707 /* 708 * Initialize archive, target and suffix modules in preparation for 709 * parsing the makefile(s) 710 */ 711 Arch_Init(); 712 Targ_Init(); 713 Suff_Init(); 714 715 DEFAULT = NULL; 716 (void)time(&now); 717 718 /* 719 * Set up the .TARGETS variable to contain the list of targets to be 720 * created. If none specified, make the variable empty -- the parser 721 * will fill the thing in with the default or .MAIN target. 722 */ 723 if (!Lst_IsEmpty(create)) { 724 LstNode ln; 725 726 for (ln = Lst_First(create); ln != NULL; 727 ln = Lst_Succ(ln)) { 728 char *name = (char *)Lst_Datum(ln); 729 730 Var_Append(".TARGETS", name, VAR_GLOBAL); 731 } 732 } else 733 Var_Set(".TARGETS", "", VAR_GLOBAL); 734 735 736 /* 737 * If no user-supplied system path was given (through the -m option) 738 * add the directories from the DEFSYSPATH (more than one may be given 739 * as dir1:...:dirn) to the system include path. 740 */ 741 if (Lst_IsEmpty(sysIncPath)) { 742 for (start = syspath; *start != '\0'; start = cp) { 743 for (cp = start; *cp != '\0' && *cp != ':'; cp++) 744 continue; 745 if (*cp == '\0') { 746 Dir_AddDir(sysIncPath, start); 747 } else { 748 *cp++ = '\0'; 749 Dir_AddDir(sysIncPath, start); 750 } 751 } 752 } 753 754 /* 755 * Read in the built-in rules first, followed by the specified 756 * makefile, if it was (makefile != (char *) NULL), or the default 757 * Makefile and makefile, in that order, if it wasn't. 758 */ 759 if (!noBuiltins) { 760 LstNode ln; 761 762 sysMkPath = Lst_Init (FALSE); 763 Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath); 764 if (Lst_IsEmpty(sysMkPath)) 765 Fatal("make: no system rules (%s).", _PATH_DEFSYSMK); 766 ln = Lst_Find(sysMkPath, (void *)NULL, ReadMakefile); 767 if (ln != NULL) 768 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln)); 769 } 770 771 if (!Lst_IsEmpty(makefiles)) { 772 LstNode ln; 773 774 ln = Lst_Find(makefiles, (void *)NULL, ReadMakefile); 775 if (ln != NULL) 776 Fatal("make: cannot open %s.", (char *)Lst_Datum(ln)); 777 } else if (!ReadMakefile("BSDmakefile", NULL)) 778 if (!ReadMakefile("makefile", NULL)) 779 (void)ReadMakefile("Makefile", NULL); 780 781 (void)ReadMakefile(".depend", NULL); 782 783 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL); 784 efree(p1); 785 786 /* Install all the flags into the MAKE envariable. */ 787 if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p) 788#ifdef POSIX 789 setenv("MAKEFLAGS", p, 1); 790#else 791 setenv("MAKE", p, 1); 792#endif 793 efree(p1); 794 795 /* 796 * For compatibility, look at the directories in the VPATH variable 797 * and add them to the search path, if the variable is defined. The 798 * variable's value is in the same format as the PATH envariable, i.e. 799 * <directory>:<directory>:<directory>... 800 */ 801 if (Var_Exists("VPATH", VAR_CMD)) { 802 char *vpath, *path1, *cp1, savec; 803 /* 804 * GCC stores string constants in read-only memory, but 805 * Var_Subst will want to write this thing, so store it 806 * in an array 807 */ 808 static char VPATH[] = "${VPATH}"; 809 810 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE); 811 path1 = vpath; 812 do { 813 /* skip to end of directory */ 814 for (cp1 = path1; *cp != ':' && *cp != '\0'; cp++) 815 continue; 816 /* Save terminator character so know when to stop */ 817 savec = *cp1; 818 *cp1 = '\0'; 819 /* Add directory to search path */ 820 Dir_AddDir(dirSearchPath, path1); 821 *cp1 = savec; 822 path1 = cp1 + 1; 823 } while (savec == ':'); 824 (void)free(vpath); 825 } 826 827 /* 828 * Now that all search paths have been read for suffixes et al, it's 829 * time to add the default search path to their lists... 830 */ 831 Suff_DoPaths(); 832 833 /* print the initial graph, if the user requested it */ 834 if (DEBUG(GRAPH1)) 835 Targ_PrintGraph(1); 836 837 /* print the values of any variables requested by the user */ 838 if (!Lst_IsEmpty(variables)) { 839 LstNode ln; 840 841 for (ln = Lst_First(variables); ln != NULL; 842 ln = Lst_Succ(ln)) { 843 char *value; 844 if (expandVars) { 845 p1 = emalloc(strlen((char *)Lst_Datum(ln)) + 1 + 3); 846 /* This sprintf is safe, because of the malloc above */ 847 (void)sprintf(p1, "${%s}", (char *)Lst_Datum(ln)); 848 value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE); 849 } else { 850 value = Var_Value((char *)Lst_Datum(ln), 851 VAR_GLOBAL, &p1); 852 } 853 printf("%s\n", value ? value : ""); 854 if (p1) 855 free(p1); 856 } 857 } else { 858 859 /* 860 * Have now read the entire graph and need to make a list of targets 861 * to create. If none was given on the command line, we consult the 862 * parsing module to find the main target(s) to create. 863 */ 864 if (Lst_IsEmpty(create)) 865 targs = Parse_MainName(); 866 else 867 targs = Targ_FindList(create, TARG_CREATE); 868 869 if (!compatMake) { 870 /* 871 * Initialize job module before traversing the graph, now that 872 * any .BEGIN and .END targets have been read. This is done 873 * only if the -q flag wasn't given (to prevent the .BEGIN from 874 * being executed should it exist). 875 */ 876 if (!queryFlag) { 877 if (maxLocal == -1) 878 maxLocal = maxJobs; 879 Job_Init(maxJobs, maxLocal); 880 jobsRunning = TRUE; 881 } 882 883 /* Traverse the graph, checking on all the targets */ 884 outOfDate = Make_Run(targs); 885 } else { 886 /* 887 * Compat_Init will take care of creating all the targets as 888 * well as initializing the module. 889 */ 890 Compat_Run(targs); 891 } 892 Lst_Destroy(targs, NOFREE); 893 } 894 895 Lst_Destroy(variables, NOFREE); 896 Lst_Destroy(makefiles, NOFREE); 897 Lst_Destroy(create, (void (*)(void *)) free); 898 899 /* print the graph now it's been processed if the user requested it */ 900 if (DEBUG(GRAPH2)) 901 Targ_PrintGraph(2); 902 903 Suff_End(); 904 Targ_End(); 905 Arch_End(); 906 str_end(); 907 Var_End(); 908 Parse_End(); 909 Dir_End(); 910 911 if (queryFlag && outOfDate) 912 return(1); 913 else 914 return(0); 915} 916 917/*- 918 * ReadMakefile -- 919 * Open and parse the given makefile. 920 * 921 * Results: 922 * TRUE if ok. FALSE if couldn't open file. 923 * 924 * Side Effects: 925 * lots 926 */ 927static Boolean 928ReadMakefile(p, q) 929 void *p; 930 void *q __unused; 931{ 932 char *fname = p; /* makefile to read */ 933 extern Lst parseIncPath; 934 FILE *stream; 935 char *name, path[MAXPATHLEN]; 936 char *MAKEFILE; 937 int setMAKEFILE; 938 939 if (!strcmp(fname, "-")) { 940 Parse_File("(stdin)", stdin); 941 Var_Set("MAKEFILE", "", VAR_GLOBAL); 942 } else { 943 setMAKEFILE = strcmp(fname, ".depend"); 944 945 /* if we've chdir'd, rebuild the path name */ 946 if (curdir != objdir && *fname != '/') { 947 (void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname); 948 /* 949 * XXX The realpath stuff breaks relative includes 950 * XXX in some cases. The problem likely is in 951 * XXX parse.c where it does special things in 952 * XXX ParseDoInclude if the file is relateive 953 * XXX or absolute and not a system file. There 954 * XXX it assumes that if the current file that's 955 * XXX being included is absolute, that any files 956 * XXX that it includes shouldn't do the -I path 957 * XXX stuff, which is inconsistant with historical 958 * XXX behavior. However, I can't pentrate the mists 959 * XXX further, so I'm putting this workaround in 960 * XXX here until such time as the underlying bug 961 * XXX can be fixed. 962 */ 963#if THIS_BREAKS_THINGS 964 if (realpath(path, path) != NULL && 965 (stream = fopen(path, "r")) != NULL) { 966 MAKEFILE = fname; 967 fname = path; 968 goto found; 969 } 970 } else if (realpath(fname, path) != NULL) { 971 MAKEFILE = fname; 972 fname = path; 973 if ((stream = fopen(fname, "r")) != NULL) 974 goto found; 975 } 976#else 977 if ((stream = fopen(path, "r")) != NULL) { 978 MAKEFILE = fname; 979 fname = path; 980 goto found; 981 } 982 } else { 983 MAKEFILE = fname; 984 if ((stream = fopen(fname, "r")) != NULL) 985 goto found; 986 } 987#endif 988 /* look in -I and system include directories. */ 989 name = Dir_FindFile(fname, parseIncPath); 990 if (!name) 991 name = Dir_FindFile(fname, sysIncPath); 992 if (!name || !(stream = fopen(name, "r"))) 993 return(FALSE); 994 MAKEFILE = fname = name; 995 /* 996 * set the MAKEFILE variable desired by System V fans -- the 997 * placement of the setting here means it gets set to the last 998 * makefile specified, as it is set by SysV make. 999 */ 1000found: 1001 if (setMAKEFILE) 1002 Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL); 1003 Parse_File(fname, stream); 1004 (void)fclose(stream); 1005 } 1006 return(TRUE); 1007} 1008 1009/*- 1010 * Cmd_Exec -- 1011 * Execute the command in cmd, and return the output of that command 1012 * in a string. 1013 * 1014 * Results: 1015 * A string containing the output of the command, or the empty string 1016 * If error is not NULL, it contains the reason for the command failure 1017 * 1018 * Side Effects: 1019 * The string must be freed by the caller. 1020 */ 1021char * 1022Cmd_Exec(cmd, error) 1023 char *cmd; 1024 char **error; 1025{ 1026 char *args[4]; /* Args for invoking the shell */ 1027 int fds[2]; /* Pipe streams */ 1028 int cpid; /* Child PID */ 1029 int pid; /* PID from wait() */ 1030 char *res; /* result */ 1031 int status; /* command exit status */ 1032 Buffer buf; /* buffer to store the result */ 1033 char *cp; 1034 int cc; 1035 1036 1037 *error = NULL; 1038 1039 /* 1040 * Set up arguments for shell 1041 */ 1042 args[0] = "sh"; 1043 args[1] = "-c"; 1044 args[2] = cmd; 1045 args[3] = NULL; 1046 1047 /* 1048 * Open a pipe for fetching its output 1049 */ 1050 if (pipe(fds) == -1) { 1051 *error = "Couldn't create pipe for \"%s\""; 1052 goto bad; 1053 } 1054 1055 /* 1056 * Fork 1057 */ 1058 switch (cpid = vfork()) { 1059 case 0: 1060 /* 1061 * Close input side of pipe 1062 */ 1063 (void) close(fds[0]); 1064 1065 /* 1066 * Duplicate the output stream to the shell's output, then 1067 * shut the extra thing down. Note we don't fetch the error 1068 * stream...why not? Why? 1069 */ 1070 (void) dup2(fds[1], 1); 1071 (void) close(fds[1]); 1072 1073#if defined(DEFSHELL) && DEFSHELL == 0 1074 (void) execv("/bin/csh", args); 1075#elif DEFSHELL == 1 1076 (void) execv("/bin/sh", args); 1077#elif DEFSHELL == 2 1078 (void) execv("/bin/ksh", args); 1079#else 1080#error "DEFSHELL must be 1 or 2." 1081#endif 1082 _exit(1); 1083 /*NOTREACHED*/ 1084 1085 case -1: 1086 *error = "Couldn't exec \"%s\""; 1087 goto bad; 1088 1089 default: 1090 /* 1091 * No need for the writing half 1092 */ 1093 (void) close(fds[1]); 1094 1095 buf = Buf_Init (MAKE_BSIZE); 1096 1097 do { 1098 char result[BUFSIZ]; 1099 cc = read(fds[0], result, sizeof(result)); 1100 if (cc > 0) 1101 Buf_AddBytes(buf, cc, (Byte *) result); 1102 } 1103 while (cc > 0 || (cc == -1 && errno == EINTR)); 1104 1105 /* 1106 * Close the input side of the pipe. 1107 */ 1108 (void) close(fds[0]); 1109 1110 /* 1111 * Wait for the process to exit. 1112 */ 1113 while(((pid = wait(&status)) != cpid) && (pid >= 0)) 1114 continue; 1115 1116 if (cc == -1) 1117 *error = "Error reading shell's output for \"%s\""; 1118 1119 res = (char *)Buf_GetAll (buf, &cc); 1120 Buf_Destroy (buf, FALSE); 1121 1122 if (status) 1123 *error = "\"%s\" returned non-zero status"; 1124 1125 /* 1126 * Null-terminate the result, convert newlines to spaces and 1127 * install it in the variable. 1128 */ 1129 res[cc] = '\0'; 1130 cp = &res[cc] - 1; 1131 1132 if (*cp == '\n') { 1133 /* 1134 * A final newline is just stripped 1135 */ 1136 *cp-- = '\0'; 1137 } 1138 while (cp >= res) { 1139 if (*cp == '\n') { 1140 *cp = ' '; 1141 } 1142 cp--; 1143 } 1144 break; 1145 } 1146 return res; 1147bad: 1148 res = emalloc(1); 1149 *res = '\0'; 1150 return res; 1151} 1152 1153/*- 1154 * Debug -- 1155 * Print a debugging message given its format. 1156 * 1157 * Results: 1158 * None. 1159 * 1160 * Side Effects: 1161 * The message is printed. 1162 */ 1163/* VARARGS */ 1164void 1165Debug(const char *fmt, ...) 1166{ 1167 va_list ap; 1168 1169 va_start(ap, fmt); 1170 (void)vfprintf(stderr, fmt, ap); 1171 va_end(ap); 1172 (void)fflush(stderr); 1173} 1174 1175/*- 1176 * Error -- 1177 * Print an error message given its format. 1178 * 1179 * Results: 1180 * None. 1181 * 1182 * Side Effects: 1183 * The message is printed. 1184 */ 1185/* VARARGS */ 1186void 1187Error(const char *fmt, ...) 1188{ 1189 va_list ap; 1190 1191 va_start(ap, fmt); 1192 (void)vfprintf(stderr, fmt, ap); 1193 va_end(ap); 1194 (void)fprintf(stderr, "\n"); 1195 (void)fflush(stderr); 1196} 1197 1198/*- 1199 * Fatal -- 1200 * Produce a Fatal error message. If jobs are running, waits for them 1201 * to finish. 1202 * 1203 * Results: 1204 * None 1205 * 1206 * Side Effects: 1207 * The program exits 1208 */ 1209/* VARARGS */ 1210void 1211Fatal(const char *fmt, ...) 1212{ 1213 va_list ap; 1214 1215 va_start(ap, fmt); 1216 if (jobsRunning) 1217 Job_Wait(); 1218 1219 (void)vfprintf(stderr, fmt, ap); 1220 va_end(ap); 1221 (void)fprintf(stderr, "\n"); 1222 (void)fflush(stderr); 1223 1224 if (DEBUG(GRAPH2)) 1225 Targ_PrintGraph(2); 1226 exit(2); /* Not 1 so -q can distinguish error */ 1227} 1228 1229/* 1230 * Punt -- 1231 * Major exception once jobs are being created. Kills all jobs, prints 1232 * a message and exits. 1233 * 1234 * Results: 1235 * None 1236 * 1237 * Side Effects: 1238 * All children are killed indiscriminately and the program Lib_Exits 1239 */ 1240/* VARARGS */ 1241void 1242Punt(const char *fmt, ...) 1243{ 1244 va_list ap; 1245 1246 va_start(ap, fmt); 1247 (void)fprintf(stderr, "make: "); 1248 (void)vfprintf(stderr, fmt, ap); 1249 va_end(ap); 1250 (void)fprintf(stderr, "\n"); 1251 (void)fflush(stderr); 1252 1253 DieHorribly(); 1254} 1255 1256/*- 1257 * DieHorribly -- 1258 * Exit without giving a message. 1259 * 1260 * Results: 1261 * None 1262 * 1263 * Side Effects: 1264 * A big one... 1265 */ 1266void 1267DieHorribly() 1268{ 1269 if (jobsRunning) 1270 Job_AbortAll(); 1271 if (DEBUG(GRAPH2)) 1272 Targ_PrintGraph(2); 1273 exit(2); /* Not 1, so -q can distinguish error */ 1274} 1275 1276/* 1277 * Finish -- 1278 * Called when aborting due to errors in child shell to signal 1279 * abnormal exit. 1280 * 1281 * Results: 1282 * None 1283 * 1284 * Side Effects: 1285 * The program exits 1286 */ 1287void 1288Finish(errors) 1289 int errors; /* number of errors encountered in Make_Make */ 1290{ 1291 Fatal("%d error%s", errors, errors == 1 ? "" : "s"); 1292} 1293 1294/* 1295 * emalloc -- 1296 * malloc, but die on error. 1297 */ 1298void * 1299emalloc(len) 1300 size_t len; 1301{ 1302 void *p; 1303 1304 if ((p = malloc(len)) == NULL) 1305 enomem(); 1306 return(p); 1307} 1308 1309/* 1310 * estrdup -- 1311 * strdup, but die on error. 1312 */ 1313char * 1314estrdup(str) 1315 const char *str; 1316{ 1317 char *p; 1318 1319 if ((p = strdup(str)) == NULL) 1320 enomem(); 1321 return(p); 1322} 1323 1324/* 1325 * erealloc -- 1326 * realloc, but die on error. 1327 */ 1328void * 1329erealloc(ptr, size) 1330 void *ptr; 1331 size_t size; 1332{ 1333 if ((ptr = realloc(ptr, size)) == NULL) 1334 enomem(); 1335 return(ptr); 1336} 1337 1338/* 1339 * enomem -- 1340 * die when out of memory. 1341 */ 1342void 1343enomem() 1344{ 1345 err(2, NULL); 1346} 1347 1348/* 1349 * enunlink -- 1350 * Remove a file carefully, avoiding directories. 1351 */ 1352int 1353eunlink(file) 1354 const char *file; 1355{ 1356 struct stat st; 1357 1358 if (lstat(file, &st) == -1) 1359 return -1; 1360 1361 if (S_ISDIR(st.st_mode)) { 1362 errno = EISDIR; 1363 return -1; 1364 } 1365 return unlink(file); 1366} 1367 1368/* 1369 * usage -- 1370 * exit with usage message 1371 */ 1372static void 1373usage() 1374{ 1375 (void)fprintf(stderr, "%s\n%s\n%s\n", 1376"usage: make [-Beiknqrstv] [-D variable] [-d flags] [-E variable] [-f makefile]", 1377" [-I directory] [-j max_jobs] [-m directory] [-V variable]", 1378" [variable=value] [target ...]"); 1379 exit(2); 1380} 1381 1382 1383int 1384PrintAddr(a, b) 1385 void * a; 1386 void * b __unused; 1387{ 1388 printf("%p ", a); 1389 return 0; 1390} 1391