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