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