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