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