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