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