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