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