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