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