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