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