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