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