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