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