1 /* $NetBSD: main.c,v 1.160 2008/12/20 09:42:02 dsl Exp $ */ 2 3 /* 4 * Copyright (c) 1988, 1989, 1990, 1993 5 * The Regents of the University of California. 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. Neither the name of the University nor the names of its contributors 19 * may be used to endorse or promote products derived from this software 20 * without specific prior written permission. 21 * 22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 * SUCH DAMAGE. 33 */ 34 35 /* 36 * Copyright (c) 1989 by Berkeley Softworks 37 * All rights reserved. 38 * 39 * This code is derived from software contributed to Berkeley by 40 * Adam de Boor. 41 * 42 * Redistribution and use in source and binary forms, with or without 43 * modification, are permitted provided that the following conditions 44 * are met: 45 * 1. Redistributions of source code must retain the above copyright 46 * notice, this list of conditions and the following disclaimer. 47 * 2. Redistributions in binary form must reproduce the above copyright 48 * notice, this list of conditions and the following disclaimer in the 49 * documentation and/or other materials provided with the distribution. 50 * 3. All advertising materials mentioning features or use of this software 51 * must display the following acknowledgement: 52 * This product includes software developed by the University of 53 * California, Berkeley and its contributors. 54 * 4. Neither the name of the University nor the names of its contributors 55 * may be used to endorse or promote products derived from this software 56 * without specific prior written permission. 57 * 58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 68 * SUCH DAMAGE. 69 */ 70 71 #ifndef MAKE_NATIVE 72 static char rcsid[] = "$NetBSD: main.c,v 1.160 2008/12/20 09:42:02 dsl Exp $"; 73 #else 74 #include <sys/cdefs.h> 75 #ifndef lint 76 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993\ 77 The Regents of the University of California. All rights reserved."); 78 #endif /* not lint */ 79 80 #ifndef lint 81 #if 0 82 static char sccsid[] = "@(#)main.c 8.3 (Berkeley) 3/19/94"; 83 #else 84 __RCSID("$NetBSD: main.c,v 1.160 2008/12/20 09:42:02 dsl Exp $"); 85 #endif 86 #endif /* not lint */ 87 #endif 88 89 /*- 90 * main.c -- 91 * The main file for this entire program. Exit routines etc 92 * reside here. 93 * 94 * Utility functions defined in this file: 95 * Main_ParseArgLine Takes a line of arguments, breaks them and 96 * treats them as if they were given when first 97 * invoked. Used by the parse module to implement 98 * the .MFLAGS target. 99 * 100 * Error Print a tagged error message. The global 101 * MAKE variable must have been defined. This 102 * takes a format string and two optional 103 * arguments for it. 104 * 105 * Fatal Print an error message and exit. Also takes 106 * a format string and two arguments. 107 * 108 * Punt Aborts all jobs and exits with a message. Also 109 * takes a format string and two arguments. 110 * 111 * Finish Finish things up by printing the number of 112 * errors which occurred, as passed to it, and 113 * exiting. 114 */ 115 116 #include <sys/types.h> 117 #include <sys/time.h> 118 #include <sys/param.h> 119 #include <sys/resource.h> 120 #include <sys/signal.h> 121 #include <sys/stat.h> 122 #ifdef MAKE_NATIVE 123 #include <sys/utsname.h> 124 #endif 125 #include <sys/wait.h> 126 127 #include <errno.h> 128 #include <fcntl.h> 129 #include <stdarg.h> 130 #include <stdio.h> 131 #include <stdlib.h> 132 #include <time.h> 133 134 #include "make.h" 135 #include "hash.h" 136 #include "dir.h" 137 #include "job.h" 138 #include "pathnames.h" 139 #include "trace.h" 140 141 #ifdef USE_IOVEC 142 #include <sys/uio.h> 143 #endif 144 145 #ifndef DEFMAXLOCAL 146 #define DEFMAXLOCAL DEFMAXJOBS 147 #endif /* DEFMAXLOCAL */ 148 149 Lst create; /* Targets to be made */ 150 time_t now; /* Time at start of make */ 151 GNode *DEFAULT; /* .DEFAULT node */ 152 Boolean allPrecious; /* .PRECIOUS given on line by itself */ 153 154 static Boolean noBuiltins; /* -r flag */ 155 static Lst makefiles; /* ordered list of makefiles to read */ 156 static Boolean printVars; /* print value of one or more vars */ 157 static Lst variables; /* list of variables to print */ 158 int maxJobs; /* -j argument */ 159 static int maxJobTokens; /* -j argument */ 160 Boolean compatMake; /* -B argument */ 161 int debug; /* -d argument */ 162 Boolean noExecute; /* -n flag */ 163 Boolean noRecursiveExecute; /* -N flag */ 164 Boolean keepgoing; /* -k flag */ 165 Boolean queryFlag; /* -q flag */ 166 Boolean touchFlag; /* -t flag */ 167 Boolean ignoreErrors; /* -i flag */ 168 Boolean beSilent; /* -s flag */ 169 Boolean oldVars; /* variable substitution style */ 170 Boolean checkEnvFirst; /* -e flag */ 171 Boolean parseWarnFatal; /* -W flag */ 172 Boolean jobServer; /* -J flag */ 173 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */ 174 Boolean varNoExportEnv; /* -X flag */ 175 Boolean doing_depend; /* Set while reading .depend */ 176 static Boolean jobsRunning; /* TRUE if the jobs might be running */ 177 static const char * tracefile; 178 static char * Check_Cwd_av(int, char **, int); 179 static void MainParseArgs(int, char **); 180 static int ReadMakefile(ClientData, ClientData); 181 static void usage(void); 182 183 static char curdir[MAXPATHLEN + 1]; /* startup directory */ 184 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */ 185 char *progname; /* the program name */ 186 187 Boolean forceJobs = FALSE; 188 189 extern Lst parseIncPath; 190 191 static void 192 parse_debug_options(const char *argvalue) 193 { 194 const char *modules; 195 const char *mode; 196 char *fname; 197 int len; 198 199 for (modules = argvalue; *modules; ++modules) { 200 switch (*modules) { 201 case 'A': 202 debug = ~0; 203 break; 204 case 'a': 205 debug |= DEBUG_ARCH; 206 break; 207 case 'C': 208 debug |= DEBUG_CWD; 209 break; 210 case 'c': 211 debug |= DEBUG_COND; 212 break; 213 case 'd': 214 debug |= DEBUG_DIR; 215 break; 216 case 'e': 217 debug |= DEBUG_ERROR; 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 else if (modules[1] == '3') { 232 debug |= DEBUG_GRAPH3; 233 ++modules; 234 } 235 break; 236 case 'j': 237 debug |= DEBUG_JOB; 238 break; 239 case 'l': 240 debug |= DEBUG_LOUD; 241 break; 242 case 'm': 243 debug |= DEBUG_MAKE; 244 break; 245 case 'n': 246 debug |= DEBUG_SCRIPT; 247 break; 248 case 'p': 249 debug |= DEBUG_PARSE; 250 break; 251 case 's': 252 debug |= DEBUG_SUFF; 253 break; 254 case 't': 255 debug |= DEBUG_TARG; 256 break; 257 case 'v': 258 debug |= DEBUG_VAR; 259 break; 260 case 'x': 261 debug |= DEBUG_SHELL; 262 break; 263 case 'F': 264 if (debug_file != stdout && debug_file != stderr) 265 fclose(debug_file); 266 if (*++modules == '+') 267 mode = "a"; 268 else 269 mode = "w"; 270 if (strcmp(modules, "stdout") == 0) { 271 debug_file = stdout; 272 goto debug_setbuf; 273 } 274 if (strcmp(modules, "stderr") == 0) { 275 debug_file = stderr; 276 goto debug_setbuf; 277 } 278 len = strlen(modules); 279 fname = malloc(len + 20); 280 memcpy(fname, modules, len + 1); 281 /* Let the filename be modified by the pid */ 282 if (strcmp(fname + len - 3, ".%d") == 0) 283 snprintf(fname + len - 2, 20, "%d", getpid()); 284 debug_file = fopen(fname, mode); 285 if (!debug_file) { 286 fprintf(stderr, "Cannot open debug file %s\n", 287 fname); 288 usage(); 289 } 290 free(fname); 291 goto debug_setbuf; 292 default: 293 (void)fprintf(stderr, 294 "%s: illegal argument to d option -- %c\n", 295 progname, *modules); 296 usage(); 297 } 298 } 299 debug_setbuf: 300 /* 301 * Make the debug_file unbuffered, and make 302 * stdout line buffered (unless debugfile == stdout). 303 */ 304 setvbuf(debug_file, NULL, _IONBF, 0); 305 if (debug_file != stdout) { 306 setvbuf(stdout, NULL, _IOLBF, 0); 307 } 308 } 309 310 /*- 311 * MainParseArgs -- 312 * Parse a given argument vector. Called from main() and from 313 * Main_ParseArgLine() when the .MAKEFLAGS target is used. 314 * 315 * XXX: Deal with command line overriding .MAKEFLAGS in makefile 316 * 317 * Results: 318 * None 319 * 320 * Side Effects: 321 * Various global and local flags will be set depending on the flags 322 * given 323 */ 324 static void 325 MainParseArgs(int argc, char **argv) 326 { 327 char *p; 328 int c = '?'; 329 int arginc; 330 char *argvalue; 331 const char *getopt_def; 332 char *optscan; 333 Boolean inOption, dashDash = FALSE; 334 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */ 335 336 #define OPTFLAGS "BD:I:J:NST:V:WXd:ef:ij:km:nqrst" 337 /* Can't actually use getopt(3) because rescanning is not portable */ 338 339 getopt_def = OPTFLAGS; 340 rearg: 341 inOption = FALSE; 342 optscan = NULL; 343 while(argc > 1) { 344 char *getopt_spec; 345 if(!inOption) 346 optscan = argv[1]; 347 c = *optscan++; 348 arginc = 0; 349 if(inOption) { 350 if(c == '\0') { 351 ++argv; 352 --argc; 353 inOption = FALSE; 354 continue; 355 } 356 } else { 357 if (c != '-' || dashDash) 358 break; 359 inOption = TRUE; 360 c = *optscan++; 361 } 362 /* '-' found at some earlier point */ 363 getopt_spec = strchr(getopt_def, c); 364 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') { 365 /* -<something> found, and <something> should have an arg */ 366 inOption = FALSE; 367 arginc = 1; 368 argvalue = optscan; 369 if(*argvalue == '\0') { 370 if (argc < 3) 371 goto noarg; 372 argvalue = argv[2]; 373 arginc = 2; 374 } 375 } else { 376 argvalue = NULL; 377 } 378 switch(c) { 379 case '\0': 380 arginc = 1; 381 inOption = FALSE; 382 break; 383 case 'B': 384 compatMake = TRUE; 385 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL); 386 break; 387 case 'D': 388 if (argvalue == NULL || argvalue[0] == 0) goto noarg; 389 Var_Set(argvalue, "1", VAR_GLOBAL, 0); 390 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL); 391 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 392 break; 393 case 'I': 394 if (argvalue == NULL) goto noarg; 395 Parse_AddIncludeDir(argvalue); 396 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL); 397 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 398 break; 399 case 'J': 400 if (argvalue == NULL) goto noarg; 401 if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) { 402 (void)fprintf(stderr, 403 "%s: internal error -- J option malformed (%s)\n", 404 progname, argvalue); 405 usage(); 406 } 407 if ((fcntl(jp_0, F_GETFD, 0) < 0) || 408 (fcntl(jp_1, F_GETFD, 0) < 0)) { 409 #if 0 410 (void)fprintf(stderr, 411 "%s: ###### warning -- J descriptors were closed!\n", 412 progname); 413 exit(2); 414 #endif 415 jp_0 = -1; 416 jp_1 = -1; 417 compatMake = TRUE; 418 } else { 419 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL); 420 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 421 jobServer = TRUE; 422 } 423 break; 424 case 'N': 425 noExecute = TRUE; 426 noRecursiveExecute = TRUE; 427 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL); 428 break; 429 case 'S': 430 keepgoing = FALSE; 431 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL); 432 break; 433 case 'T': 434 if (argvalue == NULL) goto noarg; 435 tracefile = bmake_strdup(argvalue); 436 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL); 437 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 438 break; 439 case 'V': 440 if (argvalue == NULL) goto noarg; 441 printVars = TRUE; 442 (void)Lst_AtEnd(variables, argvalue); 443 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL); 444 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 445 break; 446 case 'W': 447 parseWarnFatal = TRUE; 448 break; 449 case 'X': 450 varNoExportEnv = TRUE; 451 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL); 452 break; 453 case 'd': 454 if (argvalue == NULL) goto noarg; 455 /* If '-d-opts' don't pass to children */ 456 if (argvalue[0] == '-') 457 argvalue++; 458 else { 459 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL); 460 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 461 } 462 parse_debug_options(argvalue); 463 break; 464 case 'e': 465 checkEnvFirst = TRUE; 466 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL); 467 break; 468 case 'f': 469 if (argvalue == NULL) goto noarg; 470 (void)Lst_AtEnd(makefiles, argvalue); 471 break; 472 case 'i': 473 ignoreErrors = TRUE; 474 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL); 475 break; 476 case 'j': 477 if (argvalue == NULL) goto noarg; 478 forceJobs = TRUE; 479 maxJobs = strtol(argvalue, &p, 0); 480 if (*p != '\0' || maxJobs < 1) { 481 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n", 482 progname); 483 exit(1); 484 } 485 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL); 486 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 487 maxJobTokens = maxJobs; 488 break; 489 case 'k': 490 keepgoing = TRUE; 491 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL); 492 break; 493 case 'm': 494 if (argvalue == NULL) goto noarg; 495 /* look for magic parent directory search string */ 496 if (strncmp(".../", argvalue, 4) == 0) { 497 if (!Dir_FindHereOrAbove(curdir, argvalue+4, 498 found_path, sizeof(found_path))) 499 break; /* nothing doing */ 500 (void)Dir_AddDir(sysIncPath, found_path); 501 502 } else { 503 (void)Dir_AddDir(sysIncPath, argvalue); 504 } 505 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL); 506 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL); 507 break; 508 case 'n': 509 noExecute = TRUE; 510 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL); 511 break; 512 case 'q': 513 queryFlag = TRUE; 514 /* Kind of nonsensical, wot? */ 515 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL); 516 break; 517 case 'r': 518 noBuiltins = TRUE; 519 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL); 520 break; 521 case 's': 522 beSilent = TRUE; 523 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL); 524 break; 525 case 't': 526 touchFlag = TRUE; 527 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL); 528 break; 529 case '-': 530 dashDash = TRUE; 531 break; 532 default: 533 case '?': 534 usage(); 535 } 536 argv += arginc; 537 argc -= arginc; 538 } 539 540 oldVars = TRUE; 541 542 /* 543 * See if the rest of the arguments are variable assignments and 544 * perform them if so. Else take them to be targets and stuff them 545 * on the end of the "create" list. 546 */ 547 for (; argc > 1; ++argv, --argc) 548 if (Parse_IsVar(argv[1])) { 549 Parse_DoVar(argv[1], VAR_CMD); 550 } else { 551 if (!*argv[1]) 552 Punt("illegal (null) argument."); 553 if (*argv[1] == '-' && !dashDash) 554 goto rearg; 555 (void)Lst_AtEnd(create, bmake_strdup(argv[1])); 556 } 557 558 return; 559 noarg: 560 (void)fprintf(stderr, "%s: option requires an argument -- %c\n", 561 progname, c); 562 usage(); 563 } 564 565 /*- 566 * Main_ParseArgLine -- 567 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target 568 * is encountered and by main() when reading the .MAKEFLAGS envariable. 569 * Takes a line of arguments and breaks it into its 570 * component words and passes those words and the number of them to the 571 * MainParseArgs function. 572 * The line should have all its leading whitespace removed. 573 * 574 * Input: 575 * line Line to fracture 576 * 577 * Results: 578 * None 579 * 580 * Side Effects: 581 * Only those that come from the various arguments. 582 */ 583 void 584 Main_ParseArgLine(char *line) 585 { 586 char **argv; /* Manufactured argument vector */ 587 int argc; /* Number of arguments in argv */ 588 char *args; /* Space used by the args */ 589 char *buf, *p1; 590 char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1); 591 size_t len; 592 593 if (line == NULL) 594 return; 595 for (; *line == ' '; ++line) 596 continue; 597 if (!*line) 598 return; 599 600 buf = bmake_malloc(len = strlen(line) + strlen(argv0) + 2); 601 (void)snprintf(buf, len, "%s %s", argv0, line); 602 if (p1) 603 free(p1); 604 605 argv = brk_string(buf, &argc, TRUE, &args); 606 if (argv == NULL) { 607 Error("Unterminated quoted string [%s]", buf); 608 free(buf); 609 return; 610 } 611 free(buf); 612 MainParseArgs(argc, argv); 613 614 free(args); 615 free(argv); 616 } 617 618 Boolean 619 Main_SetObjdir(const char *path) 620 { 621 struct stat sb; 622 char *p = NULL; 623 char buf[MAXPATHLEN + 1]; 624 Boolean rc = FALSE; 625 626 /* expand variable substitutions */ 627 if (strchr(path, '$') != 0) { 628 snprintf(buf, MAXPATHLEN, "%s", path); 629 path = p = Var_Subst(NULL, buf, VAR_GLOBAL, 0); 630 } 631 632 if (path[0] != '/') { 633 snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path); 634 path = buf; 635 } 636 637 /* look for the directory and try to chdir there */ 638 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) { 639 if (chdir(path)) { 640 (void)fprintf(stderr, "make warning: %s: %s.\n", 641 path, strerror(errno)); 642 } else { 643 strncpy(objdir, path, MAXPATHLEN); 644 Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0); 645 setenv("PWD", objdir, 1); 646 Dir_InitDot(); 647 rc = TRUE; 648 } 649 } 650 651 if (p) 652 free(p); 653 return rc; 654 } 655 656 /*- 657 * ReadAllMakefiles -- 658 * wrapper around ReadMakefile() to read all. 659 * 660 * Results: 661 * TRUE if ok, FALSE on error 662 */ 663 static int 664 ReadAllMakefiles(ClientData p, ClientData q) 665 { 666 return (ReadMakefile(p, q) == 0); 667 } 668 669 /*- 670 * main -- 671 * The main function, for obvious reasons. Initializes variables 672 * and a few modules, then parses the arguments give it in the 673 * environment and on the command line. Reads the system makefile 674 * followed by either Makefile, makefile or the file given by the 675 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the 676 * flags it has received by then uses either the Make or the Compat 677 * module to create the initial list of targets. 678 * 679 * Results: 680 * If -q was given, exits -1 if anything was out-of-date. Else it exits 681 * 0. 682 * 683 * Side Effects: 684 * The program exits when done. Targets are created. etc. etc. etc. 685 */ 686 int 687 main(int argc, char **argv) 688 { 689 Lst targs; /* target nodes to create -- passed to Make_Init */ 690 Boolean outOfDate = FALSE; /* FALSE if all targets up to date */ 691 struct stat sb, sa; 692 char *p1, *path, *pwd; 693 char mdpath[MAXPATHLEN]; 694 char *machine = getenv("MACHINE"); 695 const char *machine_arch = getenv("MACHINE_ARCH"); 696 char *syspath = getenv("MAKESYSPATH"); 697 Lst sysMkPath; /* Path of sys.mk */ 698 char *cp = NULL, *start; 699 /* avoid faults on read-only strings */ 700 static char defsyspath[] = _PATH_DEFSYSPATH; 701 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */ 702 struct timeval rightnow; /* to initialize random seed */ 703 #ifdef MAKE_NATIVE 704 struct utsname utsname; 705 #endif 706 707 /* default to writing debug to stderr */ 708 debug_file = stderr; 709 710 /* 711 * Set the seed to produce a different random sequence 712 * on each program execution. 713 */ 714 gettimeofday(&rightnow, NULL); 715 srandom(rightnow.tv_sec + rightnow.tv_usec); 716 717 if ((progname = strrchr(argv[0], '/')) != NULL) 718 progname++; 719 else 720 progname = argv[0]; 721 #ifdef RLIMIT_NOFILE 722 /* 723 * get rid of resource limit on file descriptors 724 */ 725 { 726 struct rlimit rl; 727 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 && 728 rl.rlim_cur != rl.rlim_max) { 729 rl.rlim_cur = rl.rlim_max; 730 (void)setrlimit(RLIMIT_NOFILE, &rl); 731 } 732 } 733 #endif 734 /* 735 * Find where we are and take care of PWD for the automounter... 736 * All this code is so that we know where we are when we start up 737 * on a different machine with pmake. 738 */ 739 if (getcwd(curdir, MAXPATHLEN) == NULL) { 740 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno)); 741 exit(2); 742 } 743 744 if (stat(curdir, &sa) == -1) { 745 (void)fprintf(stderr, "%s: %s: %s.\n", 746 progname, curdir, strerror(errno)); 747 exit(2); 748 } 749 750 /* 751 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX 752 * since the value of curdir can very depending on how we got 753 * here. Ie sitting at a shell prompt (shell that provides $PWD) 754 * or via subdir.mk in which case its likely a shell which does 755 * not provide it. 756 * So, to stop it breaking this case only, we ignore PWD if 757 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform. 758 */ 759 if ((pwd = getenv("PWD")) != NULL && getenv("MAKEOBJDIRPREFIX") == NULL) { 760 const char *makeobjdir = getenv("MAKEOBJDIR"); 761 762 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) { 763 if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino && 764 sa.st_dev == sb.st_dev) 765 (void)strncpy(curdir, pwd, MAXPATHLEN); 766 } 767 } 768 769 /* 770 * Get the name of this type of MACHINE from utsname 771 * so we can share an executable for similar machines. 772 * (i.e. m68k: amiga hp300, mac68k, sun3, ...) 773 * 774 * Note that both MACHINE and MACHINE_ARCH are decided at 775 * run-time. 776 */ 777 if (!machine) { 778 #ifdef MAKE_NATIVE 779 if (uname(&utsname) == -1) { 780 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname, 781 strerror(errno)); 782 exit(2); 783 } 784 machine = utsname.machine; 785 #else 786 #ifdef MAKE_MACHINE 787 machine = MAKE_MACHINE; 788 #else 789 machine = "unknown"; 790 #endif 791 #endif 792 } 793 794 if (!machine_arch) { 795 #ifndef MACHINE_ARCH 796 #ifdef MAKE_MACHINE_ARCH 797 machine_arch = MAKE_MACHINE_ARCH; 798 #else 799 machine_arch = "unknown"; 800 #endif 801 #else 802 machine_arch = MACHINE_ARCH; 803 #endif 804 } 805 806 /* 807 * Just in case MAKEOBJDIR wants us to do something tricky. 808 */ 809 Var_Init(); /* Initialize the lists of variables for 810 * parsing arguments */ 811 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0); 812 Var_Set("MACHINE", machine, VAR_GLOBAL, 0); 813 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0); 814 #ifdef MAKE_VERSION 815 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0); 816 #endif 817 Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */ 818 819 /* 820 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that, 821 * MAKEOBJDIR is set in the environment, try only that value 822 * and fall back to .CURDIR if it does not exist. 823 * 824 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and 825 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none 826 * of these paths exist, just use .CURDIR. 827 */ 828 Dir_Init(curdir); 829 (void)Main_SetObjdir(curdir); 830 831 if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) { 832 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir); 833 (void)Main_SetObjdir(mdpath); 834 } else if ((path = getenv("MAKEOBJDIR")) != NULL) { 835 (void)Main_SetObjdir(path); 836 } else { 837 (void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine); 838 if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) { 839 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", 840 _PATH_OBJDIRPREFIX, curdir); 841 (void)Main_SetObjdir(mdpath); 842 } 843 } 844 845 create = Lst_Init(FALSE); 846 makefiles = Lst_Init(FALSE); 847 printVars = FALSE; 848 variables = Lst_Init(FALSE); 849 beSilent = FALSE; /* Print commands as executed */ 850 ignoreErrors = FALSE; /* Pay attention to non-zero returns */ 851 noExecute = FALSE; /* Execute all commands */ 852 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */ 853 keepgoing = FALSE; /* Stop on error */ 854 allPrecious = FALSE; /* Remove targets when interrupted */ 855 queryFlag = FALSE; /* This is not just a check-run */ 856 noBuiltins = FALSE; /* Read the built-in rules */ 857 touchFlag = FALSE; /* Actually update targets */ 858 debug = 0; /* No debug verbosity, please. */ 859 jobsRunning = FALSE; 860 861 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */ 862 maxJobTokens = maxJobs; 863 compatMake = FALSE; /* No compat mode */ 864 865 866 /* 867 * Initialize the parsing, directory and variable modules to prepare 868 * for the reading of inclusion paths and variable settings on the 869 * command line 870 */ 871 872 /* 873 * Initialize various variables. 874 * MAKE also gets this name, for compatibility 875 * .MAKEFLAGS gets set to the empty string just in case. 876 * MFLAGS also gets initialized empty, for compatibility. 877 */ 878 Parse_Init(); 879 Var_Set("MAKE", argv[0], VAR_GLOBAL, 0); 880 Var_Set(".MAKE", argv[0], VAR_GLOBAL, 0); 881 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0); 882 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0); 883 Var_Set("MFLAGS", "", VAR_GLOBAL, 0); 884 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0); 885 886 /* 887 * Set some other useful macros 888 */ 889 { 890 char tmp[64]; 891 892 snprintf(tmp, sizeof(tmp), "%u", getpid()); 893 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0); 894 snprintf(tmp, sizeof(tmp), "%u", getppid()); 895 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0); 896 } 897 Job_SetPrefix(); 898 899 /* 900 * First snag any flags out of the MAKE environment variable. 901 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's 902 * in a different format). 903 */ 904 #ifdef POSIX 905 Main_ParseArgLine(getenv("MAKEFLAGS")); 906 #else 907 Main_ParseArgLine(getenv("MAKE")); 908 #endif 909 910 MainParseArgs(argc, argv); 911 912 /* 913 * Be compatible if user did not specify -j and did not explicitly 914 * turned compatibility on 915 */ 916 if (!compatMake && !forceJobs) { 917 compatMake = TRUE; 918 } 919 920 /* 921 * Initialize archive, target and suffix modules in preparation for 922 * parsing the makefile(s) 923 */ 924 Arch_Init(); 925 Targ_Init(); 926 Suff_Init(); 927 Trace_Init(tracefile); 928 929 DEFAULT = NULL; 930 (void)time(&now); 931 932 Trace_Log(MAKESTART, NULL); 933 934 /* 935 * Set up the .TARGETS variable to contain the list of targets to be 936 * created. If none specified, make the variable empty -- the parser 937 * will fill the thing in with the default or .MAIN target. 938 */ 939 if (!Lst_IsEmpty(create)) { 940 LstNode ln; 941 942 for (ln = Lst_First(create); ln != NULL; 943 ln = Lst_Succ(ln)) { 944 char *name = (char *)Lst_Datum(ln); 945 946 Var_Append(".TARGETS", name, VAR_GLOBAL); 947 } 948 } else 949 Var_Set(".TARGETS", "", VAR_GLOBAL, 0); 950 951 952 /* 953 * If no user-supplied system path was given (through the -m option) 954 * add the directories from the DEFSYSPATH (more than one may be given 955 * as dir1:...:dirn) to the system include path. 956 */ 957 if (syspath == NULL || *syspath == '\0') 958 syspath = defsyspath; 959 else 960 syspath = bmake_strdup(syspath); 961 962 for (start = syspath; *start != '\0'; start = cp) { 963 for (cp = start; *cp != '\0' && *cp != ':'; cp++) 964 continue; 965 if (*cp == ':') { 966 *cp++ = '\0'; 967 } 968 /* look for magic parent directory search string */ 969 if (strncmp(".../", start, 4) != 0) { 970 (void)Dir_AddDir(defIncPath, start); 971 } else { 972 if (Dir_FindHereOrAbove(curdir, start+4, 973 found_path, sizeof(found_path))) { 974 (void)Dir_AddDir(defIncPath, found_path); 975 } 976 } 977 } 978 if (syspath != defsyspath) 979 free(syspath); 980 981 /* 982 * Read in the built-in rules first, followed by the specified 983 * makefile, if it was (makefile != NULL), or the default 984 * makefile and Makefile, in that order, if it wasn't. 985 */ 986 if (!noBuiltins) { 987 LstNode ln; 988 989 sysMkPath = Lst_Init(FALSE); 990 Dir_Expand(_PATH_DEFSYSMK, 991 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath, 992 sysMkPath); 993 if (Lst_IsEmpty(sysMkPath)) 994 Fatal("%s: no system rules (%s).", progname, 995 _PATH_DEFSYSMK); 996 ln = Lst_Find(sysMkPath, NULL, ReadMakefile); 997 if (ln == NULL) 998 Fatal("%s: cannot open %s.", progname, 999 (char *)Lst_Datum(ln)); 1000 } 1001 1002 if (!Lst_IsEmpty(makefiles)) { 1003 LstNode ln; 1004 1005 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles); 1006 if (ln != NULL) 1007 Fatal("%s: cannot open %s.", progname, 1008 (char *)Lst_Datum(ln)); 1009 } else if (ReadMakefile(UNCONST("makefile"), NULL) != 0) 1010 (void)ReadMakefile(UNCONST("Makefile"), NULL); 1011 1012 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */ 1013 if (!noBuiltins || !printVars) { 1014 doing_depend = TRUE; 1015 (void)ReadMakefile(UNCONST(".depend"), NULL); 1016 doing_depend = FALSE; 1017 } 1018 1019 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL); 1020 if (p1) 1021 free(p1); 1022 1023 if (!compatMake) 1024 Job_ServerStart(maxJobTokens, jp_0, jp_1); 1025 if (DEBUG(JOB)) 1026 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n", 1027 jp_0, jp_1, maxJobs, maxJobTokens, compatMake); 1028 1029 Main_ExportMAKEFLAGS(TRUE); /* initial export */ 1030 1031 Check_Cwd_av(0, NULL, 0); /* initialize it */ 1032 1033 1034 /* 1035 * For compatibility, look at the directories in the VPATH variable 1036 * and add them to the search path, if the variable is defined. The 1037 * variable's value is in the same format as the PATH envariable, i.e. 1038 * <directory>:<directory>:<directory>... 1039 */ 1040 if (Var_Exists("VPATH", VAR_CMD)) { 1041 char *vpath, savec; 1042 /* 1043 * GCC stores string constants in read-only memory, but 1044 * Var_Subst will want to write this thing, so store it 1045 * in an array 1046 */ 1047 static char VPATH[] = "${VPATH}"; 1048 1049 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE); 1050 path = vpath; 1051 do { 1052 /* skip to end of directory */ 1053 for (cp = path; *cp != ':' && *cp != '\0'; cp++) 1054 continue; 1055 /* Save terminator character so know when to stop */ 1056 savec = *cp; 1057 *cp = '\0'; 1058 /* Add directory to search path */ 1059 (void)Dir_AddDir(dirSearchPath, path); 1060 *cp = savec; 1061 path = cp + 1; 1062 } while (savec == ':'); 1063 free(vpath); 1064 } 1065 1066 /* 1067 * Now that all search paths have been read for suffixes et al, it's 1068 * time to add the default search path to their lists... 1069 */ 1070 Suff_DoPaths(); 1071 1072 /* 1073 * Propagate attributes through :: dependency lists. 1074 */ 1075 Targ_Propagate(); 1076 1077 /* print the initial graph, if the user requested it */ 1078 if (DEBUG(GRAPH1)) 1079 Targ_PrintGraph(1); 1080 1081 /* print the values of any variables requested by the user */ 1082 if (printVars) { 1083 LstNode ln; 1084 1085 for (ln = Lst_First(variables); ln != NULL; 1086 ln = Lst_Succ(ln)) { 1087 char *var = (char *)Lst_Datum(ln); 1088 char *value; 1089 1090 if (strchr(var, '$')) { 1091 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0); 1092 } else { 1093 value = Var_Value(var, VAR_GLOBAL, &p1); 1094 } 1095 printf("%s\n", value ? value : ""); 1096 if (p1) 1097 free(p1); 1098 } 1099 } else { 1100 /* 1101 * Have now read the entire graph and need to make a list of 1102 * targets to create. If none was given on the command line, 1103 * we consult the parsing module to find the main target(s) 1104 * to create. 1105 */ 1106 if (Lst_IsEmpty(create)) 1107 targs = Parse_MainName(); 1108 else 1109 targs = Targ_FindList(create, TARG_CREATE); 1110 1111 if (!compatMake) { 1112 /* 1113 * Initialize job module before traversing the graph 1114 * now that any .BEGIN and .END targets have been read. 1115 * This is done only if the -q flag wasn't given 1116 * (to prevent the .BEGIN from being executed should 1117 * it exist). 1118 */ 1119 if (!queryFlag) { 1120 Job_Init(); 1121 jobsRunning = TRUE; 1122 } 1123 1124 /* Traverse the graph, checking on all the targets */ 1125 outOfDate = Make_Run(targs); 1126 } else { 1127 /* 1128 * Compat_Init will take care of creating all the 1129 * targets as well as initializing the module. 1130 */ 1131 Compat_Run(targs); 1132 } 1133 } 1134 1135 #ifdef CLEANUP 1136 Lst_Destroy(targs, NULL); 1137 Lst_Destroy(variables, NULL); 1138 Lst_Destroy(makefiles, NULL); 1139 Lst_Destroy(create, (FreeProc *)free); 1140 #endif 1141 1142 /* print the graph now it's been processed if the user requested it */ 1143 if (DEBUG(GRAPH2)) 1144 Targ_PrintGraph(2); 1145 1146 Trace_Log(MAKEEND, 0); 1147 1148 Suff_End(); 1149 Targ_End(); 1150 Arch_End(); 1151 Var_End(); 1152 Parse_End(); 1153 Dir_End(); 1154 Job_End(); 1155 Trace_End(); 1156 1157 return outOfDate ? 1 : 0; 1158 } 1159 1160 /*- 1161 * ReadMakefile -- 1162 * Open and parse the given makefile. 1163 * 1164 * Results: 1165 * 0 if ok. -1 if couldn't open file. 1166 * 1167 * Side Effects: 1168 * lots 1169 */ 1170 static int 1171 ReadMakefile(ClientData p, ClientData q __unused) 1172 { 1173 char *fname = p; /* makefile to read */ 1174 int fd; 1175 size_t len = MAXPATHLEN; 1176 char *name, *path = bmake_malloc(len); 1177 int setMAKEFILE; 1178 1179 if (!strcmp(fname, "-")) { 1180 Parse_File("(stdin)", dup(fileno(stdin))); 1181 Var_Set("MAKEFILE", "", VAR_GLOBAL, 0); 1182 } else { 1183 setMAKEFILE = strcmp(fname, ".depend"); 1184 1185 /* if we've chdir'd, rebuild the path name */ 1186 if (strcmp(curdir, objdir) && *fname != '/') { 1187 size_t plen = strlen(curdir) + strlen(fname) + 2; 1188 if (len < plen) 1189 path = bmake_realloc(path, len = 2 * plen); 1190 1191 (void)snprintf(path, len, "%s/%s", curdir, fname); 1192 fd = open(path, O_RDONLY); 1193 if (fd != -1) { 1194 fname = path; 1195 goto found; 1196 } 1197 1198 /* If curdir failed, try objdir (ala .depend) */ 1199 plen = strlen(objdir) + strlen(fname) + 2; 1200 if (len < plen) 1201 path = bmake_realloc(path, len = 2 * plen); 1202 (void)snprintf(path, len, "%s/%s", objdir, fname); 1203 fd = open(path, O_RDONLY); 1204 if (fd != -1) { 1205 fname = path; 1206 goto found; 1207 } 1208 } else { 1209 fd = open(fname, O_RDONLY); 1210 if (fd != -1) 1211 goto found; 1212 } 1213 /* look in -I and system include directories. */ 1214 name = Dir_FindFile(fname, parseIncPath); 1215 if (!name) 1216 name = Dir_FindFile(fname, 1217 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath); 1218 if (!name || (fd = open(name, O_RDONLY)) == -1) { 1219 if (name) 1220 free(name); 1221 free(path); 1222 return(-1); 1223 } 1224 fname = name; 1225 /* 1226 * set the MAKEFILE variable desired by System V fans -- the 1227 * placement of the setting here means it gets set to the last 1228 * makefile specified, as it is set by SysV make. 1229 */ 1230 found: 1231 if (setMAKEFILE) 1232 Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0); 1233 Parse_File(fname, fd); 1234 } 1235 free(path); 1236 return(0); 1237 } 1238 1239 1240 /* 1241 * If MAKEOBJDIRPREFIX is in use, make ends up not in .CURDIR 1242 * in situations that would not arrise with ./obj (links or not). 1243 * This tends to break things like: 1244 * 1245 * build: 1246 * ${MAKE} includes 1247 * 1248 * This function spots when ${.MAKE:T} or ${.MAKE} is a command (as 1249 * opposed to an argument) in a command line and if so returns 1250 * ${.CURDIR} so caller can chdir() so that the assumptions made by 1251 * the Makefile hold true. 1252 * 1253 * If ${.MAKE} does not contain any '/', then ${.MAKE:T} is skipped. 1254 * 1255 * The chdir() only happens in the child process, and does nothing if 1256 * MAKEOBJDIRPREFIX and MAKEOBJDIR are not in the environment so it 1257 * should not break anything. Also if NOCHECKMAKECHDIR is set we 1258 * do nothing - to ensure historic semantics can be retained. 1259 */ 1260 static int Check_Cwd_Off = 0; 1261 1262 static char * 1263 Check_Cwd_av(int ac, char **av, int copy) 1264 { 1265 static char *make[4]; 1266 static char *cur_dir = NULL; 1267 char **mp; 1268 char *cp; 1269 int is_cmd, next_cmd; 1270 int i; 1271 int n; 1272 1273 if (Check_Cwd_Off) { 1274 if (DEBUG(CWD)) 1275 fprintf(debug_file, "check_cwd: check is off.\n"); 1276 return NULL; 1277 } 1278 1279 if (make[0] == NULL) { 1280 if (Var_Exists("NOCHECKMAKECHDIR", VAR_GLOBAL)) { 1281 Check_Cwd_Off = 1; 1282 if (DEBUG(CWD)) 1283 fprintf(debug_file, "check_cwd: turning check off.\n"); 1284 return NULL; 1285 } 1286 1287 make[1] = Var_Value(".MAKE", VAR_GLOBAL, &cp); 1288 if ((make[0] = strrchr(make[1], '/')) == NULL) { 1289 make[0] = make[1]; 1290 make[1] = NULL; 1291 } else 1292 ++make[0]; 1293 make[2] = NULL; 1294 cur_dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp); 1295 } 1296 if (ac == 0 || av == NULL) { 1297 if (DEBUG(CWD)) 1298 fprintf(debug_file, "check_cwd: empty command.\n"); 1299 return NULL; /* initialization only */ 1300 } 1301 1302 if (getenv("MAKEOBJDIR") == NULL && 1303 getenv("MAKEOBJDIRPREFIX") == NULL) { 1304 if (DEBUG(CWD)) 1305 fprintf(debug_file, "check_cwd: no obj dirs.\n"); 1306 return NULL; 1307 } 1308 1309 1310 next_cmd = 1; 1311 for (i = 0; i < ac; ++i) { 1312 is_cmd = next_cmd; 1313 1314 n = strlen(av[i]); 1315 cp = &(av[i])[n - 1]; 1316 if (strspn(av[i], "|&;") == (size_t)n) { 1317 next_cmd = 1; 1318 continue; 1319 } else if (*cp == ';' || *cp == '&' || *cp == '|' || *cp == ')') { 1320 next_cmd = 1; 1321 if (copy) { 1322 do { 1323 *cp-- = '\0'; 1324 } while (*cp == ';' || *cp == '&' || *cp == '|' || 1325 *cp == ')' || *cp == '}') ; 1326 } else { 1327 /* 1328 * XXX this should not happen. 1329 */ 1330 fprintf(stderr, "%s: WARNING: raw arg ends in shell meta '%s'\n", 1331 progname, av[i]); 1332 } 1333 } else 1334 next_cmd = 0; 1335 1336 cp = av[i]; 1337 if (*cp == ';' || *cp == '&' || *cp == '|') 1338 is_cmd = 1; 1339 1340 if (DEBUG(CWD)) 1341 fprintf(debug_file, "av[%d] == %s '%s'", 1342 i, (is_cmd) ? "cmd" : "arg", av[i]); 1343 if (is_cmd != 0) { 1344 if (*cp == '(' || *cp == '{' || 1345 *cp == ';' || *cp == '&' || *cp == '|') { 1346 do { 1347 ++cp; 1348 } while (*cp == '(' || *cp == '{' || 1349 *cp == ';' || *cp == '&' || *cp == '|'); 1350 if (*cp == '\0') { 1351 next_cmd = 1; 1352 continue; 1353 } 1354 } 1355 if (strcmp(cp, "cd") == 0 || strcmp(cp, "chdir") == 0) { 1356 if (DEBUG(CWD)) 1357 fprintf(debug_file, " == cd, done.\n"); 1358 return NULL; 1359 } 1360 for (mp = make; *mp != NULL; ++mp) { 1361 n = strlen(*mp); 1362 if (strcmp(cp, *mp) == 0) { 1363 if (DEBUG(CWD)) 1364 fprintf(debug_file, " %s == '%s', chdir(%s)\n", 1365 cp, *mp, cur_dir); 1366 return cur_dir; 1367 } 1368 } 1369 } 1370 if (DEBUG(CWD)) 1371 fprintf(debug_file, "\n"); 1372 } 1373 return NULL; 1374 } 1375 1376 char * 1377 Check_Cwd_Cmd(const char *cmd) 1378 { 1379 char *cp, *bp; 1380 char **av; 1381 int ac; 1382 1383 if (Check_Cwd_Off) 1384 return NULL; 1385 1386 if (cmd) { 1387 av = brk_string(cmd, &ac, TRUE, &bp); 1388 if (DEBUG(CWD)) 1389 fprintf(debug_file, "splitting: '%s' -> %d words\n", 1390 cmd, ac); 1391 } else { 1392 ac = 0; 1393 av = NULL; 1394 bp = NULL; 1395 } 1396 cp = Check_Cwd_av(ac, av, 1); 1397 if (bp) 1398 free(bp); 1399 if (av) 1400 free(av); 1401 return cp; 1402 } 1403 1404 void 1405 Check_Cwd(const char **argv) 1406 { 1407 char *cp; 1408 int ac; 1409 1410 if (Check_Cwd_Off) 1411 return; 1412 1413 for (ac = 0; argv[ac] != NULL; ++ac) 1414 /* NOTHING */; 1415 if (ac == 3 && *argv[1] == '-') { 1416 cp = Check_Cwd_Cmd(argv[2]); 1417 } else { 1418 cp = Check_Cwd_av(ac, UNCONST(argv), 0); 1419 } 1420 if (cp) { 1421 chdir(cp); 1422 } 1423 } 1424 1425 /*- 1426 * Cmd_Exec -- 1427 * Execute the command in cmd, and return the output of that command 1428 * in a string. 1429 * 1430 * Results: 1431 * A string containing the output of the command, or the empty string 1432 * If errnum is not NULL, it contains the reason for the command failure 1433 * 1434 * Side Effects: 1435 * The string must be freed by the caller. 1436 */ 1437 char * 1438 Cmd_Exec(const char *cmd, const char **errnum) 1439 { 1440 const char *args[4]; /* Args for invoking the shell */ 1441 int fds[2]; /* Pipe streams */ 1442 int cpid; /* Child PID */ 1443 int pid; /* PID from wait() */ 1444 char *res; /* result */ 1445 int status; /* command exit status */ 1446 Buffer buf; /* buffer to store the result */ 1447 char *cp; 1448 int cc; 1449 1450 1451 *errnum = NULL; 1452 1453 if (!shellName) 1454 Shell_Init(); 1455 /* 1456 * Set up arguments for shell 1457 */ 1458 args[0] = shellName; 1459 args[1] = "-c"; 1460 args[2] = cmd; 1461 args[3] = NULL; 1462 1463 /* 1464 * Open a pipe for fetching its output 1465 */ 1466 if (pipe(fds) == -1) { 1467 *errnum = "Couldn't create pipe for \"%s\""; 1468 goto bad; 1469 } 1470 1471 /* 1472 * Fork 1473 */ 1474 switch (cpid = vfork()) { 1475 case 0: 1476 /* 1477 * Close input side of pipe 1478 */ 1479 (void)close(fds[0]); 1480 1481 /* 1482 * Duplicate the output stream to the shell's output, then 1483 * shut the extra thing down. Note we don't fetch the error 1484 * stream...why not? Why? 1485 */ 1486 (void)dup2(fds[1], 1); 1487 (void)close(fds[1]); 1488 1489 Var_ExportVars(); 1490 1491 (void)execv(shellPath, UNCONST(args)); 1492 _exit(1); 1493 /*NOTREACHED*/ 1494 1495 case -1: 1496 *errnum = "Couldn't exec \"%s\""; 1497 goto bad; 1498 1499 default: 1500 /* 1501 * No need for the writing half 1502 */ 1503 (void)close(fds[1]); 1504 1505 buf = Buf_Init(0); 1506 1507 do { 1508 char result[BUFSIZ]; 1509 cc = read(fds[0], result, sizeof(result)); 1510 if (cc > 0) 1511 Buf_AddBytes(buf, cc, (Byte *)result); 1512 } 1513 while (cc > 0 || (cc == -1 && errno == EINTR)); 1514 1515 /* 1516 * Close the input side of the pipe. 1517 */ 1518 (void)close(fds[0]); 1519 1520 /* 1521 * Wait for the process to exit. 1522 */ 1523 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) 1524 continue; 1525 1526 res = (char *)Buf_GetAll(buf, &cc); 1527 Buf_Destroy(buf, FALSE); 1528 1529 if (cc == 0) 1530 *errnum = "Couldn't read shell's output for \"%s\""; 1531 1532 if (status) 1533 *errnum = "\"%s\" returned non-zero status"; 1534 1535 /* 1536 * Null-terminate the result, convert newlines to spaces and 1537 * install it in the variable. 1538 */ 1539 res[cc] = '\0'; 1540 cp = &res[cc]; 1541 1542 if (cc > 0 && *--cp == '\n') { 1543 /* 1544 * A final newline is just stripped 1545 */ 1546 *cp-- = '\0'; 1547 } 1548 while (cp >= res) { 1549 if (*cp == '\n') { 1550 *cp = ' '; 1551 } 1552 cp--; 1553 } 1554 break; 1555 } 1556 return res; 1557 bad: 1558 res = bmake_malloc(1); 1559 *res = '\0'; 1560 return res; 1561 } 1562 1563 /*- 1564 * Error -- 1565 * Print an error message given its format. 1566 * 1567 * Results: 1568 * None. 1569 * 1570 * Side Effects: 1571 * The message is printed. 1572 */ 1573 /* VARARGS */ 1574 void 1575 Error(const char *fmt, ...) 1576 { 1577 va_list ap; 1578 1579 va_start(ap, fmt); 1580 fprintf(stderr, "%s: ", progname); 1581 (void)vfprintf(stderr, fmt, ap); 1582 va_end(ap); 1583 (void)fprintf(stderr, "\n"); 1584 (void)fflush(stderr); 1585 } 1586 1587 /*- 1588 * Fatal -- 1589 * Produce a Fatal error message. If jobs are running, waits for them 1590 * to finish. 1591 * 1592 * Results: 1593 * None 1594 * 1595 * Side Effects: 1596 * The program exits 1597 */ 1598 /* VARARGS */ 1599 void 1600 Fatal(const char *fmt, ...) 1601 { 1602 va_list ap; 1603 1604 va_start(ap, fmt); 1605 if (jobsRunning) 1606 Job_Wait(); 1607 1608 (void)vfprintf(stderr, fmt, ap); 1609 va_end(ap); 1610 (void)fprintf(stderr, "\n"); 1611 (void)fflush(stderr); 1612 1613 PrintOnError(NULL); 1614 1615 if (DEBUG(GRAPH2) || DEBUG(GRAPH3)) 1616 Targ_PrintGraph(2); 1617 Trace_Log(MAKEERROR, 0); 1618 exit(2); /* Not 1 so -q can distinguish error */ 1619 } 1620 1621 /* 1622 * Punt -- 1623 * Major exception once jobs are being created. Kills all jobs, prints 1624 * a message and exits. 1625 * 1626 * Results: 1627 * None 1628 * 1629 * Side Effects: 1630 * All children are killed indiscriminately and the program Lib_Exits 1631 */ 1632 /* VARARGS */ 1633 void 1634 Punt(const char *fmt, ...) 1635 { 1636 va_list ap; 1637 1638 va_start(ap, fmt); 1639 (void)fprintf(stderr, "%s: ", progname); 1640 (void)vfprintf(stderr, fmt, ap); 1641 va_end(ap); 1642 (void)fprintf(stderr, "\n"); 1643 (void)fflush(stderr); 1644 1645 PrintOnError(NULL); 1646 1647 DieHorribly(); 1648 } 1649 1650 /*- 1651 * DieHorribly -- 1652 * Exit without giving a message. 1653 * 1654 * Results: 1655 * None 1656 * 1657 * Side Effects: 1658 * A big one... 1659 */ 1660 void 1661 DieHorribly(void) 1662 { 1663 if (jobsRunning) 1664 Job_AbortAll(); 1665 if (DEBUG(GRAPH2)) 1666 Targ_PrintGraph(2); 1667 Trace_Log(MAKEERROR, 0); 1668 exit(2); /* Not 1, so -q can distinguish error */ 1669 } 1670 1671 /* 1672 * Finish -- 1673 * Called when aborting due to errors in child shell to signal 1674 * abnormal exit. 1675 * 1676 * Results: 1677 * None 1678 * 1679 * Side Effects: 1680 * The program exits 1681 */ 1682 void 1683 Finish(int errors) 1684 /* number of errors encountered in Make_Make */ 1685 { 1686 Fatal("%d error%s", errors, errors == 1 ? "" : "s"); 1687 } 1688 1689 #ifndef USE_EMALLOC 1690 /* 1691 * enomem -- 1692 * die when out of memory. 1693 */ 1694 static void 1695 enomem(void) 1696 { 1697 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno)); 1698 exit(2); 1699 } 1700 1701 /* 1702 * bmake_malloc -- 1703 * malloc, but die on error. 1704 */ 1705 void * 1706 bmake_malloc(size_t len) 1707 { 1708 void *p; 1709 1710 if ((p = malloc(len)) == NULL) 1711 enomem(); 1712 return(p); 1713 } 1714 1715 /* 1716 * bmake_strdup -- 1717 * strdup, but die on error. 1718 */ 1719 char * 1720 bmake_strdup(const char *str) 1721 { 1722 size_t len; 1723 char *p; 1724 1725 len = strlen(str) + 1; 1726 if ((p = malloc(len)) == NULL) 1727 enomem(); 1728 return memcpy(p, str, len); 1729 } 1730 1731 /* 1732 * bmake_strndup -- 1733 * strndup, but die on error. 1734 */ 1735 char * 1736 bmake_strndup(const char *str, size_t max_len) 1737 { 1738 size_t len; 1739 char *p; 1740 1741 if (str == NULL) 1742 return NULL; 1743 1744 len = strlen(str); 1745 if (len > max_len) 1746 len = max_len; 1747 p = bmake_malloc(len + 1); 1748 memcpy(p, str, len); 1749 p[len] = '\0'; 1750 1751 return(p); 1752 } 1753 1754 /* 1755 * bmake_realloc -- 1756 * realloc, but die on error. 1757 */ 1758 void * 1759 bmake_realloc(void *ptr, size_t size) 1760 { 1761 if ((ptr = realloc(ptr, size)) == NULL) 1762 enomem(); 1763 return(ptr); 1764 } 1765 #endif 1766 1767 /* 1768 * enunlink -- 1769 * Remove a file carefully, avoiding directories. 1770 */ 1771 int 1772 eunlink(const char *file) 1773 { 1774 struct stat st; 1775 1776 if (lstat(file, &st) == -1) 1777 return -1; 1778 1779 if (S_ISDIR(st.st_mode)) { 1780 errno = EISDIR; 1781 return -1; 1782 } 1783 return unlink(file); 1784 } 1785 1786 /* 1787 * execError -- 1788 * Print why exec failed, avoiding stdio. 1789 */ 1790 void 1791 execError(const char *af, const char *av) 1792 { 1793 #ifdef USE_IOVEC 1794 int i = 0; 1795 struct iovec iov[8]; 1796 #define IOADD(s) \ 1797 (void)(iov[i].iov_base = UNCONST(s), \ 1798 iov[i].iov_len = strlen(iov[i].iov_base), \ 1799 i++) 1800 #else 1801 #define IOADD(void)write(2, s, strlen(s)) 1802 #endif 1803 1804 IOADD(progname); 1805 IOADD(": "); 1806 IOADD(af); 1807 IOADD("("); 1808 IOADD(av); 1809 IOADD(") failed ("); 1810 IOADD(strerror(errno)); 1811 IOADD(")\n"); 1812 1813 #ifdef USE_IOVEC 1814 (void)writev(2, iov, 8); 1815 #endif 1816 } 1817 1818 /* 1819 * usage -- 1820 * exit with usage message 1821 */ 1822 static void 1823 usage(void) 1824 { 1825 (void)fprintf(stderr, 1826 "usage: %s [-BeikNnqrstWX] [-D variable] [-d flags] [-f makefile]\n\ 1827 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\ 1828 [-V variable] [variable=value] [target ...]\n", progname); 1829 exit(2); 1830 } 1831 1832 1833 int 1834 PrintAddr(ClientData a, ClientData b) 1835 { 1836 printf("%lx ", (unsigned long) a); 1837 return b ? 0 : 0; 1838 } 1839 1840 1841 1842 void 1843 PrintOnError(const char *s) 1844 { 1845 char tmp[64]; 1846 char *cp; 1847 1848 if (s) 1849 printf("%s", s); 1850 1851 printf("\n%s: stopped in %s\n", progname, curdir); 1852 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}", 1853 sizeof(tmp) - 1); 1854 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0); 1855 if (cp) { 1856 if (*cp) 1857 printf("%s", cp); 1858 free(cp); 1859 } 1860 } 1861 1862 void 1863 Main_ExportMAKEFLAGS(Boolean first) 1864 { 1865 static int once = 1; 1866 char tmp[64]; 1867 char *s; 1868 1869 if (once != first) 1870 return; 1871 once = 0; 1872 1873 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}", 1874 sizeof(tmp)); 1875 s = Var_Subst(NULL, tmp, VAR_CMD, 0); 1876 if (s && *s) { 1877 #ifdef POSIX 1878 setenv("MAKEFLAGS", s, 1); 1879 #else 1880 setenv("MAKE", s, 1); 1881 #endif 1882 } 1883 } 1884