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