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