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