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