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