1 /* $NetBSD: parse.c,v 1.738 2025/01/14 21:34:09 rillig 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 /* 72 * Parsing of makefiles. 73 * 74 * Parse_File is the main entry point and controls most of the other 75 * functions in this module. 76 * 77 * Interface: 78 * Parse_Init Initialize the module 79 * 80 * Parse_End Clean up the module 81 * 82 * Parse_File Parse a top-level makefile. Included files are 83 * handled by IncludeFile instead. 84 * 85 * Parse_VarAssign 86 * Try to parse the given line as a variable assignment. 87 * Used by MainParseArgs to determine if an argument is 88 * a target or a variable assignment. Used internally 89 * for pretty much the same thing. 90 * 91 * Parse_Error Report a parse error, a warning or an informational 92 * message. 93 * 94 * Parse_MainName Populate the list of targets to create. 95 */ 96 97 #include <sys/types.h> 98 #include <sys/stat.h> 99 #include <errno.h> 100 #include <stdarg.h> 101 102 #include "make.h" 103 104 #ifdef HAVE_STDINT_H 105 #include <stdint.h> 106 #endif 107 108 #include "dir.h" 109 #include "job.h" 110 #include "pathnames.h" 111 112 /* "@(#)parse.c 8.3 (Berkeley) 3/19/94" */ 113 MAKE_RCSID("$NetBSD: parse.c,v 1.738 2025/01/14 21:34:09 rillig Exp $"); 114 115 /* Detects a multiple-inclusion guard in a makefile. */ 116 typedef enum { 117 GS_START, /* at the beginning of the file */ 118 GS_COND, /* after the guard condition */ 119 GS_DONE, /* after the closing .endif */ 120 GS_NO /* the file is not guarded */ 121 } GuardState; 122 123 /* A file being parsed. */ 124 typedef struct IncludedFile { 125 FStr name; /* absolute or relative to the cwd */ 126 unsigned lineno; /* 1-based */ 127 unsigned readLines; /* the number of physical lines that have 128 * been read from the file */ 129 unsigned forHeadLineno; /* 1-based */ 130 unsigned forBodyReadLines; /* the number of physical lines that have 131 * been read from the file above the body of 132 * the .for loop */ 133 unsigned int condMinDepth; /* depth of nested 'if' directives, at the 134 * beginning of the file */ 135 bool depending; /* state of doing_depend on EOF */ 136 137 Buffer buf; /* the file's content or the body of the .for 138 * loop; either empty or ends with '\n' */ 139 char *buf_ptr; /* next char to be read from buf */ 140 char *buf_end; /* buf_end[-1] == '\n' */ 141 142 GuardState guardState; 143 Guard *guard; 144 145 struct ForLoop *forLoop; 146 } IncludedFile; 147 148 /* Special attributes for target nodes. */ 149 typedef enum ParseSpecial { 150 SP_ATTRIBUTE, /* Generic attribute */ 151 SP_BEGIN, /* .BEGIN */ 152 SP_DEFAULT, /* .DEFAULT */ 153 SP_DELETE_ON_ERROR, /* .DELETE_ON_ERROR */ 154 SP_END, /* .END */ 155 SP_ERROR, /* .ERROR */ 156 SP_IGNORE, /* .IGNORE */ 157 SP_INCLUDES, /* .INCLUDES; not mentioned in the manual page */ 158 SP_INTERRUPT, /* .INTERRUPT */ 159 SP_LIBS, /* .LIBS; not mentioned in the manual page */ 160 SP_MAIN, /* .MAIN and no user-specified targets to make */ 161 SP_META, /* .META */ 162 SP_MFLAGS, /* .MFLAGS or .MAKEFLAGS */ 163 SP_NOMETA, /* .NOMETA */ 164 SP_NOMETA_CMP, /* .NOMETA_CMP */ 165 SP_NOPATH, /* .NOPATH */ 166 SP_NOREADONLY, /* .NOREADONLY */ 167 SP_NOT, /* Not special */ 168 SP_NOTPARALLEL, /* .NOTPARALLEL or .NO_PARALLEL */ 169 SP_NULL, /* .NULL; not mentioned in the manual page */ 170 SP_OBJDIR, /* .OBJDIR */ 171 SP_ORDER, /* .ORDER */ 172 SP_PARALLEL, /* .PARALLEL; not mentioned in the manual page */ 173 SP_PATH, /* .PATH or .PATH.suffix */ 174 SP_PHONY, /* .PHONY */ 175 SP_POSIX, /* .POSIX; not mentioned in the manual page */ 176 SP_PRECIOUS, /* .PRECIOUS */ 177 SP_READONLY, /* .READONLY */ 178 SP_SHELL, /* .SHELL */ 179 SP_SILENT, /* .SILENT */ 180 SP_SINGLESHELL, /* .SINGLESHELL; not mentioned in the manual page */ 181 SP_STALE, /* .STALE */ 182 SP_SUFFIXES, /* .SUFFIXES */ 183 SP_SYSPATH, /* .SYSPATH */ 184 SP_WAIT /* .WAIT */ 185 } ParseSpecial; 186 187 typedef List SearchPathList; 188 typedef ListNode SearchPathListNode; 189 190 191 typedef enum VarAssignOp { 192 VAR_NORMAL, /* = */ 193 VAR_APPEND, /* += */ 194 VAR_DEFAULT, /* ?= */ 195 VAR_SUBST, /* := */ 196 VAR_SHELL /* != or :sh= */ 197 } VarAssignOp; 198 199 typedef struct VarAssign { 200 char *varname; /* unexpanded */ 201 VarAssignOp op; 202 const char *value; /* unexpanded */ 203 } VarAssign; 204 205 static bool Parse_IsVar(const char *, VarAssign *); 206 static void Parse_Var(VarAssign *, GNode *); 207 208 /* 209 * The target to be made if no targets are specified in the command line. 210 * This is the first target defined in any of the makefiles. 211 */ 212 GNode *mainNode; 213 214 /* 215 * During parsing, the targets from the left-hand side of the currently 216 * active dependency line, or NULL if the current line does not belong to a 217 * dependency line, for example because it is a variable assignment. 218 * 219 * See unit-tests/deptgt.mk, keyword "parse.c:targets". 220 */ 221 static GNodeList *targets; 222 223 #ifdef CLEANUP 224 /* 225 * All shell commands for all targets, in no particular order and possibly 226 * with duplicate values. Kept in a separate list since the commands from 227 * .USE or .USEBEFORE nodes are shared with other GNodes, thereby giving up 228 * the easily understandable ownership over the allocated strings. 229 */ 230 static StringList targCmds = LST_INIT; 231 #endif 232 233 /* 234 * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER 235 * is seen, then set to each successive source on the line. 236 */ 237 static GNode *order_pred; 238 239 int parseErrors; 240 241 /* 242 * The include chain of makefiles. At index 0 is the top-level makefile from 243 * the command line, followed by the included files or .for loops, up to and 244 * including the current file. 245 * 246 * See PrintStackTrace for how to interpret the data. 247 */ 248 static Vector /* of IncludedFile */ includes; 249 250 SearchPath *parseIncPath; /* directories for "..." includes */ 251 SearchPath *sysIncPath; /* directories for <...> includes */ 252 SearchPath *defSysIncPath; /* default for sysIncPath */ 253 254 /* 255 * The parseKeywords table is searched using binary search when deciding 256 * if a target or source is special. 257 */ 258 static const struct { 259 const char name[17]; 260 ParseSpecial special; /* when used as a target */ 261 GNodeType targetAttr; /* when used as a source */ 262 } parseKeywords[] = { 263 { ".BEGIN", SP_BEGIN, OP_NONE }, 264 { ".DEFAULT", SP_DEFAULT, OP_NONE }, 265 { ".DELETE_ON_ERROR", SP_DELETE_ON_ERROR, OP_NONE }, 266 { ".END", SP_END, OP_NONE }, 267 { ".ERROR", SP_ERROR, OP_NONE }, 268 { ".EXEC", SP_ATTRIBUTE, OP_EXEC }, 269 { ".IGNORE", SP_IGNORE, OP_IGNORE }, 270 { ".INCLUDES", SP_INCLUDES, OP_NONE }, 271 { ".INTERRUPT", SP_INTERRUPT, OP_NONE }, 272 { ".INVISIBLE", SP_ATTRIBUTE, OP_INVISIBLE }, 273 { ".JOIN", SP_ATTRIBUTE, OP_JOIN }, 274 { ".LIBS", SP_LIBS, OP_NONE }, 275 { ".MADE", SP_ATTRIBUTE, OP_MADE }, 276 { ".MAIN", SP_MAIN, OP_NONE }, 277 { ".MAKE", SP_ATTRIBUTE, OP_MAKE }, 278 { ".MAKEFLAGS", SP_MFLAGS, OP_NONE }, 279 { ".META", SP_META, OP_META }, 280 { ".MFLAGS", SP_MFLAGS, OP_NONE }, 281 { ".NOMETA", SP_NOMETA, OP_NOMETA }, 282 { ".NOMETA_CMP", SP_NOMETA_CMP, OP_NOMETA_CMP }, 283 { ".NOPATH", SP_NOPATH, OP_NOPATH }, 284 { ".NOREADONLY", SP_NOREADONLY, OP_NONE }, 285 { ".NOTMAIN", SP_ATTRIBUTE, OP_NOTMAIN }, 286 { ".NOTPARALLEL", SP_NOTPARALLEL, OP_NONE }, 287 { ".NO_PARALLEL", SP_NOTPARALLEL, OP_NONE }, 288 { ".NULL", SP_NULL, OP_NONE }, 289 { ".OBJDIR", SP_OBJDIR, OP_NONE }, 290 { ".OPTIONAL", SP_ATTRIBUTE, OP_OPTIONAL }, 291 { ".ORDER", SP_ORDER, OP_NONE }, 292 { ".PARALLEL", SP_PARALLEL, OP_NONE }, 293 { ".PATH", SP_PATH, OP_NONE }, 294 { ".PHONY", SP_PHONY, OP_PHONY }, 295 { ".POSIX", SP_POSIX, OP_NONE }, 296 { ".PRECIOUS", SP_PRECIOUS, OP_PRECIOUS }, 297 { ".READONLY", SP_READONLY, OP_NONE }, 298 { ".RECURSIVE", SP_ATTRIBUTE, OP_MAKE }, 299 { ".SHELL", SP_SHELL, OP_NONE }, 300 { ".SILENT", SP_SILENT, OP_SILENT }, 301 { ".SINGLESHELL", SP_SINGLESHELL, OP_NONE }, 302 { ".STALE", SP_STALE, OP_NONE }, 303 { ".SUFFIXES", SP_SUFFIXES, OP_NONE }, 304 { ".SYSPATH", SP_SYSPATH, OP_NONE }, 305 { ".USE", SP_ATTRIBUTE, OP_USE }, 306 { ".USEBEFORE", SP_ATTRIBUTE, OP_USEBEFORE }, 307 { ".WAIT", SP_WAIT, OP_NONE }, 308 }; 309 310 enum PosixState posix_state = PS_NOT_YET; 311 312 static HashTable /* full file name -> Guard */ guards; 313 314 315 static List * 316 Lst_New(void) 317 { 318 List *list = bmake_malloc(sizeof *list); 319 Lst_Init(list); 320 return list; 321 } 322 323 static void 324 Lst_Free(List *list) 325 { 326 327 Lst_Done(list); 328 free(list); 329 } 330 331 static IncludedFile * 332 GetInclude(size_t i) 333 { 334 assert(i < includes.len); 335 return Vector_Get(&includes, i); 336 } 337 338 /* The makefile or the body of a .for loop that is currently being read. */ 339 static IncludedFile * 340 CurFile(void) 341 { 342 return GetInclude(includes.len - 1); 343 } 344 345 unsigned int 346 CurFile_CondMinDepth(void) 347 { 348 return CurFile()->condMinDepth; 349 } 350 351 static Buffer 352 LoadFile(const char *path, int fd) 353 { 354 ssize_t n; 355 Buffer buf; 356 size_t bufSize; 357 struct stat st; 358 359 bufSize = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) && 360 st.st_size > 0 && st.st_size < 1024 * 1024 * 1024 361 ? (size_t)st.st_size : 1024; 362 Buf_InitSize(&buf, bufSize); 363 364 for (;;) { 365 if (buf.len == buf.cap) { 366 if (buf.cap >= 512 * 1024 * 1024) { 367 Error("%s: file too large", path); 368 exit(2); /* Not 1 so -q can distinguish error */ 369 } 370 Buf_Expand(&buf); 371 } 372 assert(buf.len < buf.cap); 373 n = read(fd, buf.data + buf.len, buf.cap - buf.len); 374 if (n < 0) { 375 Error("%s: read error: %s", path, strerror(errno)); 376 exit(2); /* Not 1 so -q can distinguish error */ 377 } 378 if (n == 0) 379 break; 380 381 buf.len += (size_t)n; 382 } 383 assert(buf.len <= buf.cap); 384 385 if (buf.len > 0 && !Buf_EndsWith(&buf, '\n')) 386 Buf_AddByte(&buf, '\n'); 387 388 return buf; /* may not be null-terminated */ 389 } 390 391 /* 392 * Print the current chain of .include and .for directives. In Parse_Fatal 393 * or other functions that already print the location, includingInnermost 394 * would be redundant, but in other cases like Error or Fatal it needs to be 395 * included. 396 */ 397 void 398 PrintStackTrace(bool includingInnermost) 399 { 400 const IncludedFile *entries; 401 size_t i, n; 402 403 EvalStack_PrintDetails(); 404 405 n = includes.len; 406 if (n == 0) 407 return; 408 409 entries = GetInclude(0); 410 if (!includingInnermost && entries[n - 1].forLoop == NULL) 411 n--; /* already in the diagnostic */ 412 413 for (i = n; i-- > 0;) { 414 const IncludedFile *entry = entries + i; 415 const char *fname = entry->name.str; 416 char dirbuf[MAXPATHLEN + 1]; 417 418 if (fname[0] != '/' && strcmp(fname, "(stdin)") != 0) { 419 const char *realPath = realpath(fname, dirbuf); 420 if (realPath != NULL) 421 fname = realPath; 422 } 423 424 if (entry->forLoop != NULL) { 425 char *details = ForLoop_Details(entry->forLoop); 426 debug_printf("\tin .for loop from %s:%u with %s\n", 427 fname, entry->forHeadLineno, details); 428 free(details); 429 } else if (i + 1 < n && entries[i + 1].forLoop != NULL) { 430 /* entry->lineno is not a useful line number */ 431 } else 432 debug_printf("\tin %s:%u\n", fname, entry->lineno); 433 } 434 if (makelevel > 0) 435 debug_printf("\tin directory %s\n", curdir); 436 } 437 438 /* Check if the current character is escaped on the current line. */ 439 static bool 440 IsEscaped(const char *line, const char *p) 441 { 442 bool escaped = false; 443 while (p > line && *--p == '\\') 444 escaped = !escaped; 445 return escaped; 446 } 447 448 /* 449 * Remember the location (filename and lineno) where the last command was 450 * added or where the node was mentioned in a .depend file. 451 */ 452 static void 453 RememberLocation(GNode *gn) 454 { 455 IncludedFile *curFile = CurFile(); 456 gn->fname = Str_Intern(curFile->name.str); 457 gn->lineno = curFile->lineno; 458 } 459 460 /* 461 * Look in the table of keywords for one matching the given string. 462 * Return the index of the keyword, or -1 if it isn't there. 463 */ 464 static int 465 FindKeyword(const char *str) 466 { 467 int start = 0; 468 int end = sizeof parseKeywords / sizeof parseKeywords[0] - 1; 469 470 while (start <= end) { 471 int curr = start + (end - start) / 2; 472 int diff = strcmp(str, parseKeywords[curr].name); 473 474 if (diff == 0) 475 return curr; 476 if (diff < 0) 477 end = curr - 1; 478 else 479 start = curr + 1; 480 } 481 482 return -1; 483 } 484 485 void 486 PrintLocation(FILE *f, bool useVars, const GNode *gn) 487 { 488 char dirbuf[MAXPATHLEN + 1]; 489 FStr dir, base; 490 const char *fname; 491 unsigned lineno; 492 493 if (gn != NULL) { 494 fname = gn->fname; 495 lineno = gn->lineno; 496 } else if (includes.len > 0) { 497 IncludedFile *curFile = CurFile(); 498 fname = curFile->name.str; 499 lineno = curFile->lineno; 500 } else 501 return; 502 503 if (!useVars || fname[0] == '/' || strcmp(fname, "(stdin)") == 0) { 504 (void)fprintf(f, "\"%s\" line %u: ", fname, lineno); 505 return; 506 } 507 508 dir = Var_Value(SCOPE_GLOBAL, ".PARSEDIR"); 509 if (dir.str == NULL) 510 dir.str = "."; 511 if (dir.str[0] != '/') 512 dir.str = realpath(dir.str, dirbuf); 513 514 base = Var_Value(SCOPE_GLOBAL, ".PARSEFILE"); 515 if (base.str == NULL) 516 base.str = str_basename(fname); 517 518 (void)fprintf(f, "\"%s/%s\" line %u: ", dir.str, base.str, lineno); 519 520 FStr_Done(&base); 521 FStr_Done(&dir); 522 } 523 524 static void MAKE_ATTR_PRINTFLIKE(5, 0) 525 ParseVErrorInternal(FILE *f, bool useVars, const GNode *gn, 526 ParseErrorLevel level, const char *fmt, va_list ap) 527 { 528 static bool fatal_warning_error_printed = false; 529 530 (void)fprintf(f, "%s: ", progname); 531 532 PrintLocation(f, useVars, gn); 533 if (level == PARSE_WARNING) 534 (void)fprintf(f, "warning: "); 535 (void)vfprintf(f, fmt, ap); 536 (void)fprintf(f, "\n"); 537 (void)fflush(f); 538 539 if (level == PARSE_FATAL) 540 parseErrors++; 541 if (level == PARSE_WARNING && opts.parseWarnFatal) { 542 if (!fatal_warning_error_printed) { 543 Error("parsing warnings being treated as errors"); 544 fatal_warning_error_printed = true; 545 } 546 parseErrors++; 547 } 548 549 if (level == PARSE_FATAL || DEBUG(PARSE)) 550 PrintStackTrace(false); 551 } 552 553 static void MAKE_ATTR_PRINTFLIKE(3, 4) 554 ParseErrorInternal(const GNode *gn, 555 ParseErrorLevel level, const char *fmt, ...) 556 { 557 va_list ap; 558 559 (void)fflush(stdout); 560 va_start(ap, fmt); 561 ParseVErrorInternal(stderr, false, gn, level, fmt, ap); 562 va_end(ap); 563 564 if (opts.debug_file != stdout && opts.debug_file != stderr) { 565 va_start(ap, fmt); 566 ParseVErrorInternal(opts.debug_file, false, gn, 567 level, fmt, ap); 568 va_end(ap); 569 } 570 } 571 572 /* 573 * Print a message, including location information. 574 * 575 * If the level is PARSE_FATAL, continue parsing until the end of the 576 * current top-level makefile, then exit (see Parse_File). 577 * 578 * Fmt is given without a trailing newline. 579 */ 580 void 581 Parse_Error(ParseErrorLevel level, const char *fmt, ...) 582 { 583 va_list ap; 584 585 (void)fflush(stdout); 586 va_start(ap, fmt); 587 ParseVErrorInternal(stderr, true, NULL, level, fmt, ap); 588 va_end(ap); 589 590 if (opts.debug_file != stdout && opts.debug_file != stderr) { 591 va_start(ap, fmt); 592 ParseVErrorInternal(opts.debug_file, true, NULL, 593 level, fmt, ap); 594 va_end(ap); 595 } 596 } 597 598 599 /* 600 * Handle an .info, .warning or .error directive. For an .error directive, 601 * exit immediately. 602 */ 603 static void 604 HandleMessage(ParseErrorLevel level, const char *levelName, const char *umsg) 605 { 606 char *xmsg; 607 608 if (umsg[0] == '\0') { 609 Parse_Error(PARSE_FATAL, "Missing argument for \".%s\"", 610 levelName); 611 return; 612 } 613 614 xmsg = Var_Subst(umsg, SCOPE_CMDLINE, VARE_EVAL); 615 /* TODO: handle errors */ 616 617 Parse_Error(level, "%s", xmsg); 618 free(xmsg); 619 620 if (level == PARSE_FATAL) { 621 PrintOnError(NULL, "\n"); 622 exit(1); 623 } 624 } 625 626 /* 627 * Add the child to the parent's children, and for non-special targets, vice 628 * versa. 629 */ 630 static void 631 LinkSource(GNode *pgn, GNode *cgn, bool isSpecial) 632 { 633 if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty(&pgn->cohorts)) 634 pgn = pgn->cohorts.last->datum; 635 636 Lst_Append(&pgn->children, cgn); 637 pgn->unmade++; 638 639 /* 640 * Special targets like .END do not need to be informed once the child 641 * target has been made. 642 */ 643 if (!isSpecial) 644 Lst_Append(&cgn->parents, pgn); 645 646 if (DEBUG(PARSE)) { 647 debug_printf("Target \"%s\" depends on \"%s\"\n", 648 pgn->name, cgn->name); 649 Targ_PrintNode(pgn, 0); 650 Targ_PrintNode(cgn, 0); 651 } 652 } 653 654 /* Add the node to each target from the current dependency group. */ 655 static void 656 LinkToTargets(GNode *gn, bool isSpecial) 657 { 658 GNodeListNode *ln; 659 660 for (ln = targets->first; ln != NULL; ln = ln->next) 661 LinkSource(ln->datum, gn, isSpecial); 662 } 663 664 static bool 665 TryApplyDependencyOperator(GNode *gn, GNodeType op) 666 { 667 /* 668 * If the node occurred on the left-hand side of a dependency and the 669 * operator also defines a dependency, they must match. 670 */ 671 if ((op & OP_OPMASK) && (gn->type & OP_OPMASK) && 672 ((op & OP_OPMASK) != (gn->type & OP_OPMASK))) { 673 Parse_Error(PARSE_FATAL, "Inconsistent operator for %s", 674 gn->name); 675 return false; 676 } 677 678 if (op == OP_DOUBLEDEP && (gn->type & OP_OPMASK) == OP_DOUBLEDEP) { 679 /* 680 * If the node was on the left-hand side of a '::' operator, 681 * create a new node for the children and commands on this 682 * dependency line, since each of these dependency groups has 683 * its own attributes and commands, separate from the others. 684 * 685 * The new instance is placed on the 'cohorts' list of the 686 * initial one (note the initial one is not on its own 687 * cohorts list) and the new instance is linked to all 688 * parents of the initial instance. 689 */ 690 GNode *cohort; 691 692 /* 693 * Propagate copied bits to the initial node. They'll be 694 * propagated back to the rest of the cohorts later. 695 */ 696 gn->type |= op & (unsigned)~OP_OPMASK; 697 698 cohort = Targ_NewInternalNode(gn->name); 699 if (doing_depend) 700 RememberLocation(cohort); 701 /* 702 * Make the cohort invisible to avoid duplicating it 703 * into other variables. True, parents of this target won't 704 * tend to do anything with their local variables, but better 705 * safe than sorry. 706 * 707 * (I think this is pointless now, since the relevant list 708 * traversals will no longer see this node anyway. -mycroft) 709 */ 710 cohort->type = op | OP_INVISIBLE; 711 Lst_Append(&gn->cohorts, cohort); 712 cohort->centurion = gn; 713 gn->unmade_cohorts++; 714 snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d", 715 (unsigned int)gn->unmade_cohorts % 1000000); 716 } else { 717 gn->type |= op; /* preserve any previous flags */ 718 } 719 720 return true; 721 } 722 723 static void 724 ApplyDependencyOperator(GNodeType op) 725 { 726 GNodeListNode *ln; 727 728 for (ln = targets->first; ln != NULL; ln = ln->next) 729 if (!TryApplyDependencyOperator(ln->datum, op)) 730 break; 731 } 732 733 /* 734 * Add a .WAIT node in the dependency list. After any dynamic dependencies 735 * (and filename globbing) have happened, it is given a dependency on each 736 * previous child, back until the previous .WAIT node. The next child won't 737 * be scheduled until the .WAIT node is built. 738 * 739 * Give each .WAIT node a unique name (mainly for diagnostics). 740 */ 741 static void 742 ApplyDependencySourceWait(bool isSpecial) 743 { 744 static unsigned wait_number = 0; 745 char name[6 + 10 + 1]; 746 GNode *gn; 747 748 snprintf(name, sizeof name, ".WAIT_%u", ++wait_number); 749 gn = Targ_NewInternalNode(name); 750 if (doing_depend) 751 RememberLocation(gn); 752 gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN; 753 LinkToTargets(gn, isSpecial); 754 } 755 756 static bool 757 ApplyDependencySourceKeyword(const char *src, ParseSpecial special) 758 { 759 int keywd; 760 GNodeType targetAttr; 761 762 if (*src != '.' || !ch_isupper(src[1])) 763 return false; 764 765 keywd = FindKeyword(src); 766 if (keywd == -1) 767 return false; 768 769 targetAttr = parseKeywords[keywd].targetAttr; 770 if (targetAttr != OP_NONE) { 771 ApplyDependencyOperator(targetAttr); 772 return true; 773 } 774 if (parseKeywords[keywd].special == SP_WAIT) { 775 ApplyDependencySourceWait(special != SP_NOT); 776 return true; 777 } 778 return false; 779 } 780 781 /* 782 * In a line like ".MAIN: source1 source2", add all sources to the list of 783 * things to create, but only if the user didn't specify a target on the 784 * command line and .MAIN occurs for the first time. 785 * 786 * See HandleDependencyTargetSpecial, branch SP_MAIN. 787 * See unit-tests/cond-func-make-main.mk. 788 */ 789 static void 790 ApplyDependencySourceMain(const char *src) 791 { 792 Lst_Append(&opts.create, bmake_strdup(src)); 793 /* 794 * Add the name to the .TARGETS variable as well, so the user can 795 * employ that, if desired. 796 */ 797 Global_Append(".TARGETS", src); 798 } 799 800 /* 801 * For the sources of a .ORDER target, create predecessor/successor links 802 * between the previous source and the current one. 803 */ 804 static void 805 ApplyDependencySourceOrder(const char *src) 806 { 807 GNode *gn; 808 809 gn = Targ_GetNode(src); 810 if (doing_depend) 811 RememberLocation(gn); 812 if (order_pred != NULL) { 813 Lst_Append(&order_pred->order_succ, gn); 814 Lst_Append(&gn->order_pred, order_pred); 815 if (DEBUG(PARSE)) { 816 debug_printf( 817 "# .ORDER forces '%s' to be made before '%s'\n", 818 order_pred->name, gn->name); 819 Targ_PrintNode(order_pred, 0); 820 Targ_PrintNode(gn, 0); 821 } 822 } 823 /* The current source now becomes the predecessor for the next one. */ 824 order_pred = gn; 825 } 826 827 /* The source is not an attribute, so find/create a node for it. */ 828 static void 829 ApplyDependencySourceOther(const char *src, GNodeType targetAttr, 830 ParseSpecial special) 831 { 832 GNode *gn; 833 834 gn = Targ_GetNode(src); 835 if (doing_depend) 836 RememberLocation(gn); 837 if (targetAttr != OP_NONE) 838 gn->type |= targetAttr; 839 else 840 LinkToTargets(gn, special != SP_NOT); 841 } 842 843 /* 844 * Given the name of a source in a dependency line, figure out if it is an 845 * attribute (such as .SILENT) and if so, apply it to all targets. Otherwise 846 * decide if there is some attribute which should be applied *to* the source 847 * because of some special target (such as .PHONY) and apply it if so. 848 * Otherwise, make the source a child of the targets. 849 */ 850 static void 851 ApplyDependencySource(GNodeType targetAttr, const char *src, 852 ParseSpecial special) 853 { 854 if (ApplyDependencySourceKeyword(src, special)) 855 return; 856 857 if (special == SP_MAIN) 858 ApplyDependencySourceMain(src); 859 else if (special == SP_ORDER) 860 ApplyDependencySourceOrder(src); 861 else 862 ApplyDependencySourceOther(src, targetAttr, special); 863 } 864 865 /* 866 * If we have yet to decide on a main target to make, in the absence of any 867 * user input, we want the first target on the first dependency line that is 868 * actually a real target (i.e. isn't a .USE or .EXEC rule) to be made. 869 */ 870 static void 871 MaybeUpdateMainTarget(void) 872 { 873 GNodeListNode *ln; 874 875 if (mainNode != NULL) 876 return; 877 878 for (ln = targets->first; ln != NULL; ln = ln->next) { 879 GNode *gn = ln->datum; 880 if (GNode_IsMainCandidate(gn)) { 881 DEBUG1(MAKE, "Setting main node to \"%s\"\n", 882 gn->name); 883 mainNode = gn; 884 return; 885 } 886 } 887 } 888 889 static void 890 InvalidLineType(const char *line, const char *unexpanded_line) 891 { 892 if (unexpanded_line[0] == '.') { 893 const char *dirstart = unexpanded_line + 1; 894 const char *dirend; 895 cpp_skip_whitespace(&dirstart); 896 dirend = dirstart; 897 while (ch_isalnum(*dirend) || *dirend == '-') 898 dirend++; 899 Parse_Error(PARSE_FATAL, "Unknown directive \"%.*s\"", 900 (int)(dirend - dirstart), dirstart); 901 } else if (strcmp(line, unexpanded_line) == 0) 902 Parse_Error(PARSE_FATAL, "Invalid line '%s'", line); 903 else 904 Parse_Error(PARSE_FATAL, 905 "Invalid line '%s', expanded to '%s'", 906 unexpanded_line, line); 907 } 908 909 static void 910 ParseDependencyTargetWord(char **pp, const char *lstart) 911 { 912 const char *p = *pp; 913 914 while (*p != '\0') { 915 if ((ch_isspace(*p) || *p == '!' || *p == ':' || *p == '(') 916 && !IsEscaped(lstart, p)) 917 break; 918 919 if (*p == '$') { 920 FStr val = Var_Parse(&p, SCOPE_CMDLINE, VARE_PARSE); 921 /* TODO: handle errors */ 922 FStr_Done(&val); 923 } else 924 p++; 925 } 926 927 *pp += p - *pp; 928 } 929 930 /* 931 * Handle special targets like .PATH, .DEFAULT, .BEGIN, .ORDER. 932 * 933 * See the tests deptgt-*.mk. 934 */ 935 static void 936 HandleDependencyTargetSpecial(const char *targetName, 937 ParseSpecial *inout_special, 938 SearchPathList **inout_paths) 939 { 940 switch (*inout_special) { 941 case SP_PATH: 942 if (*inout_paths == NULL) 943 *inout_paths = Lst_New(); 944 Lst_Append(*inout_paths, &dirSearchPath); 945 break; 946 case SP_SYSPATH: 947 if (*inout_paths == NULL) 948 *inout_paths = Lst_New(); 949 Lst_Append(*inout_paths, sysIncPath); 950 break; 951 case SP_MAIN: 952 /* 953 * Allow targets from the command line to override the 954 * .MAIN node. 955 */ 956 if (!Lst_IsEmpty(&opts.create)) 957 *inout_special = SP_NOT; 958 break; 959 case SP_BEGIN: 960 case SP_END: 961 case SP_STALE: 962 case SP_ERROR: 963 case SP_INTERRUPT: { 964 GNode *gn = Targ_GetNode(targetName); 965 if (doing_depend) 966 RememberLocation(gn); 967 gn->type |= OP_NOTMAIN | OP_SPECIAL; 968 Lst_Append(targets, gn); 969 break; 970 } 971 case SP_DEFAULT: { 972 /* 973 * Need to create a node to hang commands on, but we don't 974 * want it in the graph, nor do we want it to be the Main 975 * Target. We claim the node is a transformation rule to make 976 * life easier later, when we'll use Make_HandleUse to 977 * actually apply the .DEFAULT commands. 978 */ 979 GNode *gn = GNode_New(".DEFAULT"); 980 gn->type |= OP_NOTMAIN | OP_TRANSFORM; 981 Lst_Append(targets, gn); 982 defaultNode = gn; 983 break; 984 } 985 case SP_DELETE_ON_ERROR: 986 deleteOnError = true; 987 break; 988 case SP_NOTPARALLEL: 989 opts.maxJobs = 1; 990 break; 991 case SP_SINGLESHELL: 992 opts.compatMake = true; 993 break; 994 case SP_ORDER: 995 order_pred = NULL; 996 break; 997 default: 998 break; 999 } 1000 } 1001 1002 static bool 1003 HandleDependencyTargetPath(const char *suffixName, 1004 SearchPathList **inout_paths) 1005 { 1006 SearchPath *path; 1007 1008 path = Suff_GetPath(suffixName); 1009 if (path == NULL) { 1010 Parse_Error(PARSE_FATAL, 1011 "Suffix '%s' not defined (yet)", suffixName); 1012 return false; 1013 } 1014 1015 if (*inout_paths == NULL) 1016 *inout_paths = Lst_New(); 1017 Lst_Append(*inout_paths, path); 1018 1019 return true; 1020 } 1021 1022 /* See if it's a special target and if so set inout_special to match it. */ 1023 static bool 1024 HandleDependencyTarget(const char *targetName, 1025 ParseSpecial *inout_special, 1026 GNodeType *inout_targetAttr, 1027 SearchPathList **inout_paths) 1028 { 1029 int keywd; 1030 1031 if (!(targetName[0] == '.' && ch_isupper(targetName[1]))) 1032 return true; 1033 1034 /* 1035 * See if the target is a special target that must have it 1036 * or its sources handled specially. 1037 */ 1038 keywd = FindKeyword(targetName); 1039 if (keywd != -1) { 1040 if (*inout_special == SP_PATH && 1041 parseKeywords[keywd].special != SP_PATH) { 1042 Parse_Error(PARSE_FATAL, "Mismatched special targets"); 1043 return false; 1044 } 1045 1046 *inout_special = parseKeywords[keywd].special; 1047 *inout_targetAttr = parseKeywords[keywd].targetAttr; 1048 1049 HandleDependencyTargetSpecial(targetName, inout_special, 1050 inout_paths); 1051 1052 } else if (strncmp(targetName, ".PATH", 5) == 0) { 1053 *inout_special = SP_PATH; 1054 if (!HandleDependencyTargetPath(targetName + 5, inout_paths)) 1055 return false; 1056 } 1057 return true; 1058 } 1059 1060 static void 1061 HandleSingleDependencyTargetMundane(const char *name) 1062 { 1063 GNode *gn = Suff_IsTransform(name) 1064 ? Suff_AddTransform(name) 1065 : Targ_GetNode(name); 1066 if (doing_depend) 1067 RememberLocation(gn); 1068 1069 Lst_Append(targets, gn); 1070 } 1071 1072 static void 1073 HandleDependencyTargetMundane(const char *targetName) 1074 { 1075 if (Dir_HasWildcards(targetName)) { 1076 StringList targetNames = LST_INIT; 1077 1078 SearchPath *emptyPath = SearchPath_New(); 1079 SearchPath_Expand(emptyPath, targetName, &targetNames); 1080 SearchPath_Free(emptyPath); 1081 1082 while (!Lst_IsEmpty(&targetNames)) { 1083 char *targName = Lst_Dequeue(&targetNames); 1084 HandleSingleDependencyTargetMundane(targName); 1085 free(targName); 1086 } 1087 } else 1088 HandleSingleDependencyTargetMundane(targetName); 1089 } 1090 1091 static void 1092 SkipExtraTargets(char **pp, const char *lstart) 1093 { 1094 bool warning = false; 1095 const char *p = *pp; 1096 1097 while (*p != '\0') { 1098 if (!IsEscaped(lstart, p) && (*p == '!' || *p == ':')) 1099 break; 1100 if (IsEscaped(lstart, p) || (*p != ' ' && *p != '\t')) 1101 warning = true; 1102 p++; 1103 } 1104 if (warning) { 1105 const char *start = *pp; 1106 cpp_skip_whitespace(&start); 1107 Parse_Error(PARSE_WARNING, "Extra target '%.*s' ignored", 1108 (int)(p - start), start); 1109 } 1110 1111 *pp += p - *pp; 1112 } 1113 1114 static void 1115 CheckSpecialMundaneMixture(ParseSpecial special) 1116 { 1117 switch (special) { 1118 case SP_DEFAULT: 1119 case SP_STALE: 1120 case SP_BEGIN: 1121 case SP_END: 1122 case SP_ERROR: 1123 case SP_INTERRUPT: 1124 /* 1125 * These create nodes on which to hang commands, so targets 1126 * shouldn't be empty. 1127 */ 1128 case SP_NOT: 1129 /* Nothing special here -- targets may be empty. */ 1130 break; 1131 default: 1132 Parse_Error(PARSE_WARNING, 1133 "Special and mundane targets don't mix. " 1134 "Mundane ones ignored"); 1135 break; 1136 } 1137 } 1138 1139 /* 1140 * In a dependency line like 'targets: sources' or 'targets! sources', parse 1141 * the operator ':', '::' or '!' from between the targets and the sources. 1142 */ 1143 static GNodeType 1144 ParseDependencyOp(char **pp) 1145 { 1146 if (**pp == '!') 1147 return (*pp)++, OP_FORCE; 1148 if (**pp == ':' && (*pp)[1] == ':') 1149 return *pp += 2, OP_DOUBLEDEP; 1150 else if (**pp == ':') 1151 return (*pp)++, OP_DEPENDS; 1152 else 1153 return OP_NONE; 1154 } 1155 1156 static void 1157 ClearPaths(ParseSpecial special, SearchPathList *paths) 1158 { 1159 if (paths != NULL) { 1160 SearchPathListNode *ln; 1161 for (ln = paths->first; ln != NULL; ln = ln->next) 1162 SearchPath_Clear(ln->datum); 1163 } 1164 if (special == SP_SYSPATH) 1165 Dir_SetSYSPATH(); 1166 else 1167 Dir_SetPATH(); 1168 } 1169 1170 static char * 1171 FindInDirOfIncludingFile(const char *file) 1172 { 1173 char *fullname, *incdir, *slash, *newName; 1174 int i; 1175 1176 fullname = NULL; 1177 incdir = bmake_strdup(CurFile()->name.str); 1178 slash = strrchr(incdir, '/'); 1179 if (slash != NULL) { 1180 *slash = '\0'; 1181 /* 1182 * Now do lexical processing of leading "../" on the 1183 * filename. 1184 */ 1185 for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) { 1186 slash = strrchr(incdir + 1, '/'); 1187 if (slash == NULL || strcmp(slash, "/..") == 0) 1188 break; 1189 *slash = '\0'; 1190 } 1191 newName = str_concat3(incdir, "/", file + i); 1192 fullname = Dir_FindFile(newName, parseIncPath); 1193 if (fullname == NULL) 1194 fullname = Dir_FindFile(newName, &dirSearchPath); 1195 free(newName); 1196 } 1197 free(incdir); 1198 return fullname; 1199 } 1200 1201 static char * 1202 FindInQuotPath(const char *file) 1203 { 1204 const char *suff; 1205 SearchPath *suffPath; 1206 char *fullname; 1207 1208 fullname = FindInDirOfIncludingFile(file); 1209 if (fullname == NULL && 1210 (suff = strrchr(file, '.')) != NULL && 1211 (suffPath = Suff_GetPath(suff)) != NULL) 1212 fullname = Dir_FindFile(file, suffPath); 1213 if (fullname == NULL) 1214 fullname = Dir_FindFile(file, parseIncPath); 1215 if (fullname == NULL) 1216 fullname = Dir_FindFile(file, &dirSearchPath); 1217 return fullname; 1218 } 1219 1220 static bool 1221 SkipGuarded(const char *fullname) 1222 { 1223 Guard *guard = HashTable_FindValue(&guards, fullname); 1224 if (guard != NULL && guard->kind == GK_VARIABLE 1225 && GNode_ValueDirect(SCOPE_GLOBAL, guard->name) != NULL) 1226 goto skip; 1227 if (guard != NULL && guard->kind == GK_TARGET 1228 && Targ_FindNode(guard->name) != NULL) 1229 goto skip; 1230 return false; 1231 1232 skip: 1233 DEBUG2(PARSE, "Skipping '%s' because '%s' is defined\n", 1234 fullname, guard->name); 1235 return true; 1236 } 1237 1238 /* 1239 * Handle one of the .[-ds]include directives by remembering the current file 1240 * and pushing the included file on the stack. After the included file has 1241 * finished, parsing continues with the including file; see Parse_PushInput 1242 * and ParseEOF. 1243 * 1244 * System includes are looked up in sysIncPath, any other includes are looked 1245 * up in the parsedir and then in the directories specified by the -I command 1246 * line options. 1247 */ 1248 static void 1249 IncludeFile(const char *file, bool isSystem, bool depinc, bool silent) 1250 { 1251 Buffer buf; 1252 char *fullname; /* full pathname of file */ 1253 int fd; 1254 1255 fullname = file[0] == '/' ? bmake_strdup(file) : NULL; 1256 1257 if (fullname == NULL && !isSystem) 1258 fullname = FindInQuotPath(file); 1259 1260 if (fullname == NULL) { 1261 SearchPath *path = Lst_IsEmpty(&sysIncPath->dirs) 1262 ? defSysIncPath : sysIncPath; 1263 fullname = Dir_FindInclude(file, path); 1264 } 1265 1266 if (fullname == NULL) { 1267 if (!silent) 1268 Parse_Error(PARSE_FATAL, "Could not find %s", file); 1269 return; 1270 } 1271 1272 if (SkipGuarded(fullname)) 1273 goto done; 1274 1275 if ((fd = open(fullname, O_RDONLY)) == -1) { 1276 if (!silent) 1277 Parse_Error(PARSE_FATAL, "Cannot open %s", fullname); 1278 goto done; 1279 } 1280 1281 buf = LoadFile(fullname, fd); 1282 (void)close(fd); 1283 1284 Parse_PushInput(fullname, 1, 0, buf, NULL); 1285 if (depinc) 1286 doing_depend = depinc; /* only turn it on */ 1287 done: 1288 free(fullname); 1289 } 1290 1291 /* Handle a "dependency" line like '.SPECIAL:' without any sources. */ 1292 static void 1293 HandleDependencySourcesEmpty(ParseSpecial special, SearchPathList *paths) 1294 { 1295 switch (special) { 1296 case SP_SUFFIXES: 1297 Suff_ClearSuffixes(); 1298 break; 1299 case SP_PRECIOUS: 1300 allPrecious = true; 1301 break; 1302 case SP_IGNORE: 1303 opts.ignoreErrors = true; 1304 break; 1305 case SP_SILENT: 1306 opts.silent = true; 1307 break; 1308 case SP_PATH: 1309 case SP_SYSPATH: 1310 ClearPaths(special, paths); 1311 break; 1312 case SP_POSIX: 1313 if (posix_state == PS_NOW_OR_NEVER) { 1314 /* 1315 * With '-r', 'posix.mk' (if it exists) 1316 * can effectively substitute for 'sys.mk', 1317 * otherwise it is an extension. 1318 */ 1319 Global_Set("%POSIX", "1003.2"); 1320 IncludeFile("posix.mk", true, false, true); 1321 } 1322 break; 1323 default: 1324 break; 1325 } 1326 } 1327 1328 static void 1329 AddToPaths(const char *dir, SearchPathList *paths) 1330 { 1331 if (paths != NULL) { 1332 SearchPathListNode *ln; 1333 for (ln = paths->first; ln != NULL; ln = ln->next) 1334 (void)SearchPath_Add(ln->datum, dir); 1335 } 1336 } 1337 1338 /* 1339 * If the target was one that doesn't take files as its sources but takes 1340 * something like suffixes, we take each space-separated word on the line as 1341 * a something and deal with it accordingly. 1342 */ 1343 static void 1344 ParseDependencySourceSpecial(ParseSpecial special, const char *word, 1345 SearchPathList *paths) 1346 { 1347 switch (special) { 1348 case SP_SUFFIXES: 1349 Suff_AddSuffix(word); 1350 break; 1351 case SP_PATH: 1352 case SP_SYSPATH: 1353 AddToPaths(word, paths); 1354 break; 1355 case SP_INCLUDES: 1356 Suff_AddInclude(word); 1357 break; 1358 case SP_LIBS: 1359 Suff_AddLib(word); 1360 break; 1361 case SP_NOREADONLY: 1362 Var_ReadOnly(word, false); 1363 break; 1364 case SP_NULL: 1365 Suff_SetNull(word); 1366 break; 1367 case SP_OBJDIR: 1368 Main_SetObjdir(false, "%s", word); 1369 break; 1370 case SP_READONLY: 1371 Var_ReadOnly(word, true); 1372 break; 1373 default: 1374 break; 1375 } 1376 } 1377 1378 static bool 1379 ApplyDependencyTarget(char *name, char *nameEnd, ParseSpecial *inout_special, 1380 GNodeType *inout_targetAttr, 1381 SearchPathList **inout_paths) 1382 { 1383 char savedNameEnd = *nameEnd; 1384 *nameEnd = '\0'; 1385 1386 if (!HandleDependencyTarget(name, inout_special, 1387 inout_targetAttr, inout_paths)) 1388 return false; 1389 1390 if (*inout_special == SP_NOT && *name != '\0') 1391 HandleDependencyTargetMundane(name); 1392 else if (*inout_special == SP_PATH && *name != '.' && *name != '\0') 1393 Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", name); 1394 1395 *nameEnd = savedNameEnd; 1396 return true; 1397 } 1398 1399 static bool 1400 ParseDependencyTargets(char **pp, 1401 const char *lstart, 1402 ParseSpecial *inout_special, 1403 GNodeType *inout_targetAttr, 1404 SearchPathList **inout_paths, 1405 const char *unexpanded_line) 1406 { 1407 char *p = *pp; 1408 1409 for (;;) { 1410 char *tgt = p; 1411 1412 ParseDependencyTargetWord(&p, lstart); 1413 1414 /* 1415 * If the word is followed by a left parenthesis, it's the 1416 * name of one or more files inside an archive. 1417 */ 1418 if (!IsEscaped(lstart, p) && *p == '(') { 1419 p = tgt; 1420 if (!Arch_ParseArchive(&p, targets, SCOPE_CMDLINE)) { 1421 Parse_Error(PARSE_FATAL, 1422 "Error in archive specification: \"%s\"", 1423 tgt); 1424 return false; 1425 } 1426 continue; 1427 } 1428 1429 if (*p == '\0') { 1430 InvalidLineType(lstart, unexpanded_line); 1431 return false; 1432 } 1433 1434 if (!ApplyDependencyTarget(tgt, p, inout_special, 1435 inout_targetAttr, inout_paths)) 1436 return false; 1437 1438 if (*inout_special != SP_NOT && *inout_special != SP_PATH) 1439 SkipExtraTargets(&p, lstart); 1440 else 1441 pp_skip_whitespace(&p); 1442 1443 if (*p == '\0') 1444 break; 1445 if ((*p == '!' || *p == ':') && !IsEscaped(lstart, p)) 1446 break; 1447 } 1448 1449 *pp = p; 1450 return true; 1451 } 1452 1453 static void 1454 ParseDependencySourcesSpecial(char *start, 1455 ParseSpecial special, SearchPathList *paths) 1456 { 1457 1458 while (*start != '\0') { 1459 char savedEnd; 1460 char *end = start; 1461 while (*end != '\0' && !ch_isspace(*end)) 1462 end++; 1463 savedEnd = *end; 1464 *end = '\0'; 1465 ParseDependencySourceSpecial(special, start, paths); 1466 *end = savedEnd; 1467 if (savedEnd != '\0') 1468 end++; 1469 pp_skip_whitespace(&end); 1470 start = end; 1471 } 1472 } 1473 1474 static void 1475 LinkVarToTargets(VarAssign *var) 1476 { 1477 GNodeListNode *ln; 1478 1479 for (ln = targets->first; ln != NULL; ln = ln->next) 1480 Parse_Var(var, ln->datum); 1481 } 1482 1483 static bool 1484 ParseDependencySourcesMundane(char *start, 1485 ParseSpecial special, GNodeType targetAttr) 1486 { 1487 while (*start != '\0') { 1488 char *end = start; 1489 VarAssign var; 1490 1491 /* 1492 * Check for local variable assignment, 1493 * rest of the line is the value. 1494 */ 1495 if (Parse_IsVar(start, &var)) { 1496 bool targetVarsEnabled = GetBooleanExpr( 1497 "${.MAKE.TARGET_LOCAL_VARIABLES}", true); 1498 1499 if (targetVarsEnabled) 1500 LinkVarToTargets(&var); 1501 free(var.varname); 1502 if (targetVarsEnabled) 1503 return true; 1504 } 1505 1506 /* 1507 * The targets take real sources, so we must beware of archive 1508 * specifications (i.e. things with left parentheses in them) 1509 * and handle them accordingly. 1510 */ 1511 for (; *end != '\0' && !ch_isspace(*end); end++) { 1512 if (*end == '(' && end > start && end[-1] != '$') { 1513 /* 1514 * Only stop for a left parenthesis if it 1515 * isn't at the start of a word (that'll be 1516 * for variable changes later) and isn't 1517 * preceded by a dollar sign (a dynamic 1518 * source). 1519 */ 1520 break; 1521 } 1522 } 1523 1524 if (*end == '(') { 1525 GNodeList sources = LST_INIT; 1526 if (!Arch_ParseArchive(&start, &sources, 1527 SCOPE_CMDLINE)) { 1528 Parse_Error(PARSE_FATAL, 1529 "Error in source archive spec \"%s\"", 1530 start); 1531 return false; 1532 } 1533 1534 while (!Lst_IsEmpty(&sources)) { 1535 GNode *gn = Lst_Dequeue(&sources); 1536 ApplyDependencySource(targetAttr, gn->name, 1537 special); 1538 } 1539 Lst_Done(&sources); 1540 end = start; 1541 } else { 1542 if (*end != '\0') { 1543 *end = '\0'; 1544 end++; 1545 } 1546 1547 ApplyDependencySource(targetAttr, start, special); 1548 } 1549 pp_skip_whitespace(&end); 1550 start = end; 1551 } 1552 return true; 1553 } 1554 1555 /* 1556 * From a dependency line like 'targets: sources', parse the sources. 1557 * 1558 * See the tests depsrc-*.mk. 1559 */ 1560 static void 1561 ParseDependencySources(char *p, GNodeType targetAttr, 1562 ParseSpecial special, SearchPathList **inout_paths) 1563 { 1564 if (*p == '\0') { 1565 HandleDependencySourcesEmpty(special, *inout_paths); 1566 } else if (special == SP_MFLAGS) { 1567 Main_ParseArgLine(p); 1568 return; 1569 } else if (special == SP_SHELL) { 1570 if (!Job_ParseShell(p)) { 1571 Parse_Error(PARSE_FATAL, 1572 "improper shell specification"); 1573 return; 1574 } 1575 return; 1576 } else if (special == SP_NOTPARALLEL || special == SP_SINGLESHELL || 1577 special == SP_DELETE_ON_ERROR) { 1578 return; 1579 } 1580 1581 switch (special) { 1582 case SP_INCLUDES: 1583 case SP_LIBS: 1584 case SP_NOREADONLY: 1585 case SP_NULL: 1586 case SP_OBJDIR: 1587 case SP_PATH: 1588 case SP_READONLY: 1589 case SP_SUFFIXES: 1590 case SP_SYSPATH: 1591 ParseDependencySourcesSpecial(p, special, *inout_paths); 1592 if (*inout_paths != NULL) { 1593 Lst_Free(*inout_paths); 1594 *inout_paths = NULL; 1595 } 1596 if (special == SP_PATH) 1597 Dir_SetPATH(); 1598 if (special == SP_SYSPATH) 1599 Dir_SetSYSPATH(); 1600 break; 1601 default: 1602 assert(*inout_paths == NULL); 1603 if (!ParseDependencySourcesMundane(p, special, targetAttr)) 1604 return; 1605 break; 1606 } 1607 1608 MaybeUpdateMainTarget(); 1609 } 1610 1611 /* 1612 * Parse a dependency line consisting of targets, followed by a dependency 1613 * operator, optionally followed by sources. 1614 * 1615 * The nodes of the sources are linked as children to the nodes of the 1616 * targets. Nodes are created as necessary. 1617 * 1618 * The operator is applied to each node in the global 'targets' list, 1619 * which is where the nodes found for the targets are kept. 1620 * 1621 * The sources are parsed in much the same way as the targets, except 1622 * that they are expanded using the wildcarding scheme of the C-Shell, 1623 * and a target is created for each expanded word. Each of the resulting 1624 * nodes is then linked to each of the targets as one of its children. 1625 * 1626 * Certain targets and sources such as .PHONY or .PRECIOUS are handled 1627 * specially, see ParseSpecial. 1628 * 1629 * Transformation rules such as '.c.o' are also handled here, see 1630 * Suff_AddTransform. 1631 * 1632 * Upon return, the value of expandedLine is unspecified. 1633 */ 1634 static void 1635 ParseDependency(char *expandedLine, const char *unexpandedLine) 1636 { 1637 char *p; 1638 SearchPathList *paths; /* search paths to alter when parsing a list 1639 * of .PATH targets */ 1640 GNodeType targetAttr; /* from special sources */ 1641 ParseSpecial special; /* in special targets, the children are 1642 * linked as children of the parent but not 1643 * vice versa */ 1644 GNodeType op; 1645 1646 DEBUG1(PARSE, "ParseDependency(%s)\n", expandedLine); 1647 p = expandedLine; 1648 paths = NULL; 1649 targetAttr = OP_NONE; 1650 special = SP_NOT; 1651 1652 if (!ParseDependencyTargets(&p, expandedLine, &special, &targetAttr, 1653 &paths, unexpandedLine)) 1654 goto out; 1655 1656 if (!Lst_IsEmpty(targets)) 1657 CheckSpecialMundaneMixture(special); 1658 1659 op = ParseDependencyOp(&p); 1660 if (op == OP_NONE) { 1661 InvalidLineType(expandedLine, unexpandedLine); 1662 goto out; 1663 } 1664 ApplyDependencyOperator(op); 1665 1666 pp_skip_whitespace(&p); 1667 1668 ParseDependencySources(p, targetAttr, special, &paths); 1669 1670 out: 1671 if (paths != NULL) 1672 Lst_Free(paths); 1673 } 1674 1675 /* 1676 * Determine the assignment operator and adjust the end of the variable 1677 * name accordingly. 1678 */ 1679 static VarAssign 1680 AdjustVarassignOp(const char *name, const char *nameEnd, const char *op, 1681 const char *value) 1682 { 1683 VarAssignOp type; 1684 VarAssign va; 1685 1686 if (op > name && op[-1] == '+') { 1687 op--; 1688 type = VAR_APPEND; 1689 1690 } else if (op > name && op[-1] == '?') { 1691 op--; 1692 type = VAR_DEFAULT; 1693 1694 } else if (op > name && op[-1] == ':') { 1695 op--; 1696 type = VAR_SUBST; 1697 1698 } else if (op > name && op[-1] == '!') { 1699 op--; 1700 type = VAR_SHELL; 1701 1702 } else { 1703 type = VAR_NORMAL; 1704 while (op > name && ch_isspace(op[-1])) 1705 op--; 1706 1707 if (op - name >= 3 && memcmp(op - 3, ":sh", 3) == 0) { 1708 op -= 3; 1709 type = VAR_SHELL; 1710 } 1711 } 1712 1713 va.varname = bmake_strsedup(name, nameEnd < op ? nameEnd : op); 1714 va.op = type; 1715 va.value = value; 1716 return va; 1717 } 1718 1719 /* 1720 * Parse a variable assignment, consisting of a single-word variable name, 1721 * optional whitespace, an assignment operator, optional whitespace and the 1722 * variable value. 1723 * 1724 * Note: There is a lexical ambiguity with assignment modifier characters 1725 * in variable names. This routine interprets the character before the = 1726 * as a modifier. Therefore, an assignment like 1727 * C++=/usr/bin/CC 1728 * is interpreted as "C+ +=" instead of "C++ =". 1729 * 1730 * Used for both lines in a file and command line arguments. 1731 */ 1732 static bool 1733 Parse_IsVar(const char *p, VarAssign *out_var) 1734 { 1735 const char *nameStart, *nameEnd, *firstSpace, *eq; 1736 int level = 0; 1737 1738 cpp_skip_hspace(&p); /* Skip to variable name */ 1739 1740 /* 1741 * During parsing, the '+' of the operator '+=' is initially parsed 1742 * as part of the variable name. It is later corrected, as is the 1743 * ':sh' modifier. Of these two (nameEnd and eq), the earlier one 1744 * determines the actual end of the variable name. 1745 */ 1746 1747 nameStart = p; 1748 firstSpace = NULL; 1749 1750 /* Scan for one of the assignment operators outside an expression. */ 1751 while (*p != '\0') { 1752 char ch = *p++; 1753 if (ch == '(' || ch == '{') { 1754 level++; 1755 continue; 1756 } 1757 if (ch == ')' || ch == '}') { 1758 level--; 1759 continue; 1760 } 1761 1762 if (level != 0) 1763 continue; 1764 1765 if ((ch == ' ' || ch == '\t') && firstSpace == NULL) 1766 firstSpace = p - 1; 1767 while (ch == ' ' || ch == '\t') 1768 ch = *p++; 1769 1770 if (ch == '\0') 1771 return false; 1772 if (ch == ':' && p[0] == 's' && p[1] == 'h') { 1773 p += 2; 1774 continue; 1775 } 1776 if (ch == '=') 1777 eq = p - 1; 1778 else if (*p == '=' && 1779 (ch == '+' || ch == ':' || ch == '?' || ch == '!')) 1780 eq = p; 1781 else if (firstSpace != NULL) 1782 return false; 1783 else 1784 continue; 1785 1786 nameEnd = firstSpace != NULL ? firstSpace : eq; 1787 p = eq + 1; 1788 cpp_skip_whitespace(&p); 1789 *out_var = AdjustVarassignOp(nameStart, nameEnd, eq, p); 1790 return true; 1791 } 1792 1793 return false; 1794 } 1795 1796 /* 1797 * Check for syntax errors such as unclosed expressions or unknown modifiers. 1798 */ 1799 static void 1800 VarCheckSyntax(VarAssignOp op, const char *uvalue, GNode *scope) 1801 { 1802 if (opts.strict) { 1803 if (op != VAR_SUBST && strchr(uvalue, '$') != NULL) { 1804 char *parsedValue = Var_Subst(uvalue, 1805 scope, VARE_PARSE); 1806 /* TODO: handle errors */ 1807 free(parsedValue); 1808 } 1809 } 1810 } 1811 1812 /* Perform a variable assignment that uses the operator ':='. */ 1813 static void 1814 VarAssign_EvalSubst(GNode *scope, const char *name, const char *uvalue, 1815 FStr *out_avalue) 1816 { 1817 char *evalue; 1818 1819 /* 1820 * Make sure that we set the variable the first time to nothing 1821 * so that it gets substituted. 1822 * 1823 * TODO: Add a test that demonstrates why this code is needed, 1824 * apart from making the debug log longer. 1825 * 1826 * XXX: The variable name is expanded up to 3 times. 1827 */ 1828 if (!Var_ExistsExpand(scope, name)) 1829 Var_SetExpand(scope, name, ""); 1830 1831 evalue = Var_Subst(uvalue, scope, 1832 VARE_EVAL_KEEP_DOLLAR_AND_UNDEFINED); 1833 /* TODO: handle errors */ 1834 1835 Var_SetExpand(scope, name, evalue); 1836 1837 *out_avalue = FStr_InitOwn(evalue); 1838 } 1839 1840 /* Perform a variable assignment that uses the operator '!='. */ 1841 static void 1842 VarAssign_EvalShell(const char *name, const char *uvalue, GNode *scope, 1843 FStr *out_avalue) 1844 { 1845 FStr cmd; 1846 char *output, *error; 1847 1848 cmd = FStr_InitRefer(uvalue); 1849 Var_Expand(&cmd, SCOPE_CMDLINE, VARE_EVAL); 1850 1851 output = Cmd_Exec(cmd.str, &error); 1852 Var_SetExpand(scope, name, output); 1853 *out_avalue = FStr_InitOwn(output); 1854 if (error != NULL) { 1855 Parse_Error(PARSE_WARNING, "%s", error); 1856 free(error); 1857 } 1858 1859 FStr_Done(&cmd); 1860 } 1861 1862 /* 1863 * Perform a variable assignment. 1864 * 1865 * The actual value of the variable is returned in *out_true_avalue. 1866 * Especially for VAR_SUBST and VAR_SHELL this can differ from the literal 1867 * value. 1868 * 1869 * Return whether the assignment was actually performed, which is usually 1870 * the case. It is only skipped if the operator is '?=' and the variable 1871 * already exists. 1872 */ 1873 static bool 1874 VarAssign_Eval(const char *name, VarAssignOp op, const char *uvalue, 1875 GNode *scope, FStr *out_true_avalue) 1876 { 1877 FStr avalue = FStr_InitRefer(uvalue); 1878 1879 if (op == VAR_APPEND) 1880 Var_AppendExpand(scope, name, uvalue); 1881 else if (op == VAR_SUBST) 1882 VarAssign_EvalSubst(scope, name, uvalue, &avalue); 1883 else if (op == VAR_SHELL) 1884 VarAssign_EvalShell(name, uvalue, scope, &avalue); 1885 else { 1886 /* XXX: The variable name is expanded up to 2 times. */ 1887 if (op == VAR_DEFAULT && Var_ExistsExpand(scope, name)) 1888 return false; 1889 1890 /* Normal assignment -- just do it. */ 1891 Var_SetExpand(scope, name, uvalue); 1892 } 1893 1894 *out_true_avalue = avalue; 1895 return true; 1896 } 1897 1898 static void 1899 VarAssignSpecial(const char *name, const char *avalue) 1900 { 1901 if (strcmp(name, ".MAKEOVERRIDES") == 0) 1902 Main_ExportMAKEFLAGS(false); /* re-export MAKEFLAGS */ 1903 else if (strcmp(name, ".CURDIR") == 0) { 1904 /* 1905 * Someone is being (too?) clever... 1906 * Let's pretend they know what they are doing and 1907 * re-initialize the 'cur' CachedDir. 1908 */ 1909 Dir_InitCur(avalue); 1910 Dir_SetPATH(); 1911 } else if (strcmp(name, ".MAKE.JOB.PREFIX") == 0) 1912 Job_SetPrefix(); 1913 else if (strcmp(name, ".MAKE.EXPORTED") == 0) 1914 Var_ExportVars(avalue); 1915 } 1916 1917 /* Perform the variable assignment in the given scope. */ 1918 static void 1919 Parse_Var(VarAssign *var, GNode *scope) 1920 { 1921 FStr avalue; /* actual value (maybe expanded) */ 1922 1923 VarCheckSyntax(var->op, var->value, scope); 1924 if (VarAssign_Eval(var->varname, var->op, var->value, scope, &avalue)) { 1925 VarAssignSpecial(var->varname, avalue.str); 1926 FStr_Done(&avalue); 1927 } 1928 } 1929 1930 1931 /* 1932 * See if the command possibly calls a sub-make by using the 1933 * expressions ${.MAKE}, ${MAKE} or the plain word "make". 1934 */ 1935 static bool 1936 MaybeSubMake(const char *cmd) 1937 { 1938 const char *start; 1939 1940 for (start = cmd; *start != '\0'; start++) { 1941 const char *p = start; 1942 char endc; 1943 1944 /* XXX: What if progname != "make"? */ 1945 if (strncmp(p, "make", 4) == 0) 1946 if (start == cmd || !ch_isalnum(p[-1])) 1947 if (!ch_isalnum(p[4])) 1948 return true; 1949 1950 if (*p != '$') 1951 continue; 1952 p++; 1953 1954 if (*p == '{') 1955 endc = '}'; 1956 else if (*p == '(') 1957 endc = ')'; 1958 else 1959 continue; 1960 p++; 1961 1962 if (*p == '.') /* Accept either ${.MAKE} or ${MAKE}. */ 1963 p++; 1964 1965 if (strncmp(p, "MAKE", 4) == 0 && p[4] == endc) 1966 return true; 1967 } 1968 return false; 1969 } 1970 1971 /* Append the command to the target node. */ 1972 static void 1973 GNode_AddCommand(GNode *gn, char *cmd) 1974 { 1975 if ((gn->type & OP_DOUBLEDEP) && gn->cohorts.last != NULL) 1976 gn = gn->cohorts.last->datum; 1977 1978 /* if target already supplied, ignore commands */ 1979 if (!(gn->type & OP_HAS_COMMANDS)) { 1980 Lst_Append(&gn->commands, cmd); 1981 if (MaybeSubMake(cmd)) 1982 gn->type |= OP_SUBMAKE; 1983 RememberLocation(gn); 1984 } else { 1985 Parse_Error(PARSE_WARNING, 1986 "duplicate script for target \"%s\" ignored", 1987 gn->name); 1988 ParseErrorInternal(gn, PARSE_WARNING, 1989 "using previous script for \"%s\" defined here", 1990 gn->name); 1991 } 1992 } 1993 1994 /* 1995 * Parse a directive like '.include' or '.-include'. 1996 * 1997 * .include "user-makefile.mk" 1998 * .include <system-makefile.mk> 1999 */ 2000 static void 2001 ParseInclude(char *directive) 2002 { 2003 char endc; /* '>' or '"' */ 2004 char *p; 2005 bool silent = directive[0] != 'i'; 2006 FStr file; 2007 2008 p = directive + (silent ? 8 : 7); 2009 pp_skip_hspace(&p); 2010 2011 if (*p != '"' && *p != '<') { 2012 Parse_Error(PARSE_FATAL, 2013 ".include filename must be delimited by '\"' or '<'"); 2014 return; 2015 } 2016 2017 endc = *p++ == '<' ? '>' : '"'; 2018 file = FStr_InitRefer(p); 2019 2020 while (*p != '\0' && *p != endc) 2021 p++; 2022 2023 if (*p != endc) { 2024 Parse_Error(PARSE_FATAL, 2025 "Unclosed .include filename. '%c' expected", endc); 2026 return; 2027 } 2028 2029 *p = '\0'; 2030 2031 Var_Expand(&file, SCOPE_CMDLINE, VARE_EVAL); 2032 IncludeFile(file.str, endc == '>', directive[0] == 'd', silent); 2033 FStr_Done(&file); 2034 } 2035 2036 /* 2037 * Split filename into dirname + basename, then assign these to the 2038 * given variables. 2039 */ 2040 static void 2041 SetFilenameVars(const char *filename, const char *dirvar, const char *filevar) 2042 { 2043 const char *slash, *basename; 2044 FStr dirname; 2045 2046 slash = strrchr(filename, '/'); 2047 if (slash == NULL) { 2048 dirname = FStr_InitRefer(curdir); 2049 basename = filename; 2050 } else { 2051 dirname = FStr_InitOwn(bmake_strsedup(filename, slash)); 2052 basename = slash + 1; 2053 } 2054 2055 Global_Set(dirvar, dirname.str); 2056 Global_Set(filevar, basename); 2057 2058 DEBUG4(PARSE, "SetFilenameVars: ${%s} = `%s' ${%s} = `%s'\n", 2059 dirvar, dirname.str, filevar, basename); 2060 FStr_Done(&dirname); 2061 } 2062 2063 /* 2064 * Return the immediately including file. 2065 * 2066 * This is made complicated since the .for loop is implemented as a special 2067 * kind of .include; see For_Run. 2068 */ 2069 static const char * 2070 GetActuallyIncludingFile(void) 2071 { 2072 size_t i; 2073 const IncludedFile *incs = GetInclude(0); 2074 2075 for (i = includes.len; i >= 2; i--) 2076 if (incs[i - 1].forLoop == NULL) 2077 return incs[i - 2].name.str; 2078 return NULL; 2079 } 2080 2081 /* Set .PARSEDIR, .PARSEFILE, .INCLUDEDFROMDIR and .INCLUDEDFROMFILE. */ 2082 static void 2083 SetParseFile(const char *filename) 2084 { 2085 const char *including; 2086 2087 SetFilenameVars(filename, ".PARSEDIR", ".PARSEFILE"); 2088 2089 including = GetActuallyIncludingFile(); 2090 if (including != NULL) { 2091 SetFilenameVars(including, 2092 ".INCLUDEDFROMDIR", ".INCLUDEDFROMFILE"); 2093 } else { 2094 Global_Delete(".INCLUDEDFROMDIR"); 2095 Global_Delete(".INCLUDEDFROMFILE"); 2096 } 2097 } 2098 2099 static bool 2100 StrContainsWord(const char *str, const char *word) 2101 { 2102 size_t strLen = strlen(str); 2103 size_t wordLen = strlen(word); 2104 const char *p; 2105 2106 if (strLen < wordLen) 2107 return false; 2108 2109 for (p = str; p != NULL; p = strchr(p, ' ')) { 2110 if (*p == ' ') 2111 p++; 2112 if (p > str + strLen - wordLen) 2113 return false; 2114 2115 if (memcmp(p, word, wordLen) == 0 && 2116 (p[wordLen] == '\0' || p[wordLen] == ' ')) 2117 return true; 2118 } 2119 return false; 2120 } 2121 2122 /* 2123 * XXX: Searching through a set of words with this linear search is 2124 * inefficient for variables that contain thousands of words. 2125 * 2126 * XXX: The paths in this list don't seem to be normalized in any way. 2127 */ 2128 static bool 2129 VarContainsWord(const char *varname, const char *word) 2130 { 2131 FStr val = Var_Value(SCOPE_GLOBAL, varname); 2132 bool found = val.str != NULL && StrContainsWord(val.str, word); 2133 FStr_Done(&val); 2134 return found; 2135 } 2136 2137 /* 2138 * Track the makefiles we read - so makefiles can set dependencies on them. 2139 * Avoid adding anything more than once. 2140 * 2141 * Time complexity: O(n) per call, in total O(n^2), where n is the number 2142 * of makefiles that have been loaded. 2143 */ 2144 static void 2145 TrackInput(const char *name) 2146 { 2147 if (!VarContainsWord(".MAKE.MAKEFILES", name)) 2148 Global_Append(".MAKE.MAKEFILES", name); 2149 } 2150 2151 2152 /* Parse from the given buffer, later return to the current file. */ 2153 void 2154 Parse_PushInput(const char *name, unsigned lineno, unsigned readLines, 2155 Buffer buf, struct ForLoop *forLoop) 2156 { 2157 IncludedFile *curFile; 2158 2159 if (forLoop != NULL) 2160 name = CurFile()->name.str; 2161 else 2162 TrackInput(name); 2163 2164 DEBUG3(PARSE, "Parse_PushInput: %s %s, line %u\n", 2165 forLoop != NULL ? ".for loop in": "file", name, lineno); 2166 2167 curFile = Vector_Push(&includes); 2168 curFile->name = FStr_InitOwn(bmake_strdup(name)); 2169 curFile->lineno = lineno; 2170 curFile->readLines = readLines; 2171 curFile->forHeadLineno = lineno; 2172 curFile->forBodyReadLines = readLines; 2173 curFile->buf = buf; 2174 curFile->depending = doing_depend; /* restore this on EOF */ 2175 curFile->guardState = forLoop == NULL ? GS_START : GS_NO; 2176 curFile->guard = NULL; 2177 curFile->forLoop = forLoop; 2178 2179 if (forLoop != NULL && !For_NextIteration(forLoop, &curFile->buf)) 2180 abort(); /* see For_Run */ 2181 2182 curFile->buf_ptr = curFile->buf.data; 2183 curFile->buf_end = curFile->buf.data + curFile->buf.len; 2184 curFile->condMinDepth = cond_depth; 2185 SetParseFile(name); 2186 } 2187 2188 /* Check if the directive is an include directive. */ 2189 static bool 2190 IsInclude(const char *dir, bool sysv) 2191 { 2192 if (dir[0] == 's' || dir[0] == '-' || (dir[0] == 'd' && !sysv)) 2193 dir++; 2194 2195 if (strncmp(dir, "include", 7) != 0) 2196 return false; 2197 2198 /* Space is not mandatory for BSD .include */ 2199 return !sysv || ch_isspace(dir[7]); 2200 } 2201 2202 2203 /* Check if the line is a SYSV include directive. */ 2204 static bool 2205 IsSysVInclude(const char *line) 2206 { 2207 const char *p; 2208 2209 if (!IsInclude(line, true)) 2210 return false; 2211 2212 /* Avoid interpreting a dependency line as an include */ 2213 for (p = line; (p = strchr(p, ':')) != NULL;) { 2214 2215 /* end of line -> it's a dependency */ 2216 if (*++p == '\0') 2217 return false; 2218 2219 /* '::' operator or ': ' -> it's a dependency */ 2220 if (*p == ':' || ch_isspace(*p)) 2221 return false; 2222 } 2223 return true; 2224 } 2225 2226 /* Push to another file. The line points to the word "include". */ 2227 static void 2228 ParseTraditionalInclude(char *line) 2229 { 2230 char *p; /* current position in file spec */ 2231 bool done = false; 2232 bool silent = line[0] != 'i'; 2233 char *file = line + (silent ? 8 : 7); 2234 char *all_files; 2235 2236 DEBUG1(PARSE, "ParseTraditionalInclude: %s\n", file); 2237 2238 pp_skip_whitespace(&file); 2239 2240 all_files = Var_Subst(file, SCOPE_CMDLINE, VARE_EVAL); 2241 /* TODO: handle errors */ 2242 2243 for (file = all_files; !done; file = p + 1) { 2244 /* Skip to end of line or next whitespace */ 2245 for (p = file; *p != '\0' && !ch_isspace(*p); p++) 2246 continue; 2247 2248 if (*p != '\0') 2249 *p = '\0'; 2250 else 2251 done = true; 2252 2253 IncludeFile(file, false, false, silent); 2254 } 2255 2256 free(all_files); 2257 } 2258 2259 /* Parse "export <variable>=<value>", and actually export it. */ 2260 static void 2261 ParseGmakeExport(char *line) 2262 { 2263 char *variable = line + 6; 2264 char *value; 2265 2266 DEBUG1(PARSE, "ParseGmakeExport: %s\n", variable); 2267 2268 pp_skip_whitespace(&variable); 2269 2270 for (value = variable; *value != '\0' && *value != '='; value++) 2271 continue; 2272 2273 if (*value != '=') { 2274 Parse_Error(PARSE_FATAL, 2275 "Variable/Value missing from \"export\""); 2276 return; 2277 } 2278 *value++ = '\0'; /* terminate variable */ 2279 2280 /* 2281 * Expand the value before putting it in the environment. 2282 */ 2283 value = Var_Subst(value, SCOPE_CMDLINE, VARE_EVAL); 2284 /* TODO: handle errors */ 2285 2286 setenv(variable, value, 1); 2287 free(value); 2288 } 2289 2290 /* 2291 * When the end of the current file or .for loop is reached, continue reading 2292 * the previous file at the previous location. 2293 * 2294 * Results: 2295 * true to continue parsing, i.e. it had only reached the end of an 2296 * included file, false if the main file has been parsed completely. 2297 */ 2298 static bool 2299 ParseEOF(void) 2300 { 2301 IncludedFile *curFile = CurFile(); 2302 2303 doing_depend = curFile->depending; 2304 if (curFile->forLoop != NULL && 2305 For_NextIteration(curFile->forLoop, &curFile->buf)) { 2306 curFile->buf_ptr = curFile->buf.data; 2307 curFile->buf_end = curFile->buf.data + curFile->buf.len; 2308 curFile->readLines = curFile->forBodyReadLines; 2309 return true; 2310 } 2311 2312 Cond_EndFile(); 2313 2314 if (curFile->guardState == GS_DONE) { 2315 HashEntry *he = HashTable_CreateEntry(&guards, 2316 curFile->name.str, NULL); 2317 if (he->value != NULL) { 2318 free(((Guard *)he->value)->name); 2319 free(he->value); 2320 } 2321 HashEntry_Set(he, curFile->guard); 2322 } else if (curFile->guard != NULL) { 2323 free(curFile->guard->name); 2324 free(curFile->guard); 2325 } 2326 2327 FStr_Done(&curFile->name); 2328 Buf_Done(&curFile->buf); 2329 if (curFile->forLoop != NULL) 2330 ForLoop_Free(curFile->forLoop); 2331 Vector_Pop(&includes); 2332 2333 if (includes.len == 0) { 2334 /* We've run out of input */ 2335 Global_Delete(".PARSEDIR"); 2336 Global_Delete(".PARSEFILE"); 2337 Global_Delete(".INCLUDEDFROMDIR"); 2338 Global_Delete(".INCLUDEDFROMFILE"); 2339 return false; 2340 } 2341 2342 curFile = CurFile(); 2343 DEBUG2(PARSE, "ParseEOF: returning to file %s, line %u\n", 2344 curFile->name.str, curFile->readLines + 1); 2345 2346 SetParseFile(curFile->name.str); 2347 return true; 2348 } 2349 2350 typedef enum ParseRawLineResult { 2351 PRLR_LINE, 2352 PRLR_EOF, 2353 PRLR_ERROR 2354 } ParseRawLineResult; 2355 2356 /* 2357 * Parse until the end of a line, taking into account lines that end with 2358 * backslash-newline. The resulting line goes from out_line to out_line_end; 2359 * the line is not null-terminated. 2360 */ 2361 static ParseRawLineResult 2362 ParseRawLine(IncludedFile *curFile, char **out_line, char **out_line_end, 2363 char **out_firstBackslash, char **out_commentLineEnd) 2364 { 2365 char *line = curFile->buf_ptr; 2366 char *buf_end = curFile->buf_end; 2367 char *p = line; 2368 char *line_end = line; 2369 char *firstBackslash = NULL; 2370 char *commentLineEnd = NULL; 2371 ParseRawLineResult res = PRLR_LINE; 2372 2373 curFile->readLines++; 2374 2375 for (;;) { 2376 char ch; 2377 2378 if (p == buf_end) { 2379 res = PRLR_EOF; 2380 break; 2381 } 2382 2383 ch = *p; 2384 if (ch == '\0' || (ch == '\\' && p[1] == '\0')) { 2385 Parse_Error(PARSE_FATAL, "Zero byte read from file"); 2386 exit(2); 2387 } 2388 2389 /* Treat next character after '\' as literal. */ 2390 if (ch == '\\') { 2391 if (firstBackslash == NULL) 2392 firstBackslash = p; 2393 if (p[1] == '\n') { 2394 curFile->readLines++; 2395 if (p + 2 == buf_end) { 2396 line_end = p; 2397 *line_end = '\n'; 2398 p += 2; 2399 continue; 2400 } 2401 } 2402 p += 2; 2403 line_end = p; 2404 assert(p <= buf_end); 2405 continue; 2406 } 2407 2408 /* 2409 * Remember the first '#' for comment stripping, unless 2410 * the previous char was '[', as in the modifier ':[#]'. 2411 */ 2412 if (ch == '#' && commentLineEnd == NULL && 2413 !(p > line && p[-1] == '[')) 2414 commentLineEnd = line_end; 2415 2416 p++; 2417 if (ch == '\n') 2418 break; 2419 2420 /* We are not interested in trailing whitespace. */ 2421 if (!ch_isspace(ch)) 2422 line_end = p; 2423 } 2424 2425 curFile->buf_ptr = p; 2426 *out_line = line; 2427 *out_line_end = line_end; 2428 *out_firstBackslash = firstBackslash; 2429 *out_commentLineEnd = commentLineEnd; 2430 return res; 2431 } 2432 2433 /* 2434 * Beginning at start, unescape '\#' to '#' and replace backslash-newline 2435 * with a single space. 2436 */ 2437 static void 2438 UnescapeBackslash(char *line, char *start) 2439 { 2440 const char *src = start; 2441 char *dst = start; 2442 char *spaceStart = line; 2443 2444 for (;;) { 2445 char ch = *src++; 2446 if (ch != '\\') { 2447 if (ch == '\0') 2448 break; 2449 *dst++ = ch; 2450 continue; 2451 } 2452 2453 ch = *src++; 2454 if (ch == '\0') { 2455 /* Delete '\\' at the end of the buffer. */ 2456 dst--; 2457 break; 2458 } 2459 2460 /* Delete '\\' from before '#' on non-command lines. */ 2461 if (ch == '#' && line[0] != '\t') 2462 *dst++ = ch; 2463 else if (ch == '\n') { 2464 cpp_skip_hspace(&src); 2465 *dst++ = ' '; 2466 } else { 2467 /* Leave '\\' in the buffer for later. */ 2468 *dst++ = '\\'; 2469 *dst++ = ch; 2470 /* Keep an escaped ' ' at the line end. */ 2471 spaceStart = dst; 2472 } 2473 } 2474 2475 /* Delete any trailing spaces - eg from empty continuations */ 2476 while (dst > spaceStart && ch_isspace(dst[-1])) 2477 dst--; 2478 *dst = '\0'; 2479 } 2480 2481 typedef enum LineKind { 2482 /* 2483 * Return the next line that is neither empty nor a comment. 2484 * Backslash line continuations are folded into a single space. 2485 * A trailing comment, if any, is discarded. 2486 */ 2487 LK_NONEMPTY, 2488 2489 /* 2490 * Return the next line, even if it is empty or a comment. 2491 * Preserve backslash-newline to keep the line numbers correct. 2492 * 2493 * Used in .for loops to collect the body of the loop while waiting 2494 * for the corresponding .endfor. 2495 */ 2496 LK_FOR_BODY, 2497 2498 /* 2499 * Return the next line that starts with a dot. 2500 * Backslash line continuations are folded into a single space. 2501 * A trailing comment, if any, is discarded. 2502 * 2503 * Used in .if directives to skip over irrelevant branches while 2504 * waiting for the corresponding .endif. 2505 */ 2506 LK_DOT 2507 } LineKind; 2508 2509 /* 2510 * Return the next "interesting" logical line from the current file. The 2511 * returned string will be freed at the end of including the file. 2512 */ 2513 static char * 2514 ReadLowLevelLine(LineKind kind) 2515 { 2516 IncludedFile *curFile = CurFile(); 2517 ParseRawLineResult res; 2518 char *line; 2519 char *line_end; 2520 char *firstBackslash; 2521 char *commentLineEnd; 2522 2523 for (;;) { 2524 curFile->lineno = curFile->readLines + 1; 2525 res = ParseRawLine(curFile, 2526 &line, &line_end, &firstBackslash, &commentLineEnd); 2527 if (res == PRLR_ERROR) 2528 return NULL; 2529 2530 if (line == line_end || line == commentLineEnd) { 2531 if (res == PRLR_EOF) 2532 return NULL; 2533 if (kind != LK_FOR_BODY) 2534 continue; 2535 } 2536 2537 /* We now have a line of data */ 2538 assert(ch_isspace(*line_end)); 2539 *line_end = '\0'; 2540 2541 if (kind == LK_FOR_BODY) 2542 return line; /* Don't join the physical lines. */ 2543 2544 if (kind == LK_DOT && line[0] != '.') 2545 continue; 2546 break; 2547 } 2548 2549 if (commentLineEnd != NULL && line[0] != '\t') 2550 *commentLineEnd = '\0'; 2551 if (firstBackslash != NULL) 2552 UnescapeBackslash(line, firstBackslash); 2553 return line; 2554 } 2555 2556 static bool 2557 SkipIrrelevantBranches(void) 2558 { 2559 const char *line; 2560 2561 while ((line = ReadLowLevelLine(LK_DOT)) != NULL) 2562 if (Cond_EvalLine(line) == CR_TRUE) 2563 return true; 2564 return false; 2565 } 2566 2567 static bool 2568 ParseForLoop(const char *line) 2569 { 2570 int rval; 2571 unsigned forHeadLineno; 2572 unsigned bodyReadLines; 2573 int forLevel; 2574 2575 rval = For_Eval(line); 2576 if (rval == 0) 2577 return false; /* Not a .for line */ 2578 if (rval < 0) 2579 return true; /* Syntax error - error printed, ignore line */ 2580 2581 forHeadLineno = CurFile()->lineno; 2582 bodyReadLines = CurFile()->readLines; 2583 2584 /* Accumulate the loop body until the matching '.endfor'. */ 2585 forLevel = 1; 2586 do { 2587 line = ReadLowLevelLine(LK_FOR_BODY); 2588 if (line == NULL) { 2589 Parse_Error(PARSE_FATAL, 2590 "Unexpected end of file in .for loop"); 2591 break; 2592 } 2593 } while (For_Accum(line, &forLevel)); 2594 2595 For_Run(forHeadLineno, bodyReadLines); 2596 return true; 2597 } 2598 2599 /* 2600 * Read an entire line from the input file. 2601 * 2602 * Empty lines, .if and .for are handled by this function, while variable 2603 * assignments, other directives, dependency lines and shell commands are 2604 * handled by the caller. 2605 * 2606 * Return a line without trailing whitespace, or NULL for EOF. The returned 2607 * string will be freed at the end of including the file. 2608 */ 2609 static char * 2610 ReadHighLevelLine(void) 2611 { 2612 char *line; 2613 CondResult condResult; 2614 2615 for (;;) { 2616 IncludedFile *curFile = CurFile(); 2617 line = ReadLowLevelLine(LK_NONEMPTY); 2618 if (posix_state == PS_MAYBE_NEXT_LINE) 2619 posix_state = PS_NOW_OR_NEVER; 2620 else 2621 posix_state = PS_TOO_LATE; 2622 if (line == NULL) 2623 return NULL; 2624 2625 DEBUG3(PARSE, "Parsing %s:%u: %s\n", 2626 curFile->name.str, curFile->lineno, line); 2627 if (curFile->guardState != GS_NO 2628 && ((curFile->guardState == GS_START && line[0] != '.') 2629 || curFile->guardState == GS_DONE)) 2630 curFile->guardState = GS_NO; 2631 if (line[0] != '.') 2632 return line; 2633 2634 condResult = Cond_EvalLine(line); 2635 if (curFile->guardState == GS_START) { 2636 Guard *guard; 2637 if (condResult != CR_ERROR 2638 && (guard = Cond_ExtractGuard(line)) != NULL) { 2639 curFile->guardState = GS_COND; 2640 curFile->guard = guard; 2641 } else 2642 curFile->guardState = GS_NO; 2643 } 2644 switch (condResult) { 2645 case CR_FALSE: /* May also mean a syntax error. */ 2646 if (!SkipIrrelevantBranches()) 2647 return NULL; 2648 continue; 2649 case CR_TRUE: 2650 continue; 2651 case CR_ERROR: /* Not a conditional line */ 2652 if (ParseForLoop(line)) 2653 continue; 2654 break; 2655 } 2656 return line; 2657 } 2658 } 2659 2660 static void 2661 FinishDependencyGroup(void) 2662 { 2663 GNodeListNode *ln; 2664 2665 if (targets == NULL) 2666 return; 2667 2668 for (ln = targets->first; ln != NULL; ln = ln->next) { 2669 GNode *gn = ln->datum; 2670 2671 Suff_EndTransform(gn); 2672 2673 /* 2674 * Mark the target as already having commands if it does, to 2675 * keep from having shell commands on multiple dependency 2676 * lines. 2677 */ 2678 if (!Lst_IsEmpty(&gn->commands)) 2679 gn->type |= OP_HAS_COMMANDS; 2680 } 2681 2682 Lst_Free(targets); 2683 targets = NULL; 2684 } 2685 2686 #ifdef CLEANUP 2687 void Parse_RegisterCommand(char *cmd) 2688 { 2689 Lst_Append(&targCmds, cmd); 2690 } 2691 #endif 2692 2693 /* Add the command to each target from the current dependency spec. */ 2694 static void 2695 ParseLine_ShellCommand(const char *p) 2696 { 2697 cpp_skip_whitespace(&p); 2698 if (*p == '\0') 2699 return; /* skip empty commands */ 2700 2701 if (targets == NULL) { 2702 Parse_Error(PARSE_FATAL, 2703 "Unassociated shell command \"%s\"", p); 2704 return; 2705 } 2706 2707 { 2708 char *cmd = bmake_strdup(p); 2709 GNodeListNode *ln; 2710 2711 for (ln = targets->first; ln != NULL; ln = ln->next) { 2712 GNode *gn = ln->datum; 2713 GNode_AddCommand(gn, cmd); 2714 } 2715 Parse_RegisterCommand(cmd); 2716 } 2717 } 2718 2719 static void 2720 HandleBreak(const char *arg) 2721 { 2722 IncludedFile *curFile = CurFile(); 2723 2724 if (arg[0] != '\0') 2725 Parse_Error(PARSE_FATAL, 2726 "The .break directive does not take arguments"); 2727 2728 if (curFile->forLoop != NULL) { 2729 /* pretend we reached EOF */ 2730 For_Break(curFile->forLoop); 2731 cond_depth = CurFile_CondMinDepth(); 2732 ParseEOF(); 2733 } else 2734 Parse_Error(PARSE_FATAL, "break outside of for loop"); 2735 } 2736 2737 /* 2738 * See if the line starts with one of the known directives, and if so, handle 2739 * the directive. 2740 */ 2741 static bool 2742 ParseDirective(char *line) 2743 { 2744 char *p = line + 1; 2745 const char *arg; 2746 Substring dir; 2747 2748 pp_skip_whitespace(&p); 2749 if (IsInclude(p, false)) { 2750 ParseInclude(p); 2751 return true; 2752 } 2753 2754 dir.start = p; 2755 while (ch_islower(*p) || *p == '-') 2756 p++; 2757 dir.end = p; 2758 2759 if (*p != '\0' && !ch_isspace(*p)) 2760 return false; 2761 2762 pp_skip_whitespace(&p); 2763 arg = p; 2764 2765 if (Substring_Equals(dir, "break")) 2766 HandleBreak(arg); 2767 else if (Substring_Equals(dir, "undef")) 2768 Var_Undef(arg); 2769 else if (Substring_Equals(dir, "export")) 2770 Var_Export(VEM_PLAIN, arg); 2771 else if (Substring_Equals(dir, "export-all")) 2772 Var_Export(VEM_ALL, arg); 2773 else if (Substring_Equals(dir, "export-env")) 2774 Var_Export(VEM_ENV, arg); 2775 else if (Substring_Equals(dir, "export-literal")) 2776 Var_Export(VEM_LITERAL, arg); 2777 else if (Substring_Equals(dir, "unexport")) 2778 Var_UnExport(false, arg); 2779 else if (Substring_Equals(dir, "unexport-env")) 2780 Var_UnExport(true, arg); 2781 else if (Substring_Equals(dir, "info")) 2782 HandleMessage(PARSE_INFO, "info", arg); 2783 else if (Substring_Equals(dir, "warning")) 2784 HandleMessage(PARSE_WARNING, "warning", arg); 2785 else if (Substring_Equals(dir, "error")) 2786 HandleMessage(PARSE_FATAL, "error", arg); 2787 else 2788 return false; 2789 return true; 2790 } 2791 2792 bool 2793 Parse_VarAssign(const char *line, bool finishDependencyGroup, GNode *scope) 2794 { 2795 VarAssign var; 2796 2797 if (!Parse_IsVar(line, &var)) 2798 return false; 2799 if (finishDependencyGroup) 2800 FinishDependencyGroup(); 2801 Parse_Var(&var, scope); 2802 free(var.varname); 2803 return true; 2804 } 2805 2806 void 2807 Parse_GuardElse(void) 2808 { 2809 IncludedFile *curFile = CurFile(); 2810 if (cond_depth == curFile->condMinDepth + 1) 2811 curFile->guardState = GS_NO; 2812 } 2813 2814 void 2815 Parse_GuardEndif(void) 2816 { 2817 IncludedFile *curFile = CurFile(); 2818 if (cond_depth == curFile->condMinDepth 2819 && curFile->guardState == GS_COND) 2820 curFile->guardState = GS_DONE; 2821 } 2822 2823 static char * 2824 FindSemicolon(char *p) 2825 { 2826 int depth = 0; 2827 2828 for (; *p != '\0'; p++) { 2829 if (*p == '\\' && p[1] != '\0') { 2830 p++; 2831 continue; 2832 } 2833 2834 if (*p == '$' && (p[1] == '(' || p[1] == '{')) 2835 depth++; 2836 else if (depth > 0 && (*p == ')' || *p == '}')) 2837 depth--; 2838 else if (depth == 0 && *p == ';') 2839 break; 2840 } 2841 return p; 2842 } 2843 2844 static void 2845 ParseDependencyLine(char *line) 2846 { 2847 char *expanded_line; 2848 const char *shellcmd = NULL; 2849 2850 { 2851 char *semicolon = FindSemicolon(line); 2852 if (*semicolon != '\0') { 2853 /* Terminate the dependency list at the ';' */ 2854 *semicolon = '\0'; 2855 shellcmd = semicolon + 1; 2856 } 2857 } 2858 2859 expanded_line = Var_Subst(line, SCOPE_CMDLINE, VARE_EVAL); 2860 /* TODO: handle errors */ 2861 2862 /* Need a fresh list for the target nodes */ 2863 if (targets != NULL) 2864 Lst_Free(targets); 2865 targets = Lst_New(); 2866 2867 ParseDependency(expanded_line, line); 2868 free(expanded_line); 2869 2870 if (shellcmd != NULL) 2871 ParseLine_ShellCommand(shellcmd); 2872 } 2873 2874 static void 2875 ParseLine(char *line) 2876 { 2877 if (line[0] == '.' && ParseDirective(line)) 2878 return; 2879 2880 if (line[0] == '\t') { 2881 ParseLine_ShellCommand(line + 1); 2882 return; 2883 } 2884 2885 if (IsSysVInclude(line)) { 2886 ParseTraditionalInclude(line); 2887 return; 2888 } 2889 2890 if (strncmp(line, "export", 6) == 0 && ch_isspace(line[6]) && 2891 strchr(line, ':') == NULL) { 2892 ParseGmakeExport(line); 2893 return; 2894 } 2895 2896 if (Parse_VarAssign(line, true, SCOPE_GLOBAL)) 2897 return; 2898 2899 FinishDependencyGroup(); 2900 2901 ParseDependencyLine(line); 2902 } 2903 2904 /* Interpret a top-level makefile. */ 2905 void 2906 Parse_File(const char *name, int fd) 2907 { 2908 char *line; 2909 Buffer buf; 2910 2911 buf = LoadFile(name, fd != -1 ? fd : STDIN_FILENO); 2912 if (fd != -1) 2913 (void)close(fd); 2914 2915 assert(targets == NULL); 2916 2917 Parse_PushInput(name, 1, 0, buf, NULL); 2918 2919 do { 2920 while ((line = ReadHighLevelLine()) != NULL) { 2921 ParseLine(line); 2922 } 2923 } while (ParseEOF()); 2924 2925 FinishDependencyGroup(); 2926 2927 if (parseErrors != 0) { 2928 (void)fflush(stdout); 2929 (void)fprintf(stderr, 2930 "%s: Fatal errors encountered -- cannot continue\n", 2931 progname); 2932 PrintOnError(NULL, ""); 2933 exit(1); 2934 } 2935 } 2936 2937 /* Initialize the parsing module. */ 2938 void 2939 Parse_Init(void) 2940 { 2941 mainNode = NULL; 2942 parseIncPath = SearchPath_New(); 2943 sysIncPath = SearchPath_New(); 2944 defSysIncPath = SearchPath_New(); 2945 Vector_Init(&includes, sizeof(IncludedFile)); 2946 HashTable_Init(&guards); 2947 } 2948 2949 #ifdef CLEANUP 2950 /* Clean up the parsing module. */ 2951 void 2952 Parse_End(void) 2953 { 2954 HashIter hi; 2955 2956 Lst_DoneFree(&targCmds); 2957 assert(targets == NULL); 2958 SearchPath_Free(defSysIncPath); 2959 SearchPath_Free(sysIncPath); 2960 SearchPath_Free(parseIncPath); 2961 assert(includes.len == 0); 2962 Vector_Done(&includes); 2963 HashIter_Init(&hi, &guards); 2964 while (HashIter_Next(&hi)) { 2965 Guard *guard = hi.entry->value; 2966 free(guard->name); 2967 free(guard); 2968 } 2969 HashTable_Done(&guards); 2970 } 2971 #endif 2972 2973 2974 /* Populate the list with the single main target to create, or error out. */ 2975 void 2976 Parse_MainName(GNodeList *mainList) 2977 { 2978 if (mainNode == NULL) 2979 Punt("no target to make."); 2980 2981 Lst_Append(mainList, mainNode); 2982 if (mainNode->type & OP_DOUBLEDEP) 2983 Lst_AppendAll(mainList, &mainNode->cohorts); 2984 2985 Global_Append(".TARGETS", mainNode->name); 2986 } 2987