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