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