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