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