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