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