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