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