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