parse.c revision 1.708 1 /* $NetBSD: parse.c,v 1.708 2023/11/02 05:40:49 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.708 2023/11/02 05:40:49 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 = 0;
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 * Add the filename and lineno to the GNode so that we remember where its
430 * last command was added or where it 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", gn->name);
862 mainNode = gn;
863 return;
864 }
865 }
866 }
867
868 static void
869 InvalidLineType(const char *line, const char *unexpanded_line)
870 {
871 if (unexpanded_line[0] == '.') {
872 const char *dirstart = unexpanded_line + 1;
873 const char *dirend;
874 cpp_skip_whitespace(&dirstart);
875 dirend = dirstart;
876 while (ch_isalnum(*dirend) || *dirend == '-')
877 dirend++;
878 Parse_Error(PARSE_FATAL, "Unknown directive \"%.*s\"",
879 (int)(dirend - dirstart), dirstart);
880 } else if (strcmp(line, unexpanded_line) == 0)
881 Parse_Error(PARSE_FATAL, "Invalid line '%s'", line);
882 else
883 Parse_Error(PARSE_FATAL, "Invalid line '%s', expanded to '%s'",
884 unexpanded_line, line);
885 }
886
887 static void
888 ParseDependencyTargetWord(char **pp, const char *lstart)
889 {
890 const char *cp = *pp;
891
892 while (*cp != '\0') {
893 if ((ch_isspace(*cp) || *cp == '!' || *cp == ':' ||
894 *cp == '(') &&
895 !IsEscaped(lstart, cp))
896 break;
897
898 if (*cp == '$') {
899 FStr val = Var_Parse(&cp, SCOPE_CMDLINE,
900 VARE_PARSE_ONLY);
901 /* TODO: handle errors */
902 FStr_Done(&val);
903 } else
904 cp++;
905 }
906
907 *pp += cp - *pp;
908 }
909
910 /*
911 * Handle special targets like .PATH, .DEFAULT, .BEGIN, .ORDER.
912 *
913 * See the tests deptgt-*.mk.
914 */
915 static void
916 HandleDependencyTargetSpecial(const char *targetName,
917 ParseSpecial *inout_special,
918 SearchPathList **inout_paths)
919 {
920 switch (*inout_special) {
921 case SP_PATH:
922 if (*inout_paths == NULL)
923 *inout_paths = Lst_New();
924 Lst_Append(*inout_paths, &dirSearchPath);
925 break;
926 case SP_SYSPATH:
927 if (*inout_paths == NULL)
928 *inout_paths = Lst_New();
929 Lst_Append(*inout_paths, sysIncPath);
930 break;
931 case SP_MAIN:
932 /*
933 * Allow targets from the command line to override the
934 * .MAIN node.
935 */
936 if (!Lst_IsEmpty(&opts.create))
937 *inout_special = SP_NOT;
938 break;
939 case SP_BEGIN:
940 case SP_END:
941 case SP_STALE:
942 case SP_ERROR:
943 case SP_INTERRUPT: {
944 GNode *gn = Targ_GetNode(targetName);
945 if (doing_depend)
946 RememberLocation(gn);
947 gn->type |= OP_NOTMAIN | OP_SPECIAL;
948 Lst_Append(targets, gn);
949 break;
950 }
951 case SP_DEFAULT: {
952 /*
953 * Need to create a node to hang commands on, but we don't
954 * want it in the graph, nor do we want it to be the Main
955 * Target. We claim the node is a transformation rule to make
956 * life easier later, when we'll use Make_HandleUse to
957 * actually apply the .DEFAULT commands.
958 */
959 GNode *gn = GNode_New(".DEFAULT");
960 gn->type |= OP_NOTMAIN | OP_TRANSFORM;
961 Lst_Append(targets, gn);
962 defaultNode = gn;
963 break;
964 }
965 case SP_DELETE_ON_ERROR:
966 deleteOnError = true;
967 break;
968 case SP_NOTPARALLEL:
969 opts.maxJobs = 1;
970 break;
971 case SP_SINGLESHELL:
972 opts.compatMake = true;
973 break;
974 case SP_ORDER:
975 order_pred = NULL;
976 break;
977 default:
978 break;
979 }
980 }
981
982 static bool
983 HandleDependencyTargetPath(const char *suffixName,
984 SearchPathList **inout_paths)
985 {
986 SearchPath *path;
987
988 path = Suff_GetPath(suffixName);
989 if (path == NULL) {
990 Parse_Error(PARSE_FATAL,
991 "Suffix '%s' not defined (yet)", suffixName);
992 return false;
993 }
994
995 if (*inout_paths == NULL)
996 *inout_paths = Lst_New();
997 Lst_Append(*inout_paths, path);
998
999 return true;
1000 }
1001
1002 /* See if it's a special target and if so set inout_special to match it. */
1003 static bool
1004 HandleDependencyTarget(const char *targetName,
1005 ParseSpecial *inout_special,
1006 GNodeType *inout_targetAttr,
1007 SearchPathList **inout_paths)
1008 {
1009 int keywd;
1010
1011 if (!(targetName[0] == '.' && ch_isupper(targetName[1])))
1012 return true;
1013
1014 /*
1015 * See if the target is a special target that must have it
1016 * or its sources handled specially.
1017 */
1018 keywd = FindKeyword(targetName);
1019 if (keywd != -1) {
1020 if (*inout_special == SP_PATH &&
1021 parseKeywords[keywd].special != SP_PATH) {
1022 Parse_Error(PARSE_FATAL, "Mismatched special targets");
1023 return false;
1024 }
1025
1026 *inout_special = parseKeywords[keywd].special;
1027 *inout_targetAttr = parseKeywords[keywd].targetAttr;
1028
1029 HandleDependencyTargetSpecial(targetName, inout_special,
1030 inout_paths);
1031
1032 } else if (strncmp(targetName, ".PATH", 5) == 0) {
1033 *inout_special = SP_PATH;
1034 if (!HandleDependencyTargetPath(targetName + 5, inout_paths))
1035 return false;
1036 }
1037 return true;
1038 }
1039
1040 static void
1041 HandleSingleDependencyTargetMundane(const char *name)
1042 {
1043 GNode *gn = Suff_IsTransform(name)
1044 ? Suff_AddTransform(name)
1045 : Targ_GetNode(name);
1046 if (doing_depend)
1047 RememberLocation(gn);
1048
1049 Lst_Append(targets, gn);
1050 }
1051
1052 static void
1053 HandleDependencyTargetMundane(const char *targetName)
1054 {
1055 if (Dir_HasWildcards(targetName)) {
1056 StringList targetNames = LST_INIT;
1057
1058 SearchPath *emptyPath = SearchPath_New();
1059 SearchPath_Expand(emptyPath, targetName, &targetNames);
1060 SearchPath_Free(emptyPath);
1061
1062 while (!Lst_IsEmpty(&targetNames)) {
1063 char *targName = Lst_Dequeue(&targetNames);
1064 HandleSingleDependencyTargetMundane(targName);
1065 free(targName);
1066 }
1067 } else
1068 HandleSingleDependencyTargetMundane(targetName);
1069 }
1070
1071 static void
1072 SkipExtraTargets(char **pp, const char *lstart)
1073 {
1074 bool warning = false;
1075 const char *p = *pp;
1076
1077 while (*p != '\0') {
1078 if (!IsEscaped(lstart, p) && (*p == '!' || *p == ':'))
1079 break;
1080 if (IsEscaped(lstart, p) || (*p != ' ' && *p != '\t'))
1081 warning = true;
1082 p++;
1083 }
1084 if (warning) {
1085 const char *start = *pp;
1086 cpp_skip_whitespace(&start);
1087 Parse_Error(PARSE_WARNING, "Extra target '%.*s' ignored",
1088 (int)(p - start), start);
1089 }
1090
1091 *pp += p - *pp;
1092 }
1093
1094 static void
1095 CheckSpecialMundaneMixture(ParseSpecial special)
1096 {
1097 switch (special) {
1098 case SP_DEFAULT:
1099 case SP_STALE:
1100 case SP_BEGIN:
1101 case SP_END:
1102 case SP_ERROR:
1103 case SP_INTERRUPT:
1104 /*
1105 * These create nodes on which to hang commands, so targets
1106 * shouldn't be empty.
1107 */
1108 case SP_NOT:
1109 /* Nothing special here -- targets may be empty. */
1110 break;
1111 default:
1112 Parse_Error(PARSE_WARNING,
1113 "Special and mundane targets don't mix. "
1114 "Mundane ones ignored");
1115 break;
1116 }
1117 }
1118
1119 /*
1120 * In a dependency line like 'targets: sources' or 'targets! sources', parse
1121 * the operator ':', '::' or '!' from between the targets and the sources.
1122 */
1123 static GNodeType
1124 ParseDependencyOp(char **pp)
1125 {
1126 if (**pp == '!')
1127 return (*pp)++, OP_FORCE;
1128 if (**pp == ':' && (*pp)[1] == ':')
1129 return *pp += 2, OP_DOUBLEDEP;
1130 else if (**pp == ':')
1131 return (*pp)++, OP_DEPENDS;
1132 else
1133 return OP_NONE;
1134 }
1135
1136 static void
1137 ClearPaths(ParseSpecial special, SearchPathList *paths)
1138 {
1139 if (paths != NULL) {
1140 SearchPathListNode *ln;
1141 for (ln = paths->first; ln != NULL; ln = ln->next)
1142 SearchPath_Clear(ln->datum);
1143 }
1144 if (special == SP_SYSPATH)
1145 Dir_SetSYSPATH();
1146 else
1147 Dir_SetPATH();
1148 }
1149
1150 static char *
1151 FindInDirOfIncludingFile(const char *file)
1152 {
1153 char *fullname, *incdir, *slash, *newName;
1154 int i;
1155
1156 fullname = NULL;
1157 incdir = bmake_strdup(CurFile()->name.str);
1158 slash = strrchr(incdir, '/');
1159 if (slash != NULL) {
1160 *slash = '\0';
1161 /*
1162 * Now do lexical processing of leading "../" on the
1163 * filename.
1164 */
1165 for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
1166 slash = strrchr(incdir + 1, '/');
1167 if (slash == NULL || strcmp(slash, "/..") == 0)
1168 break;
1169 *slash = '\0';
1170 }
1171 newName = str_concat3(incdir, "/", file + i);
1172 fullname = Dir_FindFile(newName, parseIncPath);
1173 if (fullname == NULL)
1174 fullname = Dir_FindFile(newName, &dirSearchPath);
1175 free(newName);
1176 }
1177 free(incdir);
1178 return fullname;
1179 }
1180
1181 static char *
1182 FindInQuotPath(const char *file)
1183 {
1184 const char *suff;
1185 SearchPath *suffPath;
1186 char *fullname;
1187
1188 fullname = FindInDirOfIncludingFile(file);
1189 if (fullname == NULL &&
1190 (suff = strrchr(file, '.')) != NULL &&
1191 (suffPath = Suff_GetPath(suff)) != NULL)
1192 fullname = Dir_FindFile(file, suffPath);
1193 if (fullname == NULL)
1194 fullname = Dir_FindFile(file, parseIncPath);
1195 if (fullname == NULL)
1196 fullname = Dir_FindFile(file, &dirSearchPath);
1197 return fullname;
1198 }
1199
1200 static bool
1201 SkipGuarded(const char *fullname)
1202 {
1203 Guard *guard = HashTable_FindValue(&guards, fullname);
1204 if (guard != NULL && guard->kind == GK_VARIABLE
1205 && GNode_ValueDirect(SCOPE_GLOBAL, guard->name) != NULL)
1206 goto skip;
1207 if (guard != NULL && guard->kind == GK_TARGET
1208 && Targ_FindNode(guard->name) != NULL)
1209 goto skip;
1210 return false;
1211
1212 skip:
1213 DEBUG2(PARSE, "Skipping '%s' because '%s' is defined\n",
1214 fullname, guard->name);
1215 return true;
1216 }
1217
1218 /*
1219 * Handle one of the .[-ds]include directives by remembering the current file
1220 * and pushing the included file on the stack. After the included file has
1221 * finished, parsing continues with the including file; see Parse_PushInput
1222 * and ParseEOF.
1223 *
1224 * System includes are looked up in sysIncPath, any other includes are looked
1225 * up in the parsedir and then in the directories specified by the -I command
1226 * line options.
1227 */
1228 static void
1229 IncludeFile(const char *file, bool isSystem, bool depinc, bool silent)
1230 {
1231 Buffer buf;
1232 char *fullname; /* full pathname of file */
1233 int fd;
1234
1235 fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
1236
1237 if (fullname == NULL && !isSystem)
1238 fullname = FindInQuotPath(file);
1239
1240 if (fullname == NULL) {
1241 SearchPath *path = Lst_IsEmpty(&sysIncPath->dirs)
1242 ? defSysIncPath : sysIncPath;
1243 fullname = Dir_FindFile(file, path);
1244 }
1245
1246 if (fullname == NULL) {
1247 if (!silent)
1248 Parse_Error(PARSE_FATAL, "Could not find %s", file);
1249 return;
1250 }
1251
1252 if (SkipGuarded(fullname))
1253 return;
1254
1255 if ((fd = open(fullname, O_RDONLY)) == -1) {
1256 if (!silent)
1257 Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
1258 free(fullname);
1259 return;
1260 }
1261
1262 buf = LoadFile(fullname, fd);
1263 (void)close(fd);
1264
1265 Parse_PushInput(fullname, 1, 0, buf, NULL);
1266 if (depinc)
1267 doing_depend = depinc; /* only turn it on */
1268 free(fullname);
1269 }
1270
1271 /* Handle a "dependency" line like '.SPECIAL:' without any sources. */
1272 static void
1273 HandleDependencySourcesEmpty(ParseSpecial special, SearchPathList *paths)
1274 {
1275 switch (special) {
1276 case SP_SUFFIXES:
1277 Suff_ClearSuffixes();
1278 break;
1279 case SP_PRECIOUS:
1280 allPrecious = true;
1281 break;
1282 case SP_IGNORE:
1283 opts.ignoreErrors = true;
1284 break;
1285 case SP_SILENT:
1286 opts.silent = true;
1287 break;
1288 case SP_PATH:
1289 case SP_SYSPATH:
1290 ClearPaths(special, paths);
1291 break;
1292 #ifdef POSIX
1293 case SP_POSIX:
1294 if (posix_state == PS_NOW_OR_NEVER) {
1295 /*
1296 * With '-r', 'posix.mk' (if it exists)
1297 * can effectively substitute for 'sys.mk',
1298 * otherwise it is an extension.
1299 */
1300 Global_Set("%POSIX", "1003.2");
1301 IncludeFile("posix.mk", true, false, true);
1302 }
1303 break;
1304 #endif
1305 default:
1306 break;
1307 }
1308 }
1309
1310 static void
1311 AddToPaths(const char *dir, SearchPathList *paths)
1312 {
1313 if (paths != NULL) {
1314 SearchPathListNode *ln;
1315 for (ln = paths->first; ln != NULL; ln = ln->next)
1316 (void)SearchPath_Add(ln->datum, dir);
1317 }
1318 }
1319
1320 /*
1321 * If the target was one that doesn't take files as its sources but takes
1322 * something like suffixes, we take each space-separated word on the line as
1323 * a something and deal with it accordingly.
1324 */
1325 static void
1326 ParseDependencySourceSpecial(ParseSpecial special, const char *word,
1327 SearchPathList *paths)
1328 {
1329 switch (special) {
1330 case SP_SUFFIXES:
1331 Suff_AddSuffix(word);
1332 break;
1333 case SP_PATH:
1334 AddToPaths(word, paths);
1335 break;
1336 case SP_INCLUDES:
1337 Suff_AddInclude(word);
1338 break;
1339 case SP_LIBS:
1340 Suff_AddLib(word);
1341 break;
1342 case SP_NOREADONLY:
1343 Var_ReadOnly(word, false);
1344 break;
1345 case SP_NULL:
1346 Suff_SetNull(word);
1347 break;
1348 case SP_OBJDIR:
1349 Main_SetObjdir(false, "%s", word);
1350 break;
1351 case SP_READONLY:
1352 Var_ReadOnly(word, true);
1353 break;
1354 case SP_SYSPATH:
1355 AddToPaths(word, paths);
1356 break;
1357 default:
1358 break;
1359 }
1360 }
1361
1362 static bool
1363 ApplyDependencyTarget(char *name, char *nameEnd, ParseSpecial *inout_special,
1364 GNodeType *inout_targetAttr,
1365 SearchPathList **inout_paths)
1366 {
1367 char savec = *nameEnd;
1368 *nameEnd = '\0';
1369
1370 if (!HandleDependencyTarget(name, inout_special,
1371 inout_targetAttr, inout_paths))
1372 return false;
1373
1374 if (*inout_special == SP_NOT && *name != '\0')
1375 HandleDependencyTargetMundane(name);
1376 else if (*inout_special == SP_PATH && *name != '.' && *name != '\0')
1377 Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", name);
1378
1379 *nameEnd = savec;
1380 return true;
1381 }
1382
1383 static bool
1384 ParseDependencyTargets(char **pp,
1385 const char *lstart,
1386 ParseSpecial *inout_special,
1387 GNodeType *inout_targetAttr,
1388 SearchPathList **inout_paths,
1389 const char *unexpanded_line)
1390 {
1391 char *p = *pp;
1392
1393 for (;;) {
1394 char *tgt = p;
1395
1396 ParseDependencyTargetWord(&p, lstart);
1397
1398 /*
1399 * If the word is followed by a left parenthesis, it's the
1400 * name of one or more files inside an archive.
1401 */
1402 if (!IsEscaped(lstart, p) && *p == '(') {
1403 p = tgt;
1404 if (!Arch_ParseArchive(&p, targets, SCOPE_CMDLINE)) {
1405 Parse_Error(PARSE_FATAL,
1406 "Error in archive specification: \"%s\"",
1407 tgt);
1408 return false;
1409 }
1410 continue;
1411 }
1412
1413 if (*p == '\0') {
1414 InvalidLineType(lstart, unexpanded_line);
1415 return false;
1416 }
1417
1418 if (!ApplyDependencyTarget(tgt, p, inout_special,
1419 inout_targetAttr, inout_paths))
1420 return false;
1421
1422 if (*inout_special != SP_NOT && *inout_special != SP_PATH)
1423 SkipExtraTargets(&p, lstart);
1424 else
1425 pp_skip_whitespace(&p);
1426
1427 if (*p == '\0')
1428 break;
1429 if ((*p == '!' || *p == ':') && !IsEscaped(lstart, p))
1430 break;
1431 }
1432
1433 *pp = p;
1434 return true;
1435 }
1436
1437 static void
1438 ParseDependencySourcesSpecial(char *start,
1439 ParseSpecial special, SearchPathList *paths)
1440 {
1441 char savec;
1442
1443 while (*start != '\0') {
1444 char *end = start;
1445 while (*end != '\0' && !ch_isspace(*end))
1446 end++;
1447 savec = *end;
1448 *end = '\0';
1449 ParseDependencySourceSpecial(special, start, paths);
1450 *end = savec;
1451 if (savec != '\0')
1452 end++;
1453 pp_skip_whitespace(&end);
1454 start = end;
1455 }
1456 }
1457
1458 static void
1459 LinkVarToTargets(VarAssign *var)
1460 {
1461 GNodeListNode *ln;
1462
1463 for (ln = targets->first; ln != NULL; ln = ln->next)
1464 Parse_Var(var, ln->datum);
1465 }
1466
1467 static bool
1468 ParseDependencySourcesMundane(char *start,
1469 ParseSpecial special, GNodeType targetAttr)
1470 {
1471 while (*start != '\0') {
1472 char *end = start;
1473 VarAssign var;
1474
1475 /*
1476 * Check for local variable assignment,
1477 * rest of the line is the value.
1478 */
1479 if (Parse_IsVar(start, &var)) {
1480 /*
1481 * Check if this makefile has disabled
1482 * setting local variables.
1483 */
1484 bool target_vars = GetBooleanExpr(
1485 "${.MAKE.TARGET_LOCAL_VARIABLES}", true);
1486
1487 if (target_vars)
1488 LinkVarToTargets(&var);
1489 free(var.varname);
1490 if (target_vars)
1491 return true;
1492 }
1493
1494 /*
1495 * The targets take real sources, so we must beware of archive
1496 * specifications (i.e. things with left parentheses in them)
1497 * and handle them accordingly.
1498 */
1499 for (; *end != '\0' && !ch_isspace(*end); end++) {
1500 if (*end == '(' && end > start && end[-1] != '$') {
1501 /*
1502 * Only stop for a left parenthesis if it
1503 * isn't at the start of a word (that'll be
1504 * for variable changes later) and isn't
1505 * preceded by a dollar sign (a dynamic
1506 * source).
1507 */
1508 break;
1509 }
1510 }
1511
1512 if (*end == '(') {
1513 GNodeList sources = LST_INIT;
1514 if (!Arch_ParseArchive(&start, &sources,
1515 SCOPE_CMDLINE)) {
1516 Parse_Error(PARSE_FATAL,
1517 "Error in source archive spec \"%s\"",
1518 start);
1519 return false;
1520 }
1521
1522 while (!Lst_IsEmpty(&sources)) {
1523 GNode *gn = Lst_Dequeue(&sources);
1524 ApplyDependencySource(targetAttr, gn->name,
1525 special);
1526 }
1527 Lst_Done(&sources);
1528 end = start;
1529 } else {
1530 if (*end != '\0') {
1531 *end = '\0';
1532 end++;
1533 }
1534
1535 ApplyDependencySource(targetAttr, start, special);
1536 }
1537 pp_skip_whitespace(&end);
1538 start = end;
1539 }
1540 return true;
1541 }
1542
1543 /*
1544 * From a dependency line like 'targets: sources', parse the sources.
1545 *
1546 * See the tests depsrc-*.mk.
1547 */
1548 static void
1549 ParseDependencySources(char *p, GNodeType targetAttr,
1550 ParseSpecial special, SearchPathList **inout_paths)
1551 {
1552 if (*p == '\0') {
1553 HandleDependencySourcesEmpty(special, *inout_paths);
1554 } else if (special == SP_MFLAGS) {
1555 Main_ParseArgLine(p);
1556 return;
1557 } else if (special == SP_SHELL) {
1558 if (!Job_ParseShell(p)) {
1559 Parse_Error(PARSE_FATAL,
1560 "improper shell specification");
1561 return;
1562 }
1563 return;
1564 } else if (special == SP_NOTPARALLEL || special == SP_SINGLESHELL ||
1565 special == SP_DELETE_ON_ERROR) {
1566 return;
1567 }
1568
1569 switch (special) {
1570 case SP_INCLUDES:
1571 case SP_LIBS:
1572 case SP_NOREADONLY:
1573 case SP_NULL:
1574 case SP_OBJDIR:
1575 case SP_PATH:
1576 case SP_READONLY:
1577 case SP_SUFFIXES:
1578 case SP_SYSPATH:
1579 ParseDependencySourcesSpecial(p, special, *inout_paths);
1580 if (*inout_paths != NULL) {
1581 Lst_Free(*inout_paths);
1582 *inout_paths = NULL;
1583 }
1584 if (special == SP_PATH)
1585 Dir_SetPATH();
1586 if (special == SP_SYSPATH)
1587 Dir_SetSYSPATH();
1588 break;
1589 default:
1590 assert(*inout_paths == NULL);
1591 if (!ParseDependencySourcesMundane(p, special, targetAttr))
1592 return;
1593 break;
1594 }
1595
1596 MaybeUpdateMainTarget();
1597 }
1598
1599 /*
1600 * Parse a dependency line consisting of targets, followed by a dependency
1601 * operator, optionally followed by sources.
1602 *
1603 * The nodes of the sources are linked as children to the nodes of the
1604 * targets. Nodes are created as necessary.
1605 *
1606 * The operator is applied to each node in the global 'targets' list,
1607 * which is where the nodes found for the targets are kept.
1608 *
1609 * The sources are parsed in much the same way as the targets, except
1610 * that they are expanded using the wildcarding scheme of the C-Shell,
1611 * and a target is created for each expanded word. Each of the resulting
1612 * nodes is then linked to each of the targets as one of its children.
1613 *
1614 * Certain targets and sources such as .PHONY or .PRECIOUS are handled
1615 * specially, see ParseSpecial.
1616 *
1617 * Transformation rules such as '.c.o' are also handled here, see
1618 * Suff_AddTransform.
1619 *
1620 * Upon return, the value of the line is unspecified.
1621 */
1622 static void
1623 ParseDependency(char *line, const char *unexpanded_line)
1624 {
1625 char *p;
1626 SearchPathList *paths; /* search paths to alter when parsing a list
1627 * of .PATH targets */
1628 GNodeType targetAttr; /* from special sources */
1629 ParseSpecial special; /* in special targets, the children are
1630 * linked as children of the parent but not
1631 * vice versa */
1632 GNodeType op;
1633
1634 DEBUG1(PARSE, "ParseDependency(%s)\n", line);
1635 p = line;
1636 paths = NULL;
1637 targetAttr = OP_NONE;
1638 special = SP_NOT;
1639
1640 if (!ParseDependencyTargets(&p, line, &special, &targetAttr, &paths,
1641 unexpanded_line))
1642 goto out;
1643
1644 if (!Lst_IsEmpty(targets))
1645 CheckSpecialMundaneMixture(special);
1646
1647 op = ParseDependencyOp(&p);
1648 if (op == OP_NONE) {
1649 InvalidLineType(line, unexpanded_line);
1650 goto out;
1651 }
1652 ApplyDependencyOperator(op);
1653
1654 pp_skip_whitespace(&p);
1655
1656 ParseDependencySources(p, targetAttr, special, &paths);
1657
1658 out:
1659 if (paths != NULL)
1660 Lst_Free(paths);
1661 }
1662
1663 /*
1664 * Determine the assignment operator and adjust the end of the variable
1665 * name accordingly.
1666 */
1667 static VarAssign
1668 AdjustVarassignOp(const char *name, const char *nameEnd, const char *op,
1669 const char *value)
1670 {
1671 VarAssignOp type;
1672 VarAssign va;
1673
1674 if (op > name && op[-1] == '+') {
1675 op--;
1676 type = VAR_APPEND;
1677
1678 } else if (op > name && op[-1] == '?') {
1679 op--;
1680 type = VAR_DEFAULT;
1681
1682 } else if (op > name && op[-1] == ':') {
1683 op--;
1684 type = VAR_SUBST;
1685
1686 } else if (op > name && op[-1] == '!') {
1687 op--;
1688 type = VAR_SHELL;
1689
1690 } else {
1691 type = VAR_NORMAL;
1692 #ifdef SUNSHCMD
1693 while (op > name && ch_isspace(op[-1]))
1694 op--;
1695
1696 if (op - name >= 3 && memcmp(op - 3, ":sh", 3) == 0) {
1697 op -= 3;
1698 type = VAR_SHELL;
1699 }
1700 #endif
1701 }
1702
1703 va.varname = bmake_strsedup(name, nameEnd < op ? nameEnd : op);
1704 va.op = type;
1705 va.value = value;
1706 return va;
1707 }
1708
1709 /*
1710 * Parse a variable assignment, consisting of a single-word variable name,
1711 * optional whitespace, an assignment operator, optional whitespace and the
1712 * variable value.
1713 *
1714 * Note: There is a lexical ambiguity with assignment modifier characters
1715 * in variable names. This routine interprets the character before the =
1716 * as a modifier. Therefore, an assignment like
1717 * C++=/usr/bin/CC
1718 * is interpreted as "C+ +=" instead of "C++ =".
1719 *
1720 * Used for both lines in a file and command line arguments.
1721 */
1722 static bool
1723 Parse_IsVar(const char *p, VarAssign *out_var)
1724 {
1725 const char *nameStart, *nameEnd, *firstSpace, *eq;
1726 int level = 0;
1727
1728 cpp_skip_hspace(&p); /* Skip to variable name */
1729
1730 /*
1731 * During parsing, the '+' of the operator '+=' is initially parsed
1732 * as part of the variable name. It is later corrected, as is the
1733 * ':sh' modifier. Of these two (nameEnd and eq), the earlier one
1734 * determines the actual end of the variable name.
1735 */
1736
1737 nameStart = p;
1738 firstSpace = NULL;
1739
1740 /*
1741 * Scan for one of the assignment operators outside a variable
1742 * expansion.
1743 */
1744 while (*p != '\0') {
1745 char ch = *p++;
1746 if (ch == '(' || ch == '{') {
1747 level++;
1748 continue;
1749 }
1750 if (ch == ')' || ch == '}') {
1751 level--;
1752 continue;
1753 }
1754
1755 if (level != 0)
1756 continue;
1757
1758 if ((ch == ' ' || ch == '\t') && firstSpace == NULL)
1759 firstSpace = p - 1;
1760 while (ch == ' ' || ch == '\t')
1761 ch = *p++;
1762
1763 if (ch == '\0')
1764 return false;
1765 #ifdef SUNSHCMD
1766 if (ch == ':' && p[0] == 's' && p[1] == 'h') {
1767 p += 2;
1768 continue;
1769 }
1770 #endif
1771 if (ch == '=')
1772 eq = p - 1;
1773 else if (*p == '=' &&
1774 (ch == '+' || ch == ':' || ch == '?' || ch == '!'))
1775 eq = p;
1776 else if (firstSpace != NULL)
1777 return false;
1778 else
1779 continue;
1780
1781 nameEnd = firstSpace != NULL ? firstSpace : eq;
1782 p = eq + 1;
1783 cpp_skip_whitespace(&p);
1784 *out_var = AdjustVarassignOp(nameStart, nameEnd, eq, p);
1785 return true;
1786 }
1787
1788 return false;
1789 }
1790
1791 /*
1792 * Check for syntax errors such as unclosed expressions or unknown modifiers.
1793 */
1794 static void
1795 VarCheckSyntax(VarAssignOp type, const char *uvalue, GNode *scope)
1796 {
1797 if (opts.strict) {
1798 if (type != VAR_SUBST && strchr(uvalue, '$') != NULL) {
1799 char *expandedValue = Var_Subst(uvalue,
1800 scope, VARE_PARSE_ONLY);
1801 /* TODO: handle errors */
1802 free(expandedValue);
1803 }
1804 }
1805 }
1806
1807 /* Perform a variable assignment that uses the operator ':='. */
1808 static void
1809 VarAssign_EvalSubst(GNode *scope, const char *name, const char *uvalue,
1810 FStr *out_avalue)
1811 {
1812 char *evalue;
1813
1814 /*
1815 * Make sure that we set the variable the first time to nothing
1816 * so that it gets substituted.
1817 *
1818 * TODO: Add a test that demonstrates why this code is needed,
1819 * apart from making the debug log longer.
1820 *
1821 * XXX: The variable name is expanded up to 3 times.
1822 */
1823 if (!Var_ExistsExpand(scope, name))
1824 Var_SetExpand(scope, name, "");
1825
1826 evalue = Var_Subst(uvalue, scope, VARE_KEEP_DOLLAR_UNDEF);
1827 /* TODO: handle errors */
1828
1829 Var_SetExpand(scope, name, evalue);
1830
1831 *out_avalue = FStr_InitOwn(evalue);
1832 }
1833
1834 /* Perform a variable assignment that uses the operator '!='. */
1835 static void
1836 VarAssign_EvalShell(const char *name, const char *uvalue, GNode *scope,
1837 FStr *out_avalue)
1838 {
1839 FStr cmd;
1840 char *output, *error;
1841
1842 cmd = FStr_InitRefer(uvalue);
1843 Var_Expand(&cmd, SCOPE_CMDLINE, VARE_UNDEFERR);
1844
1845 output = Cmd_Exec(cmd.str, &error);
1846 Var_SetExpand(scope, name, output);
1847 *out_avalue = FStr_InitOwn(output);
1848 if (error != NULL) {
1849 Parse_Error(PARSE_WARNING, "%s", error);
1850 free(error);
1851 }
1852
1853 FStr_Done(&cmd);
1854 }
1855
1856 /*
1857 * Perform a variable assignment.
1858 *
1859 * The actual value of the variable is returned in *out_true_avalue.
1860 * Especially for VAR_SUBST and VAR_SHELL this can differ from the literal
1861 * value.
1862 *
1863 * Return whether the assignment was actually performed, which is usually
1864 * the case. It is only skipped if the operator is '?=' and the variable
1865 * already exists.
1866 */
1867 static bool
1868 VarAssign_Eval(const char *name, VarAssignOp op, const char *uvalue,
1869 GNode *scope, FStr *out_true_avalue)
1870 {
1871 FStr avalue = FStr_InitRefer(uvalue);
1872
1873 if (op == VAR_APPEND)
1874 Var_AppendExpand(scope, name, uvalue);
1875 else if (op == VAR_SUBST)
1876 VarAssign_EvalSubst(scope, name, uvalue, &avalue);
1877 else if (op == VAR_SHELL)
1878 VarAssign_EvalShell(name, uvalue, scope, &avalue);
1879 else {
1880 /* XXX: The variable name is expanded up to 2 times. */
1881 if (op == VAR_DEFAULT && Var_ExistsExpand(scope, name))
1882 return false;
1883
1884 /* Normal assignment -- just do it. */
1885 Var_SetExpand(scope, name, uvalue);
1886 }
1887
1888 *out_true_avalue = avalue;
1889 return true;
1890 }
1891
1892 static void
1893 VarAssignSpecial(const char *name, const char *avalue)
1894 {
1895 if (strcmp(name, ".MAKEOVERRIDES") == 0)
1896 Main_ExportMAKEFLAGS(false); /* re-export MAKEFLAGS */
1897 else if (strcmp(name, ".CURDIR") == 0) {
1898 /*
1899 * Someone is being (too?) clever...
1900 * Let's pretend they know what they are doing and
1901 * re-initialize the 'cur' CachedDir.
1902 */
1903 Dir_InitCur(avalue);
1904 Dir_SetPATH();
1905 } else if (strcmp(name, ".MAKE.JOB.PREFIX") == 0)
1906 Job_SetPrefix();
1907 else if (strcmp(name, ".MAKE.EXPORTED") == 0)
1908 Var_ExportVars(avalue);
1909 }
1910
1911 /* Perform the variable assignment in the given scope. */
1912 static void
1913 Parse_Var(VarAssign *var, GNode *scope)
1914 {
1915 FStr avalue; /* actual value (maybe expanded) */
1916
1917 VarCheckSyntax(var->op, var->value, scope);
1918 if (VarAssign_Eval(var->varname, var->op, var->value, scope, &avalue)) {
1919 VarAssignSpecial(var->varname, avalue.str);
1920 FStr_Done(&avalue);
1921 }
1922 }
1923
1924
1925 /*
1926 * See if the command possibly calls a sub-make by using the variable
1927 * expressions ${.MAKE}, ${MAKE} or the plain word "make".
1928 */
1929 static bool
1930 MaybeSubMake(const char *cmd)
1931 {
1932 const char *start;
1933
1934 for (start = cmd; *start != '\0'; start++) {
1935 const char *p = start;
1936 char endc;
1937
1938 /* XXX: What if progname != "make"? */
1939 if (strncmp(p, "make", 4) == 0)
1940 if (start == cmd || !ch_isalnum(p[-1]))
1941 if (!ch_isalnum(p[4]))
1942 return true;
1943
1944 if (*p != '$')
1945 continue;
1946 p++;
1947
1948 if (*p == '{')
1949 endc = '}';
1950 else if (*p == '(')
1951 endc = ')';
1952 else
1953 continue;
1954 p++;
1955
1956 if (*p == '.') /* Accept either ${.MAKE} or ${MAKE}. */
1957 p++;
1958
1959 if (strncmp(p, "MAKE", 4) == 0 && p[4] == endc)
1960 return true;
1961 }
1962 return false;
1963 }
1964
1965 /* Append the command to the target node. */
1966 static void
1967 GNode_AddCommand(GNode *gn, char *cmd)
1968 {
1969 if ((gn->type & OP_DOUBLEDEP) && gn->cohorts.last != NULL)
1970 gn = gn->cohorts.last->datum;
1971
1972 /* if target already supplied, ignore commands */
1973 if (!(gn->type & OP_HAS_COMMANDS)) {
1974 Lst_Append(&gn->commands, cmd);
1975 if (MaybeSubMake(cmd))
1976 gn->type |= OP_SUBMAKE;
1977 RememberLocation(gn);
1978 } else {
1979 #if 0
1980 /* XXX: We cannot do this until we fix the tree */
1981 Lst_Append(&gn->commands, cmd);
1982 Parse_Error(PARSE_WARNING,
1983 "overriding commands for target \"%s\"; "
1984 "previous commands defined at %s: %u ignored",
1985 gn->name, gn->fname, gn->lineno);
1986 #else
1987 Parse_Error(PARSE_WARNING,
1988 "duplicate script for target \"%s\" ignored",
1989 gn->name);
1990 ParseErrorInternal(gn, PARSE_WARNING,
1991 "using previous script for \"%s\" defined here",
1992 gn->name);
1993 #endif
1994 }
1995 }
1996
1997 /*
1998 * Parse a directive like '.include' or '.-include'.
1999 *
2000 * .include "user-makefile.mk"
2001 * .include <system-makefile.mk>
2002 */
2003 static void
2004 ParseInclude(char *directive)
2005 {
2006 char endc; /* '>' or '"' */
2007 char *p;
2008 bool silent = directive[0] != 'i';
2009 FStr file;
2010
2011 p = directive + (silent ? 8 : 7);
2012 pp_skip_hspace(&p);
2013
2014 if (*p != '"' && *p != '<') {
2015 Parse_Error(PARSE_FATAL,
2016 ".include filename must be delimited by '\"' or '<'");
2017 return;
2018 }
2019
2020 if (*p++ == '<')
2021 endc = '>';
2022 else
2023 endc = '"';
2024 file = FStr_InitRefer(p);
2025
2026 while (*p != '\0' && *p != endc)
2027 p++;
2028
2029 if (*p != endc) {
2030 Parse_Error(PARSE_FATAL,
2031 "Unclosed .include filename. '%c' expected", endc);
2032 return;
2033 }
2034
2035 *p = '\0';
2036
2037 Var_Expand(&file, SCOPE_CMDLINE, VARE_WANTRES);
2038 IncludeFile(file.str, endc == '>', directive[0] == 'd', silent);
2039 FStr_Done(&file);
2040 }
2041
2042 /*
2043 * Split filename into dirname + basename, then assign these to the
2044 * given variables.
2045 */
2046 static void
2047 SetFilenameVars(const char *filename, const char *dirvar, const char *filevar)
2048 {
2049 const char *slash, *basename;
2050 FStr dirname;
2051
2052 slash = strrchr(filename, '/');
2053 if (slash == NULL) {
2054 dirname = FStr_InitRefer(curdir);
2055 basename = filename;
2056 } else {
2057 dirname = FStr_InitOwn(bmake_strsedup(filename, slash));
2058 basename = slash + 1;
2059 }
2060
2061 Global_Set(dirvar, dirname.str);
2062 Global_Set(filevar, basename);
2063
2064 DEBUG4(PARSE, "SetFilenameVars: ${%s} = `%s' ${%s} = `%s'\n",
2065 dirvar, dirname.str, filevar, basename);
2066 FStr_Done(&dirname);
2067 }
2068
2069 /*
2070 * Return the immediately including file.
2071 *
2072 * This is made complicated since the .for loop is implemented as a special
2073 * kind of .include; see For_Run.
2074 */
2075 static const char *
2076 GetActuallyIncludingFile(void)
2077 {
2078 size_t i;
2079 const IncludedFile *incs = GetInclude(0);
2080
2081 for (i = includes.len; i >= 2; i--)
2082 if (incs[i - 1].forLoop == NULL)
2083 return incs[i - 2].name.str;
2084 return NULL;
2085 }
2086
2087 /* Set .PARSEDIR, .PARSEFILE, .INCLUDEDFROMDIR and .INCLUDEDFROMFILE. */
2088 static void
2089 SetParseFile(const char *filename)
2090 {
2091 const char *including;
2092
2093 SetFilenameVars(filename, ".PARSEDIR", ".PARSEFILE");
2094
2095 including = GetActuallyIncludingFile();
2096 if (including != NULL) {
2097 SetFilenameVars(including,
2098 ".INCLUDEDFROMDIR", ".INCLUDEDFROMFILE");
2099 } else {
2100 Global_Delete(".INCLUDEDFROMDIR");
2101 Global_Delete(".INCLUDEDFROMFILE");
2102 }
2103 }
2104
2105 static bool
2106 StrContainsWord(const char *str, const char *word)
2107 {
2108 size_t strLen = strlen(str);
2109 size_t wordLen = strlen(word);
2110 const char *p;
2111
2112 if (strLen < wordLen)
2113 return false;
2114
2115 for (p = str; p != NULL; p = strchr(p, ' ')) {
2116 if (*p == ' ')
2117 p++;
2118 if (p > str + strLen - wordLen)
2119 return false;
2120
2121 if (memcmp(p, word, wordLen) == 0 &&
2122 (p[wordLen] == '\0' || p[wordLen] == ' '))
2123 return true;
2124 }
2125 return false;
2126 }
2127
2128 /*
2129 * XXX: Searching through a set of words with this linear search is
2130 * inefficient for variables that contain thousands of words.
2131 *
2132 * XXX: The paths in this list don't seem to be normalized in any way.
2133 */
2134 static bool
2135 VarContainsWord(const char *varname, const char *word)
2136 {
2137 FStr val = Var_Value(SCOPE_GLOBAL, varname);
2138 bool found = val.str != NULL && StrContainsWord(val.str, word);
2139 FStr_Done(&val);
2140 return found;
2141 }
2142
2143 /*
2144 * Track the makefiles we read - so makefiles can set dependencies on them.
2145 * Avoid adding anything more than once.
2146 *
2147 * Time complexity: O(n) per call, in total O(n^2), where n is the number
2148 * of makefiles that have been loaded.
2149 */
2150 static void
2151 TrackInput(const char *name)
2152 {
2153 if (!VarContainsWord(".MAKE.MAKEFILES", name))
2154 Global_Append(".MAKE.MAKEFILES", name);
2155 }
2156
2157
2158 /* Parse from the given buffer, later return to the current file. */
2159 void
2160 Parse_PushInput(const char *name, unsigned lineno, unsigned readLines,
2161 Buffer buf, struct ForLoop *forLoop)
2162 {
2163 IncludedFile *curFile;
2164
2165 if (forLoop != NULL)
2166 name = CurFile()->name.str;
2167 else
2168 TrackInput(name);
2169
2170 DEBUG3(PARSE, "Parse_PushInput: %s %s, line %u\n",
2171 forLoop != NULL ? ".for loop in": "file", name, lineno);
2172
2173 curFile = Vector_Push(&includes);
2174 curFile->name = FStr_InitOwn(bmake_strdup(name));
2175 curFile->lineno = lineno;
2176 curFile->readLines = readLines;
2177 curFile->forHeadLineno = lineno;
2178 curFile->forBodyReadLines = readLines;
2179 curFile->buf = buf;
2180 curFile->depending = doing_depend; /* restore this on EOF */
2181 curFile->guardState = forLoop == NULL ? GS_START : GS_NO;
2182 curFile->guard = NULL;
2183 curFile->forLoop = forLoop;
2184
2185 if (forLoop != NULL && !For_NextIteration(forLoop, &curFile->buf))
2186 abort(); /* see For_Run */
2187
2188 curFile->buf_ptr = curFile->buf.data;
2189 curFile->buf_end = curFile->buf.data + curFile->buf.len;
2190 curFile->condMinDepth = cond_depth;
2191 SetParseFile(name);
2192 }
2193
2194 /* Check if the directive is an include directive. */
2195 static bool
2196 IsInclude(const char *dir, bool sysv)
2197 {
2198 if (dir[0] == 's' || dir[0] == '-' || (dir[0] == 'd' && !sysv))
2199 dir++;
2200
2201 if (strncmp(dir, "include", 7) != 0)
2202 return false;
2203
2204 /* Space is not mandatory for BSD .include */
2205 return !sysv || ch_isspace(dir[7]);
2206 }
2207
2208
2209 #ifdef SYSVINCLUDE
2210 /* Check if the line is a SYSV include directive. */
2211 static bool
2212 IsSysVInclude(const char *line)
2213 {
2214 const char *p;
2215
2216 if (!IsInclude(line, true))
2217 return false;
2218
2219 /* Avoid interpreting a dependency line as an include */
2220 for (p = line; (p = strchr(p, ':')) != NULL;) {
2221
2222 /* end of line -> it's a dependency */
2223 if (*++p == '\0')
2224 return false;
2225
2226 /* '::' operator or ': ' -> it's a dependency */
2227 if (*p == ':' || ch_isspace(*p))
2228 return false;
2229 }
2230 return true;
2231 }
2232
2233 /* Push to another file. The line points to the word "include". */
2234 static void
2235 ParseTraditionalInclude(char *line)
2236 {
2237 char *cp; /* current position in file spec */
2238 bool done = false;
2239 bool silent = line[0] != 'i';
2240 char *file = line + (silent ? 8 : 7);
2241 char *all_files;
2242
2243 DEBUG1(PARSE, "ParseTraditionalInclude: %s\n", file);
2244
2245 pp_skip_whitespace(&file);
2246
2247 all_files = Var_Subst(file, SCOPE_CMDLINE, VARE_WANTRES);
2248 /* TODO: handle errors */
2249
2250 for (file = all_files; !done; file = cp + 1) {
2251 /* Skip to end of line or next whitespace */
2252 for (cp = file; *cp != '\0' && !ch_isspace(*cp); cp++)
2253 continue;
2254
2255 if (*cp != '\0')
2256 *cp = '\0';
2257 else
2258 done = true;
2259
2260 IncludeFile(file, false, false, silent);
2261 }
2262
2263 free(all_files);
2264 }
2265 #endif
2266
2267 #ifdef GMAKEEXPORT
2268 /* Parse "export <variable>=<value>", and actually export it. */
2269 static void
2270 ParseGmakeExport(char *line)
2271 {
2272 char *variable = line + 6;
2273 char *value;
2274
2275 DEBUG1(PARSE, "ParseGmakeExport: %s\n", variable);
2276
2277 pp_skip_whitespace(&variable);
2278
2279 for (value = variable; *value != '\0' && *value != '='; value++)
2280 continue;
2281
2282 if (*value != '=') {
2283 Parse_Error(PARSE_FATAL,
2284 "Variable/Value missing from \"export\"");
2285 return;
2286 }
2287 *value++ = '\0'; /* terminate variable */
2288
2289 /*
2290 * Expand the value before putting it in the environment.
2291 */
2292 value = Var_Subst(value, SCOPE_CMDLINE, VARE_WANTRES);
2293 /* TODO: handle errors */
2294
2295 setenv(variable, value, 1);
2296 free(value);
2297 }
2298 #endif
2299
2300 /*
2301 * When the end of the current file or .for loop is reached, continue reading
2302 * the previous file at the previous location.
2303 *
2304 * Results:
2305 * true to continue parsing, i.e. it had only reached the end of an
2306 * included file, false if the main file has been parsed completely.
2307 */
2308 static bool
2309 ParseEOF(void)
2310 {
2311 IncludedFile *curFile = CurFile();
2312
2313 doing_depend = curFile->depending;
2314 if (curFile->forLoop != NULL &&
2315 For_NextIteration(curFile->forLoop, &curFile->buf)) {
2316 curFile->buf_ptr = curFile->buf.data;
2317 curFile->buf_end = curFile->buf.data + curFile->buf.len;
2318 curFile->readLines = curFile->forBodyReadLines;
2319 return true;
2320 }
2321
2322 Cond_EndFile();
2323
2324 if (curFile->guardState == GS_DONE)
2325 HashTable_Set(&guards, curFile->name.str, curFile->guard);
2326 else if (curFile->guard != NULL) {
2327 free(curFile->guard->name);
2328 free(curFile->guard);
2329 }
2330
2331 FStr_Done(&curFile->name);
2332 Buf_Done(&curFile->buf);
2333 if (curFile->forLoop != NULL)
2334 ForLoop_Free(curFile->forLoop);
2335 Vector_Pop(&includes);
2336
2337 if (includes.len == 0) {
2338 /* We've run out of input */
2339 Global_Delete(".PARSEDIR");
2340 Global_Delete(".PARSEFILE");
2341 Global_Delete(".INCLUDEDFROMDIR");
2342 Global_Delete(".INCLUDEDFROMFILE");
2343 return false;
2344 }
2345
2346 curFile = CurFile();
2347 DEBUG2(PARSE, "ParseEOF: returning to file %s, line %u\n",
2348 curFile->name.str, curFile->readLines + 1);
2349
2350 SetParseFile(curFile->name.str);
2351 return true;
2352 }
2353
2354 typedef enum ParseRawLineResult {
2355 PRLR_LINE,
2356 PRLR_EOF,
2357 PRLR_ERROR
2358 } ParseRawLineResult;
2359
2360 /*
2361 * Parse until the end of a line, taking into account lines that end with
2362 * backslash-newline. The resulting line goes from out_line to out_line_end;
2363 * the line is not null-terminated.
2364 */
2365 static ParseRawLineResult
2366 ParseRawLine(IncludedFile *curFile, char **out_line, char **out_line_end,
2367 char **out_firstBackslash, char **out_commentLineEnd)
2368 {
2369 char *line = curFile->buf_ptr;
2370 char *buf_end = curFile->buf_end;
2371 char *p = line;
2372 char *line_end = line;
2373 char *firstBackslash = NULL;
2374 char *commentLineEnd = NULL;
2375 ParseRawLineResult res = PRLR_LINE;
2376
2377 curFile->readLines++;
2378
2379 for (;;) {
2380 char ch;
2381
2382 if (p == buf_end) {
2383 res = PRLR_EOF;
2384 break;
2385 }
2386
2387 ch = *p;
2388 if (ch == '\0' || (ch == '\\' && p[1] == '\0')) {
2389 Parse_Error(PARSE_FATAL, "Zero byte read from file");
2390 return PRLR_ERROR;
2391 }
2392
2393 /* Treat next character after '\' as literal. */
2394 if (ch == '\\') {
2395 if (firstBackslash == NULL)
2396 firstBackslash = p;
2397 if (p[1] == '\n') {
2398 curFile->readLines++;
2399 if (p + 2 == buf_end) {
2400 line_end = p;
2401 *line_end = '\n';
2402 p += 2;
2403 continue;
2404 }
2405 }
2406 p += 2;
2407 line_end = p;
2408 assert(p <= buf_end);
2409 continue;
2410 }
2411
2412 /*
2413 * Remember the first '#' for comment stripping, unless
2414 * the previous char was '[', as in the modifier ':[#]'.
2415 */
2416 if (ch == '#' && commentLineEnd == NULL &&
2417 !(p > line && p[-1] == '['))
2418 commentLineEnd = line_end;
2419
2420 p++;
2421 if (ch == '\n')
2422 break;
2423
2424 /* We are not interested in trailing whitespace. */
2425 if (!ch_isspace(ch))
2426 line_end = p;
2427 }
2428
2429 curFile->buf_ptr = p;
2430 *out_line = line;
2431 *out_line_end = line_end;
2432 *out_firstBackslash = firstBackslash;
2433 *out_commentLineEnd = commentLineEnd;
2434 return res;
2435 }
2436
2437 /*
2438 * Beginning at start, unescape '\#' to '#' and replace backslash-newline
2439 * with a single space.
2440 */
2441 static void
2442 UnescapeBackslash(char *line, char *start)
2443 {
2444 const char *src = start;
2445 char *dst = start;
2446 char *spaceStart = line;
2447
2448 for (;;) {
2449 char ch = *src++;
2450 if (ch != '\\') {
2451 if (ch == '\0')
2452 break;
2453 *dst++ = ch;
2454 continue;
2455 }
2456
2457 ch = *src++;
2458 if (ch == '\0') {
2459 /* Delete '\\' at the end of the buffer. */
2460 dst--;
2461 break;
2462 }
2463
2464 /* Delete '\\' from before '#' on non-command lines. */
2465 if (ch == '#' && line[0] != '\t')
2466 *dst++ = ch;
2467 else if (ch == '\n') {
2468 cpp_skip_hspace(&src);
2469 *dst++ = ' ';
2470 } else {
2471 /* Leave '\\' in the buffer for later. */
2472 *dst++ = '\\';
2473 *dst++ = ch;
2474 /* Keep an escaped ' ' at the line end. */
2475 spaceStart = dst;
2476 }
2477 }
2478
2479 /* Delete any trailing spaces - eg from empty continuations */
2480 while (dst > spaceStart && ch_isspace(dst[-1]))
2481 dst--;
2482 *dst = '\0';
2483 }
2484
2485 typedef enum LineKind {
2486 /*
2487 * Return the next line that is neither empty nor a comment.
2488 * Backslash line continuations are folded into a single space.
2489 * A trailing comment, if any, is discarded.
2490 */
2491 LK_NONEMPTY,
2492
2493 /*
2494 * Return the next line, even if it is empty or a comment.
2495 * Preserve backslash-newline to keep the line numbers correct.
2496 *
2497 * Used in .for loops to collect the body of the loop while waiting
2498 * for the corresponding .endfor.
2499 */
2500 LK_FOR_BODY,
2501
2502 /*
2503 * Return the next line that starts with a dot.
2504 * Backslash line continuations are folded into a single space.
2505 * A trailing comment, if any, is discarded.
2506 *
2507 * Used in .if directives to skip over irrelevant branches while
2508 * waiting for the corresponding .endif.
2509 */
2510 LK_DOT
2511 } LineKind;
2512
2513 /*
2514 * Return the next "interesting" logical line from the current file. The
2515 * returned string will be freed at the end of including the file.
2516 */
2517 static char *
2518 ReadLowLevelLine(LineKind kind)
2519 {
2520 IncludedFile *curFile = CurFile();
2521 ParseRawLineResult res;
2522 char *line;
2523 char *line_end;
2524 char *firstBackslash;
2525 char *commentLineEnd;
2526
2527 for (;;) {
2528 curFile->lineno = curFile->readLines + 1;
2529 res = ParseRawLine(curFile,
2530 &line, &line_end, &firstBackslash, &commentLineEnd);
2531 if (res == PRLR_ERROR)
2532 return NULL;
2533
2534 if (line == line_end || line == commentLineEnd) {
2535 if (res == PRLR_EOF)
2536 return NULL;
2537 if (kind != LK_FOR_BODY)
2538 continue;
2539 }
2540
2541 /* We now have a line of data */
2542 assert(ch_isspace(*line_end));
2543 *line_end = '\0';
2544
2545 if (kind == LK_FOR_BODY)
2546 return line; /* Don't join the physical lines. */
2547
2548 if (kind == LK_DOT && line[0] != '.')
2549 continue;
2550 break;
2551 }
2552
2553 if (commentLineEnd != NULL && line[0] != '\t')
2554 *commentLineEnd = '\0';
2555 if (firstBackslash != NULL)
2556 UnescapeBackslash(line, firstBackslash);
2557 return line;
2558 }
2559
2560 static bool
2561 SkipIrrelevantBranches(void)
2562 {
2563 const char *line;
2564
2565 while ((line = ReadLowLevelLine(LK_DOT)) != NULL)
2566 if (Cond_EvalLine(line) == CR_TRUE)
2567 return true;
2568 return false;
2569 }
2570
2571 static bool
2572 ParseForLoop(const char *line)
2573 {
2574 int rval;
2575 unsigned forHeadLineno;
2576 unsigned bodyReadLines;
2577 int forLevel;
2578
2579 rval = For_Eval(line);
2580 if (rval == 0)
2581 return false; /* Not a .for line */
2582 if (rval < 0)
2583 return true; /* Syntax error - error printed, ignore line */
2584
2585 forHeadLineno = CurFile()->lineno;
2586 bodyReadLines = CurFile()->readLines;
2587
2588 /* Accumulate the loop body until the matching '.endfor'. */
2589 forLevel = 1;
2590 do {
2591 line = ReadLowLevelLine(LK_FOR_BODY);
2592 if (line == NULL) {
2593 Parse_Error(PARSE_FATAL,
2594 "Unexpected end of file in .for loop");
2595 break;
2596 }
2597 } while (For_Accum(line, &forLevel));
2598
2599 For_Run(forHeadLineno, bodyReadLines);
2600 return true;
2601 }
2602
2603 /*
2604 * Read an entire line from the input file.
2605 *
2606 * Empty lines, .if and .for are handled by this function, while variable
2607 * assignments, other directives, dependency lines and shell commands are
2608 * handled by the caller.
2609 *
2610 * Return a line without trailing whitespace, or NULL for EOF. The returned
2611 * string will be freed at the end of including the file.
2612 */
2613 static char *
2614 ReadHighLevelLine(void)
2615 {
2616 char *line;
2617 CondResult condResult;
2618
2619 for (;;) {
2620 IncludedFile *curFile = CurFile();
2621 line = ReadLowLevelLine(LK_NONEMPTY);
2622 if (posix_state == PS_MAYBE_NEXT_LINE)
2623 posix_state = PS_NOW_OR_NEVER;
2624 else
2625 posix_state = PS_TOO_LATE;
2626 if (line == NULL)
2627 return NULL;
2628
2629 if (curFile->guardState != GS_NO
2630 && ((curFile->guardState == GS_START && line[0] != '.')
2631 || curFile->guardState == GS_DONE))
2632 curFile->guardState = GS_NO;
2633 if (line[0] != '.')
2634 return line;
2635
2636 condResult = Cond_EvalLine(line);
2637 if (curFile->guardState == GS_START) {
2638 Guard *guard;
2639 if (condResult != CR_ERROR
2640 && (guard = Cond_ExtractGuard(line)) != NULL) {
2641 curFile->guardState = GS_COND;
2642 curFile->guard = guard;
2643 } else
2644 curFile->guardState = GS_NO;
2645 }
2646 switch (condResult) {
2647 case CR_FALSE: /* May also mean a syntax error. */
2648 if (!SkipIrrelevantBranches())
2649 return NULL;
2650 continue;
2651 case CR_TRUE:
2652 continue;
2653 case CR_ERROR: /* Not a conditional line */
2654 if (ParseForLoop(line))
2655 continue;
2656 break;
2657 }
2658 return line;
2659 }
2660 }
2661
2662 static void
2663 FinishDependencyGroup(void)
2664 {
2665 GNodeListNode *ln;
2666
2667 if (targets == NULL)
2668 return;
2669
2670 for (ln = targets->first; ln != NULL; ln = ln->next) {
2671 GNode *gn = ln->datum;
2672
2673 Suff_EndTransform(gn);
2674
2675 /*
2676 * Mark the target as already having commands if it does, to
2677 * keep from having shell commands on multiple dependency
2678 * lines.
2679 */
2680 if (!Lst_IsEmpty(&gn->commands))
2681 gn->type |= OP_HAS_COMMANDS;
2682 }
2683
2684 Lst_Free(targets);
2685 targets = NULL;
2686 }
2687
2688 /* Add the command to each target from the current dependency spec. */
2689 static void
2690 ParseLine_ShellCommand(const char *p)
2691 {
2692 cpp_skip_whitespace(&p);
2693 if (*p == '\0')
2694 return; /* skip empty commands */
2695
2696 if (targets == NULL) {
2697 Parse_Error(PARSE_FATAL,
2698 "Unassociated shell command \"%s\"", p);
2699 return;
2700 }
2701
2702 {
2703 char *cmd = bmake_strdup(p);
2704 GNodeListNode *ln;
2705
2706 for (ln = targets->first; ln != NULL; ln = ln->next) {
2707 GNode *gn = ln->datum;
2708 GNode_AddCommand(gn, cmd);
2709 }
2710 #ifdef CLEANUP
2711 Lst_Append(&targCmds, cmd);
2712 #endif
2713 }
2714 }
2715
2716 static void
2717 HandleBreak(const char *arg)
2718 {
2719 IncludedFile *curFile = CurFile();
2720
2721 if (arg[0] != '\0')
2722 Parse_Error(PARSE_FATAL,
2723 "The .break directive does not take arguments");
2724
2725 if (curFile->forLoop != NULL) {
2726 /* pretend we reached EOF */
2727 For_Break(curFile->forLoop);
2728 cond_depth = CurFile_CondMinDepth();
2729 ParseEOF();
2730 } else
2731 Parse_Error(PARSE_FATAL, "break outside of for loop");
2732 }
2733
2734 /*
2735 * See if the line starts with one of the known directives, and if so, handle
2736 * the directive.
2737 */
2738 static bool
2739 ParseDirective(char *line)
2740 {
2741 char *cp = line + 1;
2742 const char *arg;
2743 Substring dir;
2744
2745 pp_skip_whitespace(&cp);
2746 if (IsInclude(cp, false)) {
2747 ParseInclude(cp);
2748 return true;
2749 }
2750
2751 dir.start = cp;
2752 while (ch_islower(*cp) || *cp == '-')
2753 cp++;
2754 dir.end = cp;
2755
2756 if (*cp != '\0' && !ch_isspace(*cp))
2757 return false;
2758
2759 pp_skip_whitespace(&cp);
2760 arg = cp;
2761
2762 if (Substring_Equals(dir, "break"))
2763 HandleBreak(arg);
2764 else if (Substring_Equals(dir, "undef"))
2765 Var_Undef(arg);
2766 else if (Substring_Equals(dir, "export"))
2767 Var_Export(VEM_PLAIN, arg);
2768 else if (Substring_Equals(dir, "export-env"))
2769 Var_Export(VEM_ENV, arg);
2770 else if (Substring_Equals(dir, "export-literal"))
2771 Var_Export(VEM_LITERAL, arg);
2772 else if (Substring_Equals(dir, "unexport"))
2773 Var_UnExport(false, arg);
2774 else if (Substring_Equals(dir, "unexport-env"))
2775 Var_UnExport(true, arg);
2776 else if (Substring_Equals(dir, "info"))
2777 HandleMessage(PARSE_INFO, "info", arg);
2778 else if (Substring_Equals(dir, "warning"))
2779 HandleMessage(PARSE_WARNING, "warning", arg);
2780 else if (Substring_Equals(dir, "error"))
2781 HandleMessage(PARSE_FATAL, "error", arg);
2782 else
2783 return false;
2784 return true;
2785 }
2786
2787 bool
2788 Parse_VarAssign(const char *line, bool finishDependencyGroup, GNode *scope)
2789 {
2790 VarAssign var;
2791
2792 if (!Parse_IsVar(line, &var))
2793 return false;
2794 if (finishDependencyGroup)
2795 FinishDependencyGroup();
2796 Parse_Var(&var, scope);
2797 free(var.varname);
2798 return true;
2799 }
2800
2801 void
2802 Parse_GuardElse(void)
2803 {
2804 IncludedFile *curFile = CurFile();
2805 if (cond_depth == curFile->condMinDepth + 1)
2806 curFile->guardState = GS_NO;
2807 }
2808
2809 void
2810 Parse_GuardEndif(void)
2811 {
2812 IncludedFile *curFile = CurFile();
2813 if (cond_depth == curFile->condMinDepth
2814 && curFile->guardState == GS_COND)
2815 curFile->guardState = GS_DONE;
2816 }
2817
2818 static char *
2819 FindSemicolon(char *p)
2820 {
2821 int level = 0;
2822
2823 for (; *p != '\0'; p++) {
2824 if (*p == '\\' && p[1] != '\0') {
2825 p++;
2826 continue;
2827 }
2828
2829 if (*p == '$' && (p[1] == '(' || p[1] == '{'))
2830 level++;
2831 else if (level > 0 && (*p == ')' || *p == '}'))
2832 level--;
2833 else if (level == 0 && *p == ';')
2834 break;
2835 }
2836 return p;
2837 }
2838
2839 static void
2840 ParseDependencyLine(char *line)
2841 {
2842 VarEvalMode emode;
2843 char *expanded_line;
2844 const char *shellcmd = NULL;
2845
2846 {
2847 char *semicolon = FindSemicolon(line);
2848 if (*semicolon != '\0') {
2849 /* Terminate the dependency list at the ';' */
2850 *semicolon = '\0';
2851 shellcmd = semicolon + 1;
2852 }
2853 }
2854
2855 /*
2856 * We now know it's a dependency line, so it needs to have all
2857 * variables expanded before being parsed.
2858 *
2859 * XXX: Ideally the dependency line would first be split into
2860 * its left-hand side, dependency operator and right-hand side,
2861 * and then each side would be expanded on its own. This would
2862 * allow for the left-hand side to allow only defined variables
2863 * and to allow variables on the right-hand side to be undefined
2864 * as well.
2865 *
2866 * Parsing the line first would also prevent that targets
2867 * generated from variable expressions are interpreted as the
2868 * dependency operator, such as in "target${:U\:} middle: source",
2869 * in which the middle is interpreted as a source, not a target.
2870 */
2871
2872 /*
2873 * In lint mode, allow undefined variables to appear in dependency
2874 * lines.
2875 *
2876 * Ideally, only the right-hand side would allow undefined variables
2877 * since it is common to have optional dependencies. Having undefined
2878 * variables on the left-hand side is more unusual though. Since
2879 * both sides are expanded in a single pass, there is not much choice
2880 * what to do here.
2881 *
2882 * In normal mode, it does not matter whether undefined variables are
2883 * allowed or not since as of 2020-09-14, Var_Parse does not print
2884 * any parse errors in such a case. It simply returns the special
2885 * empty string var_Error, which cannot be detected in the result of
2886 * Var_Subst.
2887 */
2888 emode = opts.strict ? VARE_WANTRES : VARE_UNDEFERR;
2889 expanded_line = Var_Subst(line, SCOPE_CMDLINE, emode);
2890 /* TODO: handle errors */
2891
2892 /* Need a fresh list for the target nodes */
2893 if (targets != NULL)
2894 Lst_Free(targets);
2895 targets = Lst_New();
2896
2897 ParseDependency(expanded_line, line);
2898 free(expanded_line);
2899
2900 if (shellcmd != NULL)
2901 ParseLine_ShellCommand(shellcmd);
2902 }
2903
2904 static void
2905 ParseLine(char *line)
2906 {
2907 /*
2908 * Lines that begin with '.' can be pretty much anything:
2909 * - directives like '.include' or '.if',
2910 * - suffix rules like '.c.o:',
2911 * - dependencies for filenames that start with '.',
2912 * - variable assignments like '.tmp=value'.
2913 */
2914 if (line[0] == '.' && ParseDirective(line))
2915 return;
2916
2917 if (line[0] == '\t') {
2918 ParseLine_ShellCommand(line + 1);
2919 return;
2920 }
2921
2922 #ifdef SYSVINCLUDE
2923 if (IsSysVInclude(line)) {
2924 ParseTraditionalInclude(line);
2925 return;
2926 }
2927 #endif
2928
2929 #ifdef GMAKEEXPORT
2930 if (strncmp(line, "export", 6) == 0 && ch_isspace(line[6]) &&
2931 strchr(line, ':') == NULL) {
2932 ParseGmakeExport(line);
2933 return;
2934 }
2935 #endif
2936
2937 if (Parse_VarAssign(line, true, SCOPE_GLOBAL))
2938 return;
2939
2940 FinishDependencyGroup();
2941
2942 ParseDependencyLine(line);
2943 }
2944
2945 /* Interpret a top-level makefile. */
2946 void
2947 Parse_File(const char *name, int fd)
2948 {
2949 char *line;
2950 Buffer buf;
2951
2952 buf = LoadFile(name, fd != -1 ? fd : STDIN_FILENO);
2953 if (fd != -1)
2954 (void)close(fd);
2955
2956 assert(targets == NULL);
2957
2958 Parse_PushInput(name, 1, 0, buf, NULL);
2959
2960 do {
2961 while ((line = ReadHighLevelLine()) != NULL) {
2962 DEBUG2(PARSE, "Parsing line %u: %s\n",
2963 CurFile()->lineno, line);
2964 ParseLine(line);
2965 }
2966 } while (ParseEOF());
2967
2968 FinishDependencyGroup();
2969
2970 if (parseErrors != 0) {
2971 (void)fflush(stdout);
2972 (void)fprintf(stderr,
2973 "%s: Fatal errors encountered -- cannot continue\n",
2974 progname);
2975 PrintOnError(NULL, "");
2976 exit(1);
2977 }
2978 }
2979
2980 /* Initialize the parsing module. */
2981 void
2982 Parse_Init(void)
2983 {
2984 mainNode = NULL;
2985 parseIncPath = SearchPath_New();
2986 sysIncPath = SearchPath_New();
2987 defSysIncPath = SearchPath_New();
2988 Vector_Init(&includes, sizeof(IncludedFile));
2989 HashTable_Init(&guards);
2990 }
2991
2992 /* Clean up the parsing module. */
2993 void
2994 Parse_End(void)
2995 {
2996 #ifdef CLEANUP
2997 HashIter hi;
2998
2999 Lst_DoneCall(&targCmds, free);
3000 assert(targets == NULL);
3001 SearchPath_Free(defSysIncPath);
3002 SearchPath_Free(sysIncPath);
3003 SearchPath_Free(parseIncPath);
3004 assert(includes.len == 0);
3005 Vector_Done(&includes);
3006 HashIter_Init(&hi, &guards);
3007 while (HashIter_Next(&hi) != NULL) {
3008 Guard *guard = hi.entry->value;
3009 free(guard->name);
3010 free(guard);
3011 }
3012 HashTable_Done(&guards);
3013 #endif
3014 }
3015
3016
3017 /* Populate the list with the single main target to create, or error out. */
3018 void
3019 Parse_MainName(GNodeList *mainList)
3020 {
3021 if (mainNode == NULL)
3022 Punt("no target to make.");
3023
3024 Lst_Append(mainList, mainNode);
3025 if (mainNode->type & OP_DOUBLEDEP)
3026 Lst_AppendAll(mainList, &mainNode->cohorts);
3027
3028 Global_Append(".TARGETS", mainNode->name);
3029 }
3030
3031 int
3032 Parse_NumErrors(void)
3033 {
3034 return parseErrors;
3035 }
3036