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