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