parse.c revision 1.604 1 /* $NetBSD: parse.c,v 1.604 2021/12/29 05:01:35 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.604 2021/12/29 05:01:35 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 struct VarAssignParsed {
1629 const char *nameStart; /* unexpanded */
1630 const char *nameEnd; /* before operator adjustment */
1631 const char *eq; /* the '=' of the assignment operator */
1632 } VarAssignParsed;
1633
1634 /*
1635 * Determine the assignment operator and adjust the end of the variable
1636 * name accordingly.
1637 */
1638 static void
1639 AdjustVarassignOp(const VarAssignParsed *pvar, const char *value,
1640 VarAssign *out_var)
1641 {
1642 const char *op = pvar->eq;
1643 const char *const name = pvar->nameStart;
1644 VarAssignOp type;
1645
1646 if (op > name && op[-1] == '+') {
1647 op--;
1648 type = VAR_APPEND;
1649
1650 } else if (op > name && op[-1] == '?') {
1651 op--;
1652 type = VAR_DEFAULT;
1653
1654 } else if (op > name && op[-1] == ':') {
1655 op--;
1656 type = VAR_SUBST;
1657
1658 } else if (op > name && op[-1] == '!') {
1659 op--;
1660 type = VAR_SHELL;
1661
1662 } else {
1663 type = VAR_NORMAL;
1664 #ifdef SUNSHCMD
1665 while (op > name && ch_isspace(op[-1]))
1666 op--;
1667
1668 if (op >= name + 3 && memcmp(op - 3, ":sh", 3) == 0) {
1669 op -= 3;
1670 type = VAR_SHELL;
1671 }
1672 #endif
1673 }
1674
1675 {
1676 const char *nameEnd = pvar->nameEnd < op ? pvar->nameEnd : op;
1677 out_var->varname = bmake_strsedup(pvar->nameStart, nameEnd);
1678 out_var->op = type;
1679 out_var->value = value;
1680 }
1681 }
1682
1683 /*
1684 * Parse a variable assignment, consisting of a single-word variable name,
1685 * optional whitespace, an assignment operator, optional whitespace and the
1686 * variable value.
1687 *
1688 * Note: There is a lexical ambiguity with assignment modifier characters
1689 * in variable names. This routine interprets the character before the =
1690 * as a modifier. Therefore, an assignment like
1691 * C++=/usr/bin/CC
1692 * is interpreted as "C+ +=" instead of "C++ =".
1693 *
1694 * Used for both lines in a file and command line arguments.
1695 */
1696 bool
1697 Parse_IsVar(const char *p, VarAssign *out_var)
1698 {
1699 VarAssignParsed pvar;
1700 const char *firstSpace = NULL;
1701 int level = 0;
1702
1703 cpp_skip_hspace(&p); /* Skip to variable name */
1704
1705 /*
1706 * During parsing, the '+' of the '+=' operator is initially parsed
1707 * as part of the variable name. It is later corrected, as is the
1708 * ':sh' modifier. Of these two (nameEnd and op), the earlier one
1709 * determines the actual end of the variable name.
1710 */
1711 pvar.nameStart = p;
1712 #ifdef CLEANUP
1713 pvar.nameEnd = NULL;
1714 pvar.eq = NULL;
1715 #endif
1716
1717 /*
1718 * Scan for one of the assignment operators outside a variable
1719 * expansion.
1720 */
1721 while (*p != '\0') {
1722 char ch = *p++;
1723 if (ch == '(' || ch == '{') {
1724 level++;
1725 continue;
1726 }
1727 if (ch == ')' || ch == '}') {
1728 level--;
1729 continue;
1730 }
1731
1732 if (level != 0)
1733 continue;
1734
1735 if (ch == ' ' || ch == '\t')
1736 if (firstSpace == NULL)
1737 firstSpace = p - 1;
1738 while (ch == ' ' || ch == '\t')
1739 ch = *p++;
1740
1741 #ifdef SUNSHCMD
1742 if (ch == ':' && p[0] == 's' && p[1] == 'h') {
1743 p += 2;
1744 continue;
1745 }
1746 #endif
1747 if (ch == '=') {
1748 pvar.eq = p - 1;
1749 pvar.nameEnd = firstSpace != NULL ? firstSpace : p - 1;
1750 cpp_skip_whitespace(&p);
1751 AdjustVarassignOp(&pvar, p, out_var);
1752 return true;
1753 }
1754 if (*p == '=' &&
1755 (ch == '+' || ch == ':' || ch == '?' || ch == '!')) {
1756 pvar.eq = p;
1757 pvar.nameEnd = firstSpace != NULL ? firstSpace : p;
1758 p++;
1759 cpp_skip_whitespace(&p);
1760 AdjustVarassignOp(&pvar, p, out_var);
1761 return true;
1762 }
1763 if (firstSpace != NULL)
1764 return false;
1765 }
1766
1767 return false;
1768 }
1769
1770 /*
1771 * Check for syntax errors such as unclosed expressions or unknown modifiers.
1772 */
1773 static void
1774 VarCheckSyntax(VarAssignOp type, const char *uvalue, GNode *scope)
1775 {
1776 if (opts.strict) {
1777 if (type != VAR_SUBST && strchr(uvalue, '$') != NULL) {
1778 char *expandedValue;
1779
1780 (void)Var_Subst(uvalue, scope, VARE_PARSE_ONLY,
1781 &expandedValue);
1782 /* TODO: handle errors */
1783 free(expandedValue);
1784 }
1785 }
1786 }
1787
1788 static void
1789 VarAssign_EvalSubst(GNode *scope, const char *name, const char *uvalue,
1790 FStr *out_avalue)
1791 {
1792 char *evalue;
1793
1794 /*
1795 * make sure that we set the variable the first time to nothing
1796 * so that it gets substituted.
1797 *
1798 * TODO: Add a test that demonstrates why this code is needed,
1799 * apart from making the debug log longer.
1800 */
1801 if (!Var_ExistsExpand(scope, name))
1802 Var_SetExpand(scope, name, "");
1803
1804 (void)Var_Subst(uvalue, scope, VARE_KEEP_DOLLAR_UNDEF, &evalue);
1805 /* TODO: handle errors */
1806
1807 Var_SetExpand(scope, name, evalue);
1808
1809 *out_avalue = FStr_InitOwn(evalue);
1810 }
1811
1812 static void
1813 VarAssign_EvalShell(const char *name, const char *uvalue, GNode *scope,
1814 FStr *out_avalue)
1815 {
1816 FStr cmd;
1817 const char *errfmt;
1818 char *cmdOut;
1819
1820 cmd = FStr_InitRefer(uvalue);
1821 if (strchr(cmd.str, '$') != NULL) {
1822 char *expanded;
1823 (void)Var_Subst(cmd.str, SCOPE_CMDLINE, VARE_UNDEFERR,
1824 &expanded);
1825 /* TODO: handle errors */
1826 cmd = FStr_InitOwn(expanded);
1827 }
1828
1829 cmdOut = Cmd_Exec(cmd.str, &errfmt);
1830 Var_SetExpand(scope, name, cmdOut);
1831 *out_avalue = FStr_InitOwn(cmdOut);
1832
1833 if (errfmt != NULL)
1834 Parse_Error(PARSE_WARNING, errfmt, cmd.str);
1835
1836 FStr_Done(&cmd);
1837 }
1838
1839 /*
1840 * Perform a variable assignment.
1841 *
1842 * The actual value of the variable is returned in *out_true_avalue.
1843 * Especially for VAR_SUBST and VAR_SHELL this can differ from the literal
1844 * value.
1845 *
1846 * Return whether the assignment was actually performed, which is usually
1847 * the case. It is only skipped if the operator is '?=' and the variable
1848 * already exists.
1849 */
1850 static bool
1851 VarAssign_Eval(const char *name, VarAssignOp op, const char *uvalue,
1852 GNode *scope, FStr *out_true_avalue)
1853 {
1854 FStr avalue = FStr_InitRefer(uvalue);
1855
1856 if (op == VAR_APPEND)
1857 Var_AppendExpand(scope, name, uvalue);
1858 else if (op == VAR_SUBST)
1859 VarAssign_EvalSubst(scope, name, uvalue, &avalue);
1860 else if (op == VAR_SHELL)
1861 VarAssign_EvalShell(name, uvalue, scope, &avalue);
1862 else {
1863 if (op == VAR_DEFAULT && Var_ExistsExpand(scope, name))
1864 return false;
1865
1866 /* Normal assignment -- just do it. */
1867 Var_SetExpand(scope, name, uvalue);
1868 }
1869
1870 *out_true_avalue = avalue;
1871 return true;
1872 }
1873
1874 static void
1875 VarAssignSpecial(const char *name, const char *avalue)
1876 {
1877 if (strcmp(name, MAKEOVERRIDES) == 0)
1878 Main_ExportMAKEFLAGS(false); /* re-export MAKEFLAGS */
1879 else if (strcmp(name, ".CURDIR") == 0) {
1880 /*
1881 * Someone is being (too?) clever...
1882 * Let's pretend they know what they are doing and
1883 * re-initialize the 'cur' CachedDir.
1884 */
1885 Dir_InitCur(avalue);
1886 Dir_SetPATH();
1887 } else if (strcmp(name, MAKE_JOB_PREFIX) == 0)
1888 Job_SetPrefix();
1889 else if (strcmp(name, MAKE_EXPORTED) == 0)
1890 Var_ExportVars(avalue);
1891 }
1892
1893 /* Perform the variable assignment in the given scope. */
1894 void
1895 Parse_Var(VarAssign *var, GNode *scope)
1896 {
1897 FStr avalue; /* actual value (maybe expanded) */
1898
1899 VarCheckSyntax(var->op, var->value, scope);
1900 if (VarAssign_Eval(var->varname, var->op, var->value, scope, &avalue)) {
1901 VarAssignSpecial(var->varname, avalue.str);
1902 FStr_Done(&avalue);
1903 }
1904
1905 free(var->varname);
1906 }
1907
1908
1909 /*
1910 * See if the command possibly calls a sub-make by using the variable
1911 * expressions ${.MAKE}, ${MAKE} or the plain word "make".
1912 */
1913 static bool
1914 MaybeSubMake(const char *cmd)
1915 {
1916 const char *start;
1917
1918 for (start = cmd; *start != '\0'; start++) {
1919 const char *p = start;
1920 char endc;
1921
1922 /* XXX: What if progname != "make"? */
1923 if (strncmp(p, "make", 4) == 0)
1924 if (start == cmd || !ch_isalnum(p[-1]))
1925 if (!ch_isalnum(p[4]))
1926 return true;
1927
1928 if (*p != '$')
1929 continue;
1930 p++;
1931
1932 if (*p == '{')
1933 endc = '}';
1934 else if (*p == '(')
1935 endc = ')';
1936 else
1937 continue;
1938 p++;
1939
1940 if (*p == '.') /* Accept either ${.MAKE} or ${MAKE}. */
1941 p++;
1942
1943 if (strncmp(p, "MAKE", 4) == 0)
1944 if (p[4] == endc)
1945 return true;
1946 }
1947 return false;
1948 }
1949
1950 /*
1951 * Append the command to the target node.
1952 *
1953 * The node may be marked as a submake node if the command is determined to
1954 * be that.
1955 */
1956 static void
1957 GNode_AddCommand(GNode *gn, char *cmd)
1958 {
1959 /* Add to last (ie current) cohort for :: targets */
1960 if ((gn->type & OP_DOUBLEDEP) && gn->cohorts.last != NULL)
1961 gn = gn->cohorts.last->datum;
1962
1963 /* if target already supplied, ignore commands */
1964 if (!(gn->type & OP_HAS_COMMANDS)) {
1965 Lst_Append(&gn->commands, cmd);
1966 if (MaybeSubMake(cmd))
1967 gn->type |= OP_SUBMAKE;
1968 RememberLocation(gn);
1969 } else {
1970 #if 0
1971 /* XXX: We cannot do this until we fix the tree */
1972 Lst_Append(&gn->commands, cmd);
1973 Parse_Error(PARSE_WARNING,
1974 "overriding commands for target \"%s\"; "
1975 "previous commands defined at %s: %d ignored",
1976 gn->name, gn->fname, gn->lineno);
1977 #else
1978 Parse_Error(PARSE_WARNING,
1979 "duplicate script for target \"%s\" ignored",
1980 gn->name);
1981 ParseErrorInternal(gn->fname, (size_t)gn->lineno, PARSE_WARNING,
1982 "using previous script for \"%s\" defined here",
1983 gn->name);
1984 #endif
1985 }
1986 }
1987
1988 /*
1989 * Add a directory to the path searched for included makefiles bracketed
1990 * by double-quotes.
1991 */
1992 void
1993 Parse_AddIncludeDir(const char *dir)
1994 {
1995 (void)SearchPath_Add(parseIncPath, dir);
1996 }
1997
1998 /*
1999 * Handle one of the .[-ds]include directives by remembering the current file
2000 * and pushing the included file on the stack. After the included file has
2001 * finished, parsing continues with the including file; see Parse_PushInput
2002 * and ParseEOF.
2003 *
2004 * System includes are looked up in sysIncPath, any other includes are looked
2005 * up in the parsedir and then in the directories specified by the -I command
2006 * line options.
2007 */
2008 static void
2009 IncludeFile(const char *file, bool isSystem, bool depinc, bool silent)
2010 {
2011 struct loadedfile *lf;
2012 char *fullname; /* full pathname of file */
2013 char *newName;
2014 char *slash, *incdir;
2015 int fd;
2016 int i;
2017
2018 fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
2019
2020 if (fullname == NULL && !isSystem) {
2021 /*
2022 * Include files contained in double-quotes are first searched
2023 * relative to the including file's location. We don't want to
2024 * cd there, of course, so we just tack on the old file's
2025 * leading path components and call Dir_FindFile to see if
2026 * we can locate the file.
2027 */
2028
2029 incdir = bmake_strdup(CurFile()->name.str);
2030 slash = strrchr(incdir, '/');
2031 if (slash != NULL) {
2032 *slash = '\0';
2033 /*
2034 * Now do lexical processing of leading "../" on the
2035 * filename.
2036 */
2037 for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
2038 slash = strrchr(incdir + 1, '/');
2039 if (slash == NULL || strcmp(slash, "/..") == 0)
2040 break;
2041 *slash = '\0';
2042 }
2043 newName = str_concat3(incdir, "/", file + i);
2044 fullname = Dir_FindFile(newName, parseIncPath);
2045 if (fullname == NULL)
2046 fullname = Dir_FindFile(newName,
2047 &dirSearchPath);
2048 free(newName);
2049 }
2050 free(incdir);
2051
2052 if (fullname == NULL) {
2053 /*
2054 * Makefile wasn't found in same directory as included
2055 * makefile.
2056 *
2057 * Search for it first on the -I search path, then on
2058 * the .PATH search path, if not found in a -I
2059 * directory. If we have a suffix-specific path, we
2060 * should use that.
2061 */
2062 const char *suff;
2063 SearchPath *suffPath = NULL;
2064
2065 if ((suff = strrchr(file, '.')) != NULL) {
2066 suffPath = Suff_GetPath(suff);
2067 if (suffPath != NULL)
2068 fullname = Dir_FindFile(file, suffPath);
2069 }
2070 if (fullname == NULL) {
2071 fullname = Dir_FindFile(file, parseIncPath);
2072 if (fullname == NULL)
2073 fullname = Dir_FindFile(file,
2074 &dirSearchPath);
2075 }
2076 }
2077 }
2078
2079 /* Looking for a system file or file still not found */
2080 if (fullname == NULL) {
2081 /*
2082 * Look for it on the system path
2083 */
2084 SearchPath *path = Lst_IsEmpty(&sysIncPath->dirs)
2085 ? defSysIncPath : sysIncPath;
2086 fullname = Dir_FindFile(file, path);
2087 }
2088
2089 if (fullname == NULL) {
2090 if (!silent)
2091 Parse_Error(PARSE_FATAL, "Could not find %s", file);
2092 return;
2093 }
2094
2095 /* Actually open the file... */
2096 fd = open(fullname, O_RDONLY);
2097 if (fd == -1) {
2098 if (!silent)
2099 Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
2100 free(fullname);
2101 return;
2102 }
2103
2104 /* load it */
2105 lf = loadfile(fullname, fd);
2106
2107 /* Start reading from this file next */
2108 Parse_PushInput(fullname, 0, -1, loadedfile_readMore, lf);
2109 CurFile()->lf = lf;
2110 if (depinc)
2111 doing_depend = depinc; /* only turn it on */
2112 free(fullname);
2113 }
2114
2115 /*
2116 * Parse a directive like '.include' or '.-include'.
2117 *
2118 * .include "user-makefile.mk"
2119 * .include <system-makefile.mk>
2120 */
2121 static void
2122 ParseInclude(char *directive)
2123 {
2124 char endc; /* '>' or '"' */
2125 char *p;
2126 bool silent = directive[0] != 'i';
2127 FStr file;
2128
2129 p = directive + (silent ? 8 : 7);
2130 pp_skip_hspace(&p);
2131
2132 if (*p != '"' && *p != '<') {
2133 Parse_Error(PARSE_FATAL,
2134 ".include filename must be delimited by '\"' or '<'");
2135 return;
2136 }
2137
2138 if (*p++ == '<')
2139 endc = '>';
2140 else
2141 endc = '"';
2142 file = FStr_InitRefer(p);
2143
2144 /* Skip to matching delimiter */
2145 while (*p != '\0' && *p != endc)
2146 p++;
2147
2148 if (*p != endc) {
2149 Parse_Error(PARSE_FATAL,
2150 "Unclosed .include filename. '%c' expected", endc);
2151 return;
2152 }
2153
2154 *p = '\0';
2155
2156 if (strchr(file.str, '$') != NULL) {
2157 char *xfile;
2158 Var_Subst(file.str, SCOPE_CMDLINE, VARE_WANTRES, &xfile);
2159 /* TODO: handle errors */
2160 file = FStr_InitOwn(xfile);
2161 }
2162
2163 IncludeFile(file.str, endc == '>', directive[0] == 'd', silent);
2164 FStr_Done(&file);
2165 }
2166
2167 /*
2168 * Split filename into dirname + basename, then assign these to the
2169 * given variables.
2170 */
2171 static void
2172 SetFilenameVars(const char *filename, const char *dirvar, const char *filevar)
2173 {
2174 const char *slash, *basename;
2175 FStr dirname;
2176
2177 slash = strrchr(filename, '/');
2178 if (slash == NULL) {
2179 dirname = FStr_InitRefer(curdir);
2180 basename = filename;
2181 } else {
2182 dirname = FStr_InitOwn(bmake_strsedup(filename, slash));
2183 basename = slash + 1;
2184 }
2185
2186 Global_Set(dirvar, dirname.str);
2187 Global_Set(filevar, basename);
2188
2189 DEBUG4(PARSE, "SetFilenameVars: ${%s} = `%s' ${%s} = `%s'\n",
2190 dirvar, dirname.str, filevar, basename);
2191 FStr_Done(&dirname);
2192 }
2193
2194 /*
2195 * Return the immediately including file.
2196 *
2197 * This is made complicated since the .for loop is implemented as a special
2198 * kind of .include; see For_Run.
2199 */
2200 static const char *
2201 GetActuallyIncludingFile(void)
2202 {
2203 size_t i;
2204 const IFile *incs = GetInclude(0);
2205
2206 for (i = includes.len; i >= 2; i--)
2207 if (!incs[i - 1].fromForLoop)
2208 return incs[i - 2].name.str;
2209 return NULL;
2210 }
2211
2212 /* Set .PARSEDIR, .PARSEFILE, .INCLUDEDFROMDIR and .INCLUDEDFROMFILE. */
2213 static void
2214 SetParseFile(const char *filename)
2215 {
2216 const char *including;
2217
2218 SetFilenameVars(filename, ".PARSEDIR", ".PARSEFILE");
2219
2220 including = GetActuallyIncludingFile();
2221 if (including != NULL) {
2222 SetFilenameVars(including,
2223 ".INCLUDEDFROMDIR", ".INCLUDEDFROMFILE");
2224 } else {
2225 Global_Delete(".INCLUDEDFROMDIR");
2226 Global_Delete(".INCLUDEDFROMFILE");
2227 }
2228 }
2229
2230 static bool
2231 StrContainsWord(const char *str, const char *word)
2232 {
2233 size_t strLen = strlen(str);
2234 size_t wordLen = strlen(word);
2235 const char *p;
2236
2237 if (strLen < wordLen)
2238 return false;
2239
2240 for (p = str; p != NULL; p = strchr(p, ' ')) {
2241 if (*p == ' ')
2242 p++;
2243 if (p > str + strLen - wordLen)
2244 return false;
2245
2246 if (memcmp(p, word, wordLen) == 0 &&
2247 (p[wordLen] == '\0' || p[wordLen] == ' '))
2248 return true;
2249 }
2250 return false;
2251 }
2252
2253 /*
2254 * XXX: Searching through a set of words with this linear search is
2255 * inefficient for variables that contain thousands of words.
2256 *
2257 * XXX: The paths in this list don't seem to be normalized in any way.
2258 */
2259 static bool
2260 VarContainsWord(const char *varname, const char *word)
2261 {
2262 FStr val = Var_Value(SCOPE_GLOBAL, varname);
2263 bool found = val.str != NULL && StrContainsWord(val.str, word);
2264 FStr_Done(&val);
2265 return found;
2266 }
2267
2268 /*
2269 * Track the makefiles we read - so makefiles can set dependencies on them.
2270 * Avoid adding anything more than once.
2271 *
2272 * Time complexity: O(n) per call, in total O(n^2), where n is the number
2273 * of makefiles that have been loaded.
2274 */
2275 static void
2276 TrackInput(const char *name)
2277 {
2278 if (!VarContainsWord(MAKE_MAKEFILES, name))
2279 Global_Append(MAKE_MAKEFILES, name);
2280 }
2281
2282
2283 /*
2284 * Start parsing from the given source.
2285 *
2286 * The given file is added to the includes stack.
2287 */
2288 void
2289 Parse_PushInput(const char *name, int lineno, int fd,
2290 ReadMoreProc readMore, void *readMoreArg)
2291 {
2292 IFile *curFile;
2293 char *buf;
2294 size_t len;
2295 bool fromForLoop = name == NULL;
2296
2297 if (fromForLoop)
2298 name = CurFile()->name.str;
2299 else
2300 TrackInput(name);
2301
2302 DEBUG3(PARSE, "Parse_PushInput: %s %s, line %d\n",
2303 readMore == loadedfile_readMore ? "file" : ".for loop in",
2304 name, lineno);
2305
2306 if (fd == -1 && readMore == NULL)
2307 /* sanity */
2308 return;
2309
2310 curFile = Vector_Push(&includes);
2311 curFile->name = FStr_InitOwn(bmake_strdup(name));
2312 curFile->fromForLoop = fromForLoop;
2313 curFile->lineno = lineno;
2314 curFile->first_lineno = lineno;
2315 curFile->readMore = readMore;
2316 curFile->readMoreArg = readMoreArg;
2317 curFile->lf = NULL;
2318 curFile->depending = doing_depend; /* restore this on EOF */
2319
2320 assert(readMore != NULL);
2321
2322 /* Get first block of input data */
2323 buf = curFile->readMore(curFile->readMoreArg, &len);
2324 if (buf == NULL) {
2325 /* Was all a waste of time ... */
2326 FStr_Done(&curFile->name);
2327 free(curFile);
2328 return;
2329 }
2330 curFile->buf_freeIt = buf;
2331 curFile->buf_ptr = buf;
2332 curFile->buf_end = buf + len;
2333
2334 curFile->cond_depth = Cond_save_depth();
2335 SetParseFile(name);
2336 }
2337
2338 /* Check if the directive is an include directive. */
2339 static bool
2340 IsInclude(const char *dir, bool sysv)
2341 {
2342 if (dir[0] == 's' || dir[0] == '-' || (dir[0] == 'd' && !sysv))
2343 dir++;
2344
2345 if (strncmp(dir, "include", 7) != 0)
2346 return false;
2347
2348 /* Space is not mandatory for BSD .include */
2349 return !sysv || ch_isspace(dir[7]);
2350 }
2351
2352
2353 #ifdef SYSVINCLUDE
2354 /* Check if the line is a SYSV include directive. */
2355 static bool
2356 IsSysVInclude(const char *line)
2357 {
2358 const char *p;
2359
2360 if (!IsInclude(line, true))
2361 return false;
2362
2363 /* Avoid interpreting a dependency line as an include */
2364 for (p = line; (p = strchr(p, ':')) != NULL;) {
2365
2366 /* end of line -> it's a dependency */
2367 if (*++p == '\0')
2368 return false;
2369
2370 /* '::' operator or ': ' -> it's a dependency */
2371 if (*p == ':' || ch_isspace(*p))
2372 return false;
2373 }
2374 return true;
2375 }
2376
2377 /* Push to another file. The line points to the word "include". */
2378 static void
2379 ParseTraditionalInclude(char *line)
2380 {
2381 char *cp; /* current position in file spec */
2382 bool done = false;
2383 bool silent = line[0] != 'i';
2384 char *file = line + (silent ? 8 : 7);
2385 char *all_files;
2386
2387 DEBUG1(PARSE, "ParseTraditionalInclude: %s\n", file);
2388
2389 pp_skip_whitespace(&file);
2390
2391 (void)Var_Subst(file, SCOPE_CMDLINE, VARE_WANTRES, &all_files);
2392 /* TODO: handle errors */
2393
2394 for (file = all_files; !done; file = cp + 1) {
2395 /* Skip to end of line or next whitespace */
2396 for (cp = file; *cp != '\0' && !ch_isspace(*cp); cp++)
2397 continue;
2398
2399 if (*cp != '\0')
2400 *cp = '\0';
2401 else
2402 done = true;
2403
2404 IncludeFile(file, false, false, silent);
2405 }
2406
2407 free(all_files);
2408 }
2409 #endif
2410
2411 #ifdef GMAKEEXPORT
2412 /* Parse "export <variable>=<value>", and actually export it. */
2413 static void
2414 ParseGmakeExport(char *line)
2415 {
2416 char *variable = line + 6;
2417 char *value;
2418
2419 DEBUG1(PARSE, "ParseGmakeExport: %s\n", variable);
2420
2421 pp_skip_whitespace(&variable);
2422
2423 for (value = variable; *value != '\0' && *value != '='; value++)
2424 continue;
2425
2426 if (*value != '=') {
2427 Parse_Error(PARSE_FATAL,
2428 "Variable/Value missing from \"export\"");
2429 return;
2430 }
2431 *value++ = '\0'; /* terminate variable */
2432
2433 /*
2434 * Expand the value before putting it in the environment.
2435 */
2436 (void)Var_Subst(value, SCOPE_CMDLINE, VARE_WANTRES, &value);
2437 /* TODO: handle errors */
2438
2439 setenv(variable, value, 1);
2440 free(value);
2441 }
2442 #endif
2443
2444 /*
2445 * Called when EOF is reached in the current file. If we were reading an
2446 * include file or a .for loop, the includes stack is popped and things set
2447 * up to go back to reading the previous file at the previous location.
2448 *
2449 * Results:
2450 * true to continue parsing, i.e. it had only reached the end of an
2451 * included file, false if the main file has been parsed completely.
2452 */
2453 static bool
2454 ParseEOF(void)
2455 {
2456 char *ptr;
2457 size_t len;
2458 IFile *curFile = CurFile();
2459
2460 assert(curFile->readMore != NULL);
2461
2462 doing_depend = curFile->depending; /* restore this */
2463 /* get next input buffer, if any */
2464 ptr = curFile->readMore(curFile->readMoreArg, &len);
2465 curFile->buf_ptr = ptr;
2466 curFile->buf_freeIt = ptr;
2467 curFile->buf_end = ptr == NULL ? NULL : ptr + len;
2468 curFile->lineno = curFile->first_lineno;
2469 if (ptr != NULL)
2470 return true; /* Iterate again */
2471
2472 /*
2473 * Ensure the makefile (or .for loop) didn't have mismatched
2474 * conditionals.
2475 */
2476 Cond_restore_depth(curFile->cond_depth);
2477
2478 if (curFile->lf != NULL) {
2479 loadedfile_destroy(curFile->lf);
2480 curFile->lf = NULL;
2481 }
2482
2483 FStr_Done(&curFile->name);
2484 free(curFile->buf_freeIt);
2485 Vector_Pop(&includes);
2486
2487 if (includes.len == 0) {
2488 /* We've run out of input */
2489 Global_Delete(".PARSEDIR");
2490 Global_Delete(".PARSEFILE");
2491 Global_Delete(".INCLUDEDFROMDIR");
2492 Global_Delete(".INCLUDEDFROMFILE");
2493 return false;
2494 }
2495
2496 curFile = CurFile();
2497 DEBUG2(PARSE, "ParseEOF: returning to file %s, line %d\n",
2498 curFile->name.str, curFile->lineno);
2499
2500 SetParseFile(curFile->name.str);
2501 return true;
2502 }
2503
2504 typedef enum ParseRawLineResult {
2505 PRLR_LINE,
2506 PRLR_EOF,
2507 PRLR_ERROR
2508 } ParseRawLineResult;
2509
2510 /*
2511 * Parse until the end of a line, taking into account lines that end with
2512 * backslash-newline. The resulting line goes from out_line to out_line_end;
2513 * the line is not null-terminated.
2514 */
2515 static ParseRawLineResult
2516 ParseRawLine(IFile *curFile, char **out_line, char **out_line_end,
2517 char **out_firstBackslash, char **out_firstComment)
2518 {
2519 char *line = curFile->buf_ptr;
2520 char *buf_end = curFile->buf_end;
2521 char *p = line;
2522 char *line_end = line;
2523 char *firstBackslash = NULL;
2524 char *firstComment = NULL;
2525 ParseRawLineResult res = PRLR_LINE;
2526
2527 curFile->lineno++;
2528
2529 for (;;) {
2530 char ch;
2531
2532 if (p == buf_end) {
2533 res = PRLR_EOF;
2534 break;
2535 }
2536
2537 ch = *p;
2538 if (ch == '\0' ||
2539 (ch == '\\' && p + 1 < buf_end && p[1] == '\0')) {
2540 Parse_Error(PARSE_FATAL, "Zero byte read from file");
2541 return PRLR_ERROR;
2542 }
2543
2544 /* Treat next character after '\' as literal. */
2545 if (ch == '\\') {
2546 if (firstBackslash == NULL)
2547 firstBackslash = p;
2548 if (p[1] == '\n') {
2549 curFile->lineno++;
2550 if (p + 2 == buf_end) {
2551 line_end = p;
2552 *line_end = '\n';
2553 p += 2;
2554 continue;
2555 }
2556 }
2557 p += 2;
2558 line_end = p;
2559 assert(p <= buf_end);
2560 continue;
2561 }
2562
2563 /*
2564 * Remember the first '#' for comment stripping, unless
2565 * the previous char was '[', as in the modifier ':[#]'.
2566 */
2567 if (ch == '#' && firstComment == NULL &&
2568 !(p > line && p[-1] == '['))
2569 firstComment = line_end;
2570
2571 p++;
2572 if (ch == '\n')
2573 break;
2574
2575 /* We are not interested in trailing whitespace. */
2576 if (!ch_isspace(ch))
2577 line_end = p;
2578 }
2579
2580 *out_line = line;
2581 curFile->buf_ptr = p;
2582 *out_line_end = line_end;
2583 *out_firstBackslash = firstBackslash;
2584 *out_firstComment = firstComment;
2585 return res;
2586 }
2587
2588 /*
2589 * Beginning at start, unescape '\#' to '#' and replace backslash-newline
2590 * with a single space.
2591 */
2592 static void
2593 UnescapeBackslash(char *line, char *start)
2594 {
2595 char *src = start;
2596 char *dst = start;
2597 char *spaceStart = line;
2598
2599 for (;;) {
2600 char ch = *src++;
2601 if (ch != '\\') {
2602 if (ch == '\0')
2603 break;
2604 *dst++ = ch;
2605 continue;
2606 }
2607
2608 ch = *src++;
2609 if (ch == '\0') {
2610 /* Delete '\\' at end of buffer */
2611 dst--;
2612 break;
2613 }
2614
2615 /* Delete '\\' from before '#' on non-command lines */
2616 if (ch == '#' && line[0] != '\t') {
2617 *dst++ = ch;
2618 continue;
2619 }
2620
2621 if (ch != '\n') {
2622 /* Leave '\\' in buffer for later */
2623 *dst++ = '\\';
2624 /*
2625 * Make sure we don't delete an escaped ' ' from the
2626 * line end.
2627 */
2628 spaceStart = dst + 1;
2629 *dst++ = ch;
2630 continue;
2631 }
2632
2633 /*
2634 * Escaped '\n' -- replace following whitespace with a single
2635 * ' '.
2636 */
2637 pp_skip_hspace(&src);
2638 *dst++ = ' ';
2639 }
2640
2641 /* Delete any trailing spaces - eg from empty continuations */
2642 while (dst > spaceStart && ch_isspace(dst[-1]))
2643 dst--;
2644 *dst = '\0';
2645 }
2646
2647 typedef enum LineKind {
2648 /*
2649 * Return the next line that is neither empty nor a comment.
2650 * Backslash line continuations are folded into a single space.
2651 * A trailing comment, if any, is discarded.
2652 */
2653 LK_NONEMPTY,
2654
2655 /*
2656 * Return the next line, even if it is empty or a comment.
2657 * Preserve backslash-newline to keep the line numbers correct.
2658 *
2659 * Used in .for loops to collect the body of the loop while waiting
2660 * for the corresponding .endfor.
2661 */
2662 LK_FOR_BODY,
2663
2664 /*
2665 * Return the next line that starts with a dot.
2666 * Backslash line continuations are folded into a single space.
2667 * A trailing comment, if any, is discarded.
2668 *
2669 * Used in .if directives to skip over irrelevant branches while
2670 * waiting for the corresponding .endif.
2671 */
2672 LK_DOT
2673 } LineKind;
2674
2675 /* Return the next "interesting" logical line from the current file. */
2676 static char *
2677 ReadLowLevelLine(LineKind kind)
2678 {
2679 IFile *curFile = CurFile();
2680 char *line;
2681 char *line_end;
2682 char *firstBackslash;
2683 char *firstComment;
2684
2685 for (;;) {
2686 ParseRawLineResult res = ParseRawLine(curFile,
2687 &line, &line_end, &firstBackslash, &firstComment);
2688 if (res == PRLR_ERROR)
2689 return NULL;
2690
2691 if (line_end == line || firstComment == line) {
2692 if (res == PRLR_EOF)
2693 return NULL;
2694 if (kind != LK_FOR_BODY)
2695 continue;
2696 }
2697
2698 /* We now have a line of data */
2699 assert(ch_isspace(*line_end));
2700 *line_end = '\0';
2701
2702 if (kind == LK_FOR_BODY)
2703 return line; /* Don't join the physical lines. */
2704
2705 if (kind == LK_DOT && line[0] != '.')
2706 continue;
2707 break;
2708 }
2709
2710 /* Ignore anything after a non-escaped '#' in non-commands. */
2711 if (firstComment != NULL && line[0] != '\t')
2712 *firstComment = '\0';
2713
2714 /* If we didn't see a '\\' then the in-situ data is fine. */
2715 if (firstBackslash == NULL)
2716 return line;
2717
2718 /* Remove escapes from '\n' and '#' */
2719 UnescapeBackslash(line, firstBackslash);
2720
2721 return line;
2722 }
2723
2724 static bool
2725 SkipIrrelevantBranches(void)
2726 {
2727 char *line;
2728
2729 while ((line = ReadLowLevelLine(LK_DOT)) != NULL) {
2730 if (Cond_EvalLine(line) == CR_TRUE)
2731 break;
2732 /*
2733 * TODO: Check for typos in .elif directives
2734 * such as .elsif or .elseif.
2735 *
2736 * This check will probably duplicate some of
2737 * the code in ParseLine. Most of the code
2738 * there cannot apply, only ParseVarassign and
2739 * ParseDependencyLine can, and to prevent code
2740 * duplication, these would need to be called
2741 * with a flag called onlyCheckSyntax.
2742 *
2743 * See directive-elif.mk for details.
2744 */
2745 }
2746
2747 return line != NULL;
2748 }
2749
2750 static bool
2751 ParseForLoop(const char *line)
2752 {
2753 int rval;
2754 int firstLineno;
2755
2756 rval = For_Eval(line);
2757 if (rval == 0)
2758 return false; /* Not a .for line */
2759 if (rval < 0)
2760 return true; /* Syntax error - error printed, ignore line */
2761
2762 firstLineno = CurFile()->lineno;
2763
2764 /* Accumulate loop lines until matching .endfor */
2765 do {
2766 line = ReadLowLevelLine(LK_FOR_BODY);
2767 if (line == NULL) {
2768 Parse_Error(PARSE_FATAL,
2769 "Unexpected end of file in .for loop");
2770 break;
2771 }
2772 } while (For_Accum(line));
2773
2774 For_Run(firstLineno); /* Stash each iteration as a new 'input file' */
2775
2776 return true; /* Read next line from for-loop buffer */
2777 }
2778
2779 /*
2780 * Read an entire line from the input file.
2781 *
2782 * Empty lines, .if and .for are completely handled by this function,
2783 * leaving only variable assignments, other directives, dependency lines
2784 * and shell commands to the caller.
2785 *
2786 * Results:
2787 * A line without its newline and without any trailing whitespace,
2788 * or NULL.
2789 */
2790 static char *
2791 ReadHighLevelLine(void)
2792 {
2793 char *line;
2794
2795 for (;;) {
2796 line = ReadLowLevelLine(LK_NONEMPTY);
2797 if (line == NULL)
2798 return NULL;
2799
2800 if (line[0] != '.')
2801 return line;
2802
2803 /*
2804 * The line might be a conditional. Ask the conditional module
2805 * about it and act accordingly
2806 */
2807 switch (Cond_EvalLine(line)) {
2808 case CR_FALSE: /* May also mean a syntax error. */
2809 if (!SkipIrrelevantBranches())
2810 return NULL;
2811 continue;
2812 case CR_TRUE:
2813 continue;
2814 case CR_ERROR: /* Not a conditional line */
2815 if (ParseForLoop(line))
2816 continue;
2817 break;
2818 }
2819 return line;
2820 }
2821 }
2822
2823 static void
2824 FinishDependencyGroup(void)
2825 {
2826 GNodeListNode *ln;
2827
2828 if (targets == NULL)
2829 return;
2830
2831 for (ln = targets->first; ln != NULL; ln = ln->next) {
2832 GNode *gn = ln->datum;
2833
2834 Suff_EndTransform(gn);
2835
2836 /*
2837 * Mark the target as already having commands if it does, to
2838 * keep from having shell commands on multiple dependency
2839 * lines.
2840 */
2841 if (!Lst_IsEmpty(&gn->commands))
2842 gn->type |= OP_HAS_COMMANDS;
2843 }
2844
2845 Lst_Free(targets);
2846 targets = NULL;
2847 }
2848
2849 /* Add the command to each target from the current dependency spec. */
2850 static void
2851 ParseLine_ShellCommand(const char *p)
2852 {
2853 cpp_skip_whitespace(&p);
2854 if (*p == '\0')
2855 return; /* skip empty commands */
2856
2857 if (targets == NULL) {
2858 Parse_Error(PARSE_FATAL,
2859 "Unassociated shell command \"%s\"", p);
2860 return;
2861 }
2862
2863 {
2864 char *cmd = bmake_strdup(p);
2865 GNodeListNode *ln;
2866
2867 for (ln = targets->first; ln != NULL; ln = ln->next) {
2868 GNode *gn = ln->datum;
2869 GNode_AddCommand(gn, cmd);
2870 }
2871 #ifdef CLEANUP
2872 Lst_Append(&targCmds, cmd);
2873 #endif
2874 }
2875 }
2876
2877 /*
2878 * See if the line starts with one of the known directives, and if so, handle
2879 * the directive.
2880 */
2881 static bool
2882 ParseDirective(char *line)
2883 {
2884 char *cp = line + 1;
2885 const char *arg;
2886 Substring dir;
2887
2888 pp_skip_whitespace(&cp);
2889 if (IsInclude(cp, false)) {
2890 ParseInclude(cp);
2891 return true;
2892 }
2893
2894 dir.start = cp;
2895 while (ch_isalpha(*cp) || *cp == '-')
2896 cp++;
2897 dir.end = cp;
2898
2899 if (*cp != '\0' && !ch_isspace(*cp))
2900 return false;
2901
2902 pp_skip_whitespace(&cp);
2903 arg = cp;
2904
2905 if (Substring_Equals(dir, "undef"))
2906 Var_Undef(arg);
2907 else if (Substring_Equals(dir, "export"))
2908 Var_Export(VEM_PLAIN, arg);
2909 else if (Substring_Equals(dir, "export-env"))
2910 Var_Export(VEM_ENV, arg);
2911 else if (Substring_Equals(dir, "export-literal"))
2912 Var_Export(VEM_LITERAL, arg);
2913 else if (Substring_Equals(dir, "unexport"))
2914 Var_UnExport(false, arg);
2915 else if (Substring_Equals(dir, "unexport-env"))
2916 Var_UnExport(true, arg);
2917 else if (Substring_Equals(dir, "info"))
2918 HandleMessage(PARSE_INFO, "info", arg);
2919 else if (Substring_Equals(dir, "warning"))
2920 HandleMessage(PARSE_WARNING, "warning", arg);
2921 else if (Substring_Equals(dir, "error"))
2922 HandleMessage(PARSE_FATAL, "error", arg);
2923 else
2924 return false;
2925 return true;
2926 }
2927
2928 static bool
2929 ParseVarassign(const char *line)
2930 {
2931 VarAssign var;
2932
2933 if (!Parse_IsVar(line, &var))
2934 return false;
2935
2936 FinishDependencyGroup();
2937 Parse_Var(&var, SCOPE_GLOBAL);
2938 return true;
2939 }
2940
2941 static char *
2942 FindSemicolon(char *p)
2943 {
2944 int level = 0;
2945
2946 for (; *p != '\0'; p++) {
2947 if (*p == '\\' && p[1] != '\0') {
2948 p++;
2949 continue;
2950 }
2951
2952 if (*p == '$' && (p[1] == '(' || p[1] == '{'))
2953 level++;
2954 else if (level > 0 && (*p == ')' || *p == '}'))
2955 level--;
2956 else if (level == 0 && *p == ';')
2957 break;
2958 }
2959 return p;
2960 }
2961
2962 /*
2963 * dependency -> target... op [source...] [';' command]
2964 * op -> ':' | '::' | '!'
2965 */
2966 static void
2967 ParseDependencyLine(char *line)
2968 {
2969 VarEvalMode emode;
2970 char *expanded_line;
2971 const char *shellcmd = NULL;
2972
2973 /*
2974 * For some reason - probably to make the parser impossible -
2975 * a ';' can be used to separate commands from dependencies.
2976 * Attempt to avoid ';' inside substitution patterns.
2977 */
2978 {
2979 char *semicolon = FindSemicolon(line);
2980 if (*semicolon != '\0') {
2981 /* Terminate the dependency list at the ';' */
2982 *semicolon = '\0';
2983 shellcmd = semicolon + 1;
2984 }
2985 }
2986
2987 /*
2988 * We now know it's a dependency line so it needs to have all
2989 * variables expanded before being parsed.
2990 *
2991 * XXX: Ideally the dependency line would first be split into
2992 * its left-hand side, dependency operator and right-hand side,
2993 * and then each side would be expanded on its own. This would
2994 * allow for the left-hand side to allow only defined variables
2995 * and to allow variables on the right-hand side to be undefined
2996 * as well.
2997 *
2998 * Parsing the line first would also prevent that targets
2999 * generated from variable expressions are interpreted as the
3000 * dependency operator, such as in "target${:U\:} middle: source",
3001 * in which the middle is interpreted as a source, not a target.
3002 */
3003
3004 /*
3005 * In lint mode, allow undefined variables to appear in dependency
3006 * lines.
3007 *
3008 * Ideally, only the right-hand side would allow undefined variables
3009 * since it is common to have optional dependencies. Having undefined
3010 * variables on the left-hand side is more unusual though. Since
3011 * both sides are expanded in a single pass, there is not much choice
3012 * what to do here.
3013 *
3014 * In normal mode, it does not matter whether undefined variables are
3015 * allowed or not since as of 2020-09-14, Var_Parse does not print
3016 * any parse errors in such a case. It simply returns the special
3017 * empty string var_Error, which cannot be detected in the result of
3018 * Var_Subst.
3019 */
3020 emode = opts.strict ? VARE_WANTRES : VARE_UNDEFERR;
3021 (void)Var_Subst(line, SCOPE_CMDLINE, emode, &expanded_line);
3022 /* TODO: handle errors */
3023
3024 /* Need a fresh list for the target nodes */
3025 if (targets != NULL)
3026 Lst_Free(targets);
3027 targets = Lst_New();
3028
3029 ParseDependency(expanded_line);
3030 free(expanded_line);
3031
3032 if (shellcmd != NULL)
3033 ParseLine_ShellCommand(shellcmd);
3034 }
3035
3036 static void
3037 ParseLine(char *line)
3038 {
3039 /*
3040 * Lines that begin with '.' can be pretty much anything:
3041 * - directives like '.include' or '.if',
3042 * - suffix rules like '.c.o:',
3043 * - dependencies for filenames that start with '.',
3044 * - variable assignments like '.tmp=value'.
3045 */
3046 if (line[0] == '.' && ParseDirective(line))
3047 return;
3048
3049 if (line[0] == '\t') {
3050 ParseLine_ShellCommand(line + 1);
3051 return;
3052 }
3053
3054 #ifdef SYSVINCLUDE
3055 if (IsSysVInclude(line)) {
3056 /*
3057 * It's an S3/S5-style "include".
3058 */
3059 ParseTraditionalInclude(line);
3060 return;
3061 }
3062 #endif
3063
3064 #ifdef GMAKEEXPORT
3065 if (strncmp(line, "export", 6) == 0 && ch_isspace(line[6]) &&
3066 strchr(line, ':') == NULL) {
3067 /*
3068 * It's a Gmake "export".
3069 */
3070 ParseGmakeExport(line);
3071 return;
3072 }
3073 #endif
3074
3075 if (ParseVarassign(line))
3076 return;
3077
3078 FinishDependencyGroup();
3079
3080 ParseDependencyLine(line);
3081 }
3082
3083 /*
3084 * Parse a top-level makefile, incorporating its content into the global
3085 * dependency graph.
3086 *
3087 * Input:
3088 * name The name of the file being read
3089 * fd The open file to parse; will be closed at the end
3090 */
3091 void
3092 Parse_File(const char *name, int fd)
3093 {
3094 char *line; /* the line we're working on */
3095 struct loadedfile *lf;
3096
3097 lf = loadfile(name, fd);
3098
3099 assert(targets == NULL);
3100
3101 if (name == NULL)
3102 name = "(stdin)";
3103
3104 Parse_PushInput(name, 0, -1, loadedfile_readMore, lf);
3105 CurFile()->lf = lf;
3106
3107 do {
3108 while ((line = ReadHighLevelLine()) != NULL) {
3109 DEBUG2(PARSE, "Parsing line %d: %s\n",
3110 CurFile()->lineno, line);
3111 ParseLine(line);
3112 }
3113 /* Reached EOF, but it may be just EOF of an include file. */
3114 } while (ParseEOF());
3115
3116 FinishDependencyGroup();
3117
3118 if (parseErrors != 0) {
3119 (void)fflush(stdout);
3120 (void)fprintf(stderr,
3121 "%s: Fatal errors encountered -- cannot continue",
3122 progname);
3123 PrintOnError(NULL, NULL);
3124 exit(1);
3125 }
3126 }
3127
3128 /* Initialize the parsing module. */
3129 void
3130 Parse_Init(void)
3131 {
3132 mainNode = NULL;
3133 parseIncPath = SearchPath_New();
3134 sysIncPath = SearchPath_New();
3135 defSysIncPath = SearchPath_New();
3136 Vector_Init(&includes, sizeof(IFile));
3137 }
3138
3139 /* Clean up the parsing module. */
3140 void
3141 Parse_End(void)
3142 {
3143 #ifdef CLEANUP
3144 Lst_DoneCall(&targCmds, free);
3145 assert(targets == NULL);
3146 SearchPath_Free(defSysIncPath);
3147 SearchPath_Free(sysIncPath);
3148 SearchPath_Free(parseIncPath);
3149 assert(includes.len == 0);
3150 Vector_Done(&includes);
3151 #endif
3152 }
3153
3154
3155 /*
3156 * Return a list containing the single main target to create.
3157 * If no such target exists, we Punt with an obnoxious error message.
3158 */
3159 void
3160 Parse_MainName(GNodeList *mainList)
3161 {
3162 if (mainNode == NULL)
3163 Punt("no target to make.");
3164
3165 Lst_Append(mainList, mainNode);
3166 if (mainNode->type & OP_DOUBLEDEP)
3167 Lst_AppendAll(mainList, &mainNode->cohorts);
3168
3169 Global_Append(".TARGETS", mainNode->name);
3170 }
3171
3172 int
3173 Parse_NumErrors(void)
3174 {
3175 return parseErrors;
3176 }
3177