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