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