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