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