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