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