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