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