parse.c revision 1.338 1 /* $NetBSD: parse.c,v 1.338 2020/09/27 21:35:16 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.338 2020/09/27 21:35:16 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 immediately. */
781 exit(1);
782 }
783 return TRUE;
784 }
785
786 struct ParseLinkSrcArgs {
787 GNode *cgn;
788
789 /* The special target of the current dependency line. */
790 /* Example: for ".END: action", it is 'End'. */
791 ParseSpecial specType;
792 };
793
794 /* Add the child to the parent's children.
795 *
796 * Add the parent to the child's parents, but only if the target is not
797 * special. An example for such a special target is .END, which does not
798 * need to be informed once the child target has been made. */
799 static void
800 ParseLinkSrc(void *pgnp, void *data)
801 {
802 const struct ParseLinkSrcArgs *args = data;
803 GNode *pgn = pgnp;
804 GNode *cgn = args->cgn;
805
806 if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty(pgn->cohorts))
807 pgn = LstNode_Datum(Lst_Last(pgn->cohorts));
808
809 Lst_Append(pgn->children, cgn);
810 pgn->unmade += 1;
811
812 if (args->specType == Not)
813 Lst_Append(cgn->parents, pgn);
814
815 if (DEBUG(PARSE)) {
816 fprintf(debug_file, "# %s: added child %s - %s\n",
817 __func__, pgn->name, cgn->name);
818 Targ_PrintNode(pgn, 0);
819 Targ_PrintNode(cgn, 0);
820 }
821 }
822
823 static Boolean
824 TryApplyDependencyOperator(GNode *gn, GNodeType op)
825 {
826 /*
827 * If the dependency mask of the operator and the node don't match and
828 * the node has actually had an operator applied to it before, and
829 * the operator actually has some dependency information in it, complain.
830 */
831 if (((op & OP_OPMASK) != (gn->type & OP_OPMASK)) &&
832 !OP_NOP(gn->type) && !OP_NOP(op))
833 {
834 Parse_Error(PARSE_FATAL, "Inconsistent operator for %s", gn->name);
835 return FALSE;
836 }
837
838 if (op == OP_DOUBLEDEP && (gn->type & OP_OPMASK) == OP_DOUBLEDEP) {
839 /*
840 * If the node was the object of a :: operator, we need to create a
841 * new instance of it for the children and commands on this dependency
842 * line. The new instance is placed on the 'cohorts' list of the
843 * initial one (note the initial one is not on its own cohorts list)
844 * and the new instance is linked to all parents of the initial
845 * instance.
846 */
847 GNode *cohort;
848
849 /*
850 * Propagate copied bits to the initial node. They'll be propagated
851 * back to the rest of the cohorts later.
852 */
853 gn->type |= op & ~OP_OPMASK;
854
855 cohort = Targ_NewInternalNode(gn->name);
856 if (doing_depend)
857 ParseMark(cohort);
858 /*
859 * Make the cohort invisible as well to avoid duplicating it into
860 * other variables. True, parents of this target won't tend to do
861 * anything with their local variables, but better safe than
862 * sorry. (I think this is pointless now, since the relevant list
863 * traversals will no longer see this node anyway. -mycroft)
864 */
865 cohort->type = op | OP_INVISIBLE;
866 Lst_Append(gn->cohorts, cohort);
867 cohort->centurion = gn;
868 gn->unmade_cohorts += 1;
869 snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
870 gn->unmade_cohorts);
871 } else {
872 /*
873 * We don't want to nuke any previous flags (whatever they were) so we
874 * just OR the new operator into the old
875 */
876 gn->type |= op;
877 }
878
879 return TRUE;
880 }
881
882 static void
883 ApplyDependencyOperator(GNodeType op)
884 {
885 GNodeListNode *ln;
886 for (ln = targets->first; ln != NULL; ln = ln->next)
887 if (!TryApplyDependencyOperator(ln->datum, op))
888 break;
889 }
890
891 /*-
892 *---------------------------------------------------------------------
893 * ParseDoSrc --
894 * Given the name of a source, figure out if it is an attribute
895 * and apply it to the targets if it is. Else decide if there is
896 * some attribute which should be applied *to* the source because
897 * of some special target and apply it if so. Otherwise, make the
898 * source be a child of the targets in the list 'targets'
899 *
900 * Input:
901 * tOp operator (if any) from special targets
902 * src name of the source to handle
903 *
904 * Results:
905 * None
906 *
907 * Side Effects:
908 * Operator bits may be added to the list of targets or to the source.
909 * The targets may have a new source added to their lists of children.
910 *---------------------------------------------------------------------
911 */
912 static void
913 ParseDoSrc(int tOp, const char *src, ParseSpecial specType)
914 {
915 GNode *gn = NULL;
916 static int wait_number = 0;
917 char wait_src[16];
918
919 if (*src == '.' && ch_isupper(src[1])) {
920 int keywd = ParseFindKeyword(src);
921 if (keywd != -1) {
922 int op = parseKeywords[keywd].op;
923 if (op != 0) {
924 ApplyDependencyOperator(op);
925 return;
926 }
927 if (parseKeywords[keywd].spec == Wait) {
928 /*
929 * We add a .WAIT node in the dependency list.
930 * After any dynamic dependencies (and filename globbing)
931 * have happened, it is given a dependency on the each
932 * previous child back to and previous .WAIT node.
933 * The next child won't be scheduled until the .WAIT node
934 * is built.
935 * We give each .WAIT node a unique name (mainly for diag).
936 */
937 snprintf(wait_src, sizeof wait_src, ".WAIT_%u", ++wait_number);
938 gn = Targ_NewInternalNode(wait_src);
939 if (doing_depend)
940 ParseMark(gn);
941 gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
942 {
943 struct ParseLinkSrcArgs args = { gn, specType };
944 Lst_ForEach(targets, ParseLinkSrc, &args);
945 }
946 return;
947 }
948 }
949 }
950
951 switch (specType) {
952 case Main:
953 /*
954 * If we have noted the existence of a .MAIN, it means we need
955 * to add the sources of said target to the list of things
956 * to create. The string 'src' is likely to be free, so we
957 * must make a new copy of it. Note that this will only be
958 * invoked if the user didn't specify a target on the command
959 * line. This is to allow #ifmake's to succeed, or something...
960 */
961 Lst_Append(create, bmake_strdup(src));
962 /*
963 * Add the name to the .TARGETS variable as well, so the user can
964 * employ that, if desired.
965 */
966 Var_Append(".TARGETS", src, VAR_GLOBAL);
967 return;
968
969 case Order:
970 /*
971 * Create proper predecessor/successor links between the previous
972 * source and the current one.
973 */
974 gn = Targ_GetNode(src);
975 if (doing_depend)
976 ParseMark(gn);
977 if (predecessor != NULL) {
978 Lst_Append(predecessor->order_succ, gn);
979 Lst_Append(gn->order_pred, predecessor);
980 if (DEBUG(PARSE)) {
981 fprintf(debug_file, "# %s: added Order dependency %s - %s\n",
982 __func__, predecessor->name, gn->name);
983 Targ_PrintNode(predecessor, 0);
984 Targ_PrintNode(gn, 0);
985 }
986 }
987 /*
988 * The current source now becomes the predecessor for the next one.
989 */
990 predecessor = gn;
991 break;
992
993 default:
994 /*
995 * If the source is not an attribute, we need to find/create
996 * a node for it. After that we can apply any operator to it
997 * from a special target or link it to its parents, as
998 * appropriate.
999 *
1000 * In the case of a source that was the object of a :: operator,
1001 * the attribute is applied to all of its instances (as kept in
1002 * the 'cohorts' list of the node) or all the cohorts are linked
1003 * to all the targets.
1004 */
1005
1006 /* Find/create the 'src' node and attach to all targets */
1007 gn = Targ_GetNode(src);
1008 if (doing_depend)
1009 ParseMark(gn);
1010 if (tOp) {
1011 gn->type |= tOp;
1012 } else {
1013 {
1014 struct ParseLinkSrcArgs args = { gn, specType };
1015 Lst_ForEach(targets, ParseLinkSrc, &args);
1016 }
1017 }
1018 break;
1019 }
1020 }
1021
1022 /* If we have yet to decide on a main target to make, in the absence of any
1023 * user input, we want the first target on the first dependency line that is
1024 * actually a real target (i.e. isn't a .USE or .EXEC rule) to be made. */
1025 static void
1026 FindMainTarget(void)
1027 {
1028 GNodeListNode *ln;
1029
1030 if (mainNode != NULL)
1031 return;
1032
1033 for (ln = targets->first; ln != NULL; ln = ln->next) {
1034 GNode *gn = ln->datum;
1035 if (!(gn->type & OP_NOTARGET)) {
1036 mainNode = gn;
1037 Targ_SetMain(gn);
1038 return;
1039 }
1040 }
1041 }
1042
1043 static void
1044 ParseAddDir(void *path, void *name)
1045 {
1046 (void)Dir_AddDir(path, name);
1047 }
1048
1049 static void
1050 ParseClearPath(void *path, void *unused MAKE_ATTR_UNUSED)
1051 {
1052 Dir_ClearPath(path);
1053 }
1054
1055 /*
1056 * We got to the end of the line while we were still looking at targets.
1057 *
1058 * Ending a dependency line without an operator is a Bozo no-no. As a
1059 * heuristic, this is also often triggered by undetected conflicts from
1060 * cvs/rcs merges.
1061 */
1062 static void
1063 ParseErrorNoDependency(const char *lstart, const char *line)
1064 {
1065 if ((strncmp(line, "<<<<<<", 6) == 0) ||
1066 (strncmp(line, "======", 6) == 0) ||
1067 (strncmp(line, ">>>>>>", 6) == 0))
1068 Parse_Error(PARSE_FATAL,
1069 "Makefile appears to contain unresolved cvs/rcs/??? merge conflicts");
1070 else if (lstart[0] == '.') {
1071 const char *dirstart = lstart + 1;
1072 const char *dirend;
1073 while (ch_isspace(*dirstart))
1074 dirstart++;
1075 dirend = dirstart;
1076 while (ch_isalnum(*dirend) || *dirend == '-')
1077 dirend++;
1078 Parse_Error(PARSE_FATAL, "Unknown directive \"%.*s\"",
1079 (int)(dirend - dirstart), dirstart);
1080 } else
1081 Parse_Error(PARSE_FATAL, "Need an operator");
1082 }
1083
1084 static void
1085 ParseDependencyTargetWord(/*const*/ char **pp, const char *lstart)
1086 {
1087 /*const*/ char *cp = *pp;
1088
1089 while (*cp != '\0') {
1090 if ((ch_isspace(*cp) || *cp == '!' || *cp == ':' || *cp == '(') &&
1091 !ParseIsEscaped(lstart, cp))
1092 break;
1093
1094 if (*cp == '$') {
1095 /*
1096 * Must be a dynamic source (would have been expanded
1097 * otherwise), so call the Var module to parse the puppy
1098 * so we can safely advance beyond it...There should be
1099 * no errors in this, as they would have been discovered
1100 * in the initial Var_Subst and we wouldn't be here.
1101 */
1102 const char *nested_p = cp;
1103 const char *nested_val;
1104 void *freeIt;
1105
1106 (void)Var_Parse(&nested_p, VAR_CMD, VARE_UNDEFERR|VARE_WANTRES,
1107 &nested_val, &freeIt);
1108 /* TODO: handle errors */
1109 free(freeIt);
1110 cp += nested_p - cp;
1111 } else
1112 cp++;
1113 }
1114
1115 *pp = cp;
1116 }
1117
1118 /* Parse a dependency line consisting of targets, followed by a dependency
1119 * operator, optionally followed by sources.
1120 *
1121 * The nodes of the sources are linked as children to the nodes of the
1122 * targets. Nodes are created as necessary.
1123 *
1124 * The operator is applied to each node in the global 'targets' list,
1125 * which is where the nodes found for the targets are kept, by means of
1126 * the ParseDoOp function.
1127 *
1128 * The sources are parsed in much the same way as the targets, except
1129 * that they are expanded using the wildcarding scheme of the C-Shell,
1130 * and all instances of the resulting words in the list of all targets
1131 * are found. Each of the resulting nodes is then linked to each of the
1132 * targets as one of its children.
1133 *
1134 * Certain targets and sources such as .PHONY or .PRECIOUS are handled
1135 * specially. These are the ones detailed by the specType variable.
1136 *
1137 * The storing of transformation rules such as '.c.o' is also taken care of
1138 * here. A target is recognized as a transformation rule by calling
1139 * Suff_IsTransform. If it is a transformation rule, its node is gotten
1140 * from the suffix module via Suff_AddTransform rather than the standard
1141 * Targ_FindNode in the target module.
1142 */
1143 static void
1144 ParseDoDependency(char *line)
1145 {
1146 typedef List SearchPathList;
1147
1148 char *cp; /* our current position */
1149 GNodeType op; /* the operator on the line */
1150 char savec; /* a place to save a character */
1151 SearchPathList *paths; /* search paths to alter when parsing
1152 * a list of .PATH targets */
1153 int tOp; /* operator from special target */
1154 GNodeList *sources; /* archive sources after expansion */
1155 StringList *curTargs; /* target names to be found and added
1156 * to the targets list */
1157 char *lstart = line;
1158
1159 /*
1160 * specType contains the SPECial TYPE of the current target. It is Not
1161 * if the target is unspecial. If it *is* special, however, the children
1162 * are linked as children of the parent but not vice versa.
1163 */
1164 ParseSpecial specType = Not;
1165
1166 if (DEBUG(PARSE))
1167 fprintf(debug_file, "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 if (DEBUG(PARSE))
2224 fprintf(debug_file, "%s: ${%s} = `%s' ${%s} = `%s'\n",
2225 __func__, dirvar, dirname, filevar, basename);
2226 free(freeIt);
2227 }
2228
2229 /* Return the immediately including file.
2230 *
2231 * This is made complicated since the .for loop is implemented as a special
2232 * kind of .include; see For_Run. */
2233 static const char *
2234 GetActuallyIncludingFile(void)
2235 {
2236 size_t i;
2237
2238 /* XXX: Stack was supposed to be an opaque data structure. */
2239 for (i = includes.len; i > 0; i--) {
2240 IFile *parent = includes.items[i - 1];
2241 IFile *child = i < includes.len ? includes.items[i] : curFile;
2242 if (!child->fromForLoop)
2243 return parent->fname;
2244 }
2245 return NULL;
2246 }
2247
2248 /* Set .PARSEDIR, .PARSEFILE, .INCLUDEDFROMDIR and .INCLUDEDFROMFILE. */
2249 static void
2250 ParseSetParseFile(const char *filename)
2251 {
2252 const char *including;
2253
2254 SetFilenameVars(filename, ".PARSEDIR", ".PARSEFILE");
2255
2256 including = GetActuallyIncludingFile();
2257 if (including != NULL) {
2258 SetFilenameVars(including,
2259 ".INCLUDEDFROMDIR", ".INCLUDEDFROMFILE");
2260 } else {
2261 Var_Delete(".INCLUDEDFROMDIR", VAR_GLOBAL);
2262 Var_Delete(".INCLUDEDFROMFILE", VAR_GLOBAL);
2263 }
2264 }
2265
2266 /* Track the makefiles we read - so makefiles can set dependencies on them.
2267 * Avoid adding anything more than once. */
2268 static void
2269 ParseTrackInput(const char *name)
2270 {
2271 char *fp = NULL;
2272
2273 const char *old = Var_Value(MAKE_MAKEFILES, VAR_GLOBAL, &fp);
2274 if (old) {
2275 size_t name_len = strlen(name);
2276 const char *ep = old + strlen(old) - name_len;
2277 /* does it contain name? */
2278 for (; old != NULL; old = strchr(old, ' ')) {
2279 if (*old == ' ')
2280 old++;
2281 if (old >= ep)
2282 break; /* cannot contain name */
2283 if (memcmp(old, name, name_len) == 0
2284 && (old[name_len] == 0 || old[name_len] == ' '))
2285 goto cleanup;
2286 }
2287 }
2288 Var_Append (MAKE_MAKEFILES, name, VAR_GLOBAL);
2289 cleanup:
2290 bmake_free(fp);
2291 }
2292
2293
2294 /* Start Parsing from the given source.
2295 *
2296 * The given file is added to the includes stack. */
2297 void
2298 Parse_SetInput(const char *name, int line, int fd,
2299 char *(*nextbuf)(void *, size_t *), void *arg)
2300 {
2301 char *buf;
2302 size_t len;
2303 Boolean fromForLoop = name == NULL;
2304
2305 if (fromForLoop)
2306 name = curFile->fname;
2307 else
2308 ParseTrackInput(name);
2309
2310 if (DEBUG(PARSE))
2311 fprintf(debug_file, "%s: file %s, line %d, fd %d, nextbuf %s, arg %p\n",
2312 __func__, name, line, fd,
2313 nextbuf == loadedfile_nextbuf ? "loadedfile" : "other", arg);
2314
2315 if (fd == -1 && nextbuf == NULL)
2316 /* sanity */
2317 return;
2318
2319 if (curFile != NULL)
2320 /* Save existing file info */
2321 Stack_Push(&includes, curFile);
2322
2323 /* Allocate and fill in new structure */
2324 curFile = bmake_malloc(sizeof *curFile);
2325
2326 /*
2327 * Once the previous state has been saved, we can get down to reading
2328 * the new file. We set up the name of the file to be the absolute
2329 * name of the include file so error messages refer to the right
2330 * place.
2331 */
2332 curFile->fname = bmake_strdup(name);
2333 curFile->fromForLoop = fromForLoop;
2334 curFile->lineno = line;
2335 curFile->first_lineno = line;
2336 curFile->nextbuf = nextbuf;
2337 curFile->nextbuf_arg = arg;
2338 curFile->lf = NULL;
2339 curFile->depending = doing_depend; /* restore this on EOF */
2340
2341 assert(nextbuf != NULL);
2342
2343 /* Get first block of input data */
2344 buf = curFile->nextbuf(curFile->nextbuf_arg, &len);
2345 if (buf == NULL) {
2346 /* Was all a waste of time ... */
2347 if (curFile->fname)
2348 free(curFile->fname);
2349 free(curFile);
2350 return;
2351 }
2352 curFile->P_str = buf;
2353 curFile->P_ptr = buf;
2354 curFile->P_end = buf+len;
2355
2356 curFile->cond_depth = Cond_save_depth();
2357 ParseSetParseFile(name);
2358 }
2359
2360 /* Check if the line is an include directive. */
2361 static Boolean
2362 IsInclude(const char *dir, Boolean sysv)
2363 {
2364 if (dir[0] == 's' || dir[0] == '-' || (dir[0] == 'd' && !sysv))
2365 dir++;
2366
2367 if (strncmp(dir, "include", 7) != 0)
2368 return FALSE;
2369
2370 /* Space is not mandatory for BSD .include */
2371 return !sysv || ch_isspace(dir[7]);
2372 }
2373
2374
2375 #ifdef SYSVINCLUDE
2376 /* Check if the line is a SYSV include directive. */
2377 static Boolean
2378 IsSysVInclude(const char *line)
2379 {
2380 const char *p;
2381
2382 if (!IsInclude(line, TRUE))
2383 return FALSE;
2384
2385 /* Avoid interpeting a dependency line as an include */
2386 for (p = line; (p = strchr(p, ':')) != NULL;) {
2387 if (*++p == '\0') {
2388 /* end of line -> dependency */
2389 return FALSE;
2390 }
2391 if (*p == ':' || ch_isspace(*p)) {
2392 /* :: operator or ': ' -> dependency */
2393 return FALSE;
2394 }
2395 }
2396 return TRUE;
2397 }
2398
2399 /* Push to another file. The line points to the word "include". */
2400 static void
2401 ParseTraditionalInclude(char *line)
2402 {
2403 char *cp; /* current position in file spec */
2404 int done = 0;
2405 int silent = line[0] != 'i';
2406 char *file = &line[silent + 7];
2407 char *all_files;
2408
2409 if (DEBUG(PARSE))
2410 fprintf(debug_file, "%s: %s\n", __func__, file);
2411
2412 /*
2413 * Skip over whitespace
2414 */
2415 while (ch_isspace(*file))
2416 file++;
2417
2418 /*
2419 * Substitute for any variables in the file name before trying to
2420 * find the thing.
2421 */
2422 (void)Var_Subst(file, VAR_CMD, VARE_WANTRES, &all_files);
2423 /* TODO: handle errors */
2424
2425 if (*file == '\0') {
2426 Parse_Error(PARSE_FATAL,
2427 "Filename missing from \"include\"");
2428 goto out;
2429 }
2430
2431 for (file = all_files; !done; file = cp + 1) {
2432 /* Skip to end of line or next whitespace */
2433 for (cp = file; *cp && !ch_isspace(*cp); cp++)
2434 continue;
2435
2436 if (*cp)
2437 *cp = '\0';
2438 else
2439 done = 1;
2440
2441 Parse_include_file(file, FALSE, FALSE, silent);
2442 }
2443 out:
2444 free(all_files);
2445 }
2446 #endif
2447
2448 #ifdef GMAKEEXPORT
2449 /* Parse export <variable>=<value>, and actually export it. */
2450 static void
2451 ParseGmakeExport(char *line)
2452 {
2453 char *variable = &line[6];
2454 char *value;
2455
2456 if (DEBUG(PARSE))
2457 fprintf(debug_file, "%s: %s\n", __func__, variable);
2458
2459 /*
2460 * Skip over whitespace
2461 */
2462 while (ch_isspace(*variable))
2463 variable++;
2464
2465 for (value = variable; *value && *value != '='; value++)
2466 continue;
2467
2468 if (*value != '=') {
2469 Parse_Error(PARSE_FATAL,
2470 "Variable/Value missing from \"export\"");
2471 return;
2472 }
2473 *value++ = '\0'; /* terminate variable */
2474
2475 /*
2476 * Expand the value before putting it in the environment.
2477 */
2478 (void)Var_Subst(value, VAR_CMD, VARE_WANTRES, &value);
2479 /* TODO: handle errors */
2480
2481 setenv(variable, value, 1);
2482 free(value);
2483 }
2484 #endif
2485
2486 /* Called when EOF is reached in the current file. If we were reading an
2487 * include file, the includes stack is popped and things set up to go back
2488 * to reading the previous file at the previous location.
2489 *
2490 * Results:
2491 * CONTINUE if there's more to do. DONE if not.
2492 */
2493 static int
2494 ParseEOF(void)
2495 {
2496 char *ptr;
2497 size_t len;
2498
2499 assert(curFile->nextbuf != NULL);
2500
2501 doing_depend = curFile->depending; /* restore this */
2502 /* get next input buffer, if any */
2503 ptr = curFile->nextbuf(curFile->nextbuf_arg, &len);
2504 curFile->P_ptr = ptr;
2505 curFile->P_str = ptr;
2506 curFile->P_end = ptr + len;
2507 curFile->lineno = curFile->first_lineno;
2508 if (ptr != NULL) {
2509 /* Iterate again */
2510 return CONTINUE;
2511 }
2512
2513 /* Ensure the makefile (or loop) didn't have mismatched conditionals */
2514 Cond_restore_depth(curFile->cond_depth);
2515
2516 if (curFile->lf != NULL) {
2517 loadedfile_destroy(curFile->lf);
2518 curFile->lf = NULL;
2519 }
2520
2521 /* Dispose of curFile info */
2522 /* Leak curFile->fname because all the gnodes have pointers to it */
2523 free(curFile->P_str);
2524 free(curFile);
2525
2526 if (Stack_IsEmpty(&includes)) {
2527 curFile = NULL;
2528 /* We've run out of input */
2529 Var_Delete(".PARSEDIR", VAR_GLOBAL);
2530 Var_Delete(".PARSEFILE", VAR_GLOBAL);
2531 Var_Delete(".INCLUDEDFROMDIR", VAR_GLOBAL);
2532 Var_Delete(".INCLUDEDFROMFILE", VAR_GLOBAL);
2533 return DONE;
2534 }
2535
2536 curFile = Stack_Pop(&includes);
2537 if (DEBUG(PARSE))
2538 fprintf(debug_file, "ParseEOF: returning to file %s, line %d\n",
2539 curFile->fname, curFile->lineno);
2540
2541 ParseSetParseFile(curFile->fname);
2542 return CONTINUE;
2543 }
2544
2545 #define PARSE_RAW 1
2546 #define PARSE_SKIP 2
2547
2548 static char *
2549 ParseGetLine(int flags, int *length)
2550 {
2551 IFile *cf = curFile;
2552 char *ptr;
2553 char ch;
2554 char *line;
2555 char *line_end;
2556 char *escaped;
2557 char *comment;
2558 char *tp;
2559
2560 /* Loop through blank lines and comment lines */
2561 for (;;) {
2562 cf->lineno++;
2563 line = cf->P_ptr;
2564 ptr = line;
2565 line_end = line;
2566 escaped = NULL;
2567 comment = NULL;
2568 for (;;) {
2569 if (cf->P_end != NULL && ptr == cf->P_end) {
2570 /* end of buffer */
2571 ch = 0;
2572 break;
2573 }
2574 ch = *ptr;
2575 if (ch == 0 || (ch == '\\' && ptr[1] == 0)) {
2576 if (cf->P_end == NULL)
2577 /* End of string (aka for loop) data */
2578 break;
2579 /* see if there is more we can parse */
2580 while (ptr++ < cf->P_end) {
2581 if ((ch = *ptr) == '\n') {
2582 if (ptr > line && ptr[-1] == '\\')
2583 continue;
2584 Parse_Error(PARSE_WARNING,
2585 "Zero byte read from file, skipping rest of line.");
2586 break;
2587 }
2588 }
2589 if (cf->nextbuf != NULL) {
2590 /*
2591 * End of this buffer; return EOF and outer logic
2592 * will get the next one. (eww)
2593 */
2594 break;
2595 }
2596 Parse_Error(PARSE_FATAL, "Zero byte read from file");
2597 return NULL;
2598 }
2599
2600 if (ch == '\\') {
2601 /* Don't treat next character as special, remember first one */
2602 if (escaped == NULL)
2603 escaped = ptr;
2604 if (ptr[1] == '\n')
2605 cf->lineno++;
2606 ptr += 2;
2607 line_end = ptr;
2608 continue;
2609 }
2610 if (ch == '#' && comment == NULL) {
2611 /* Remember first '#' for comment stripping */
2612 /* Unless previous char was '[', as in modifier :[#] */
2613 if (!(ptr > line && ptr[-1] == '['))
2614 comment = line_end;
2615 }
2616 ptr++;
2617 if (ch == '\n')
2618 break;
2619 if (!ch_isspace(ch))
2620 /* We are not interested in trailing whitespace */
2621 line_end = ptr;
2622 }
2623
2624 /* Save next 'to be processed' location */
2625 cf->P_ptr = ptr;
2626
2627 /* Check we have a non-comment, non-blank line */
2628 if (line_end == line || comment == line) {
2629 if (ch == 0)
2630 /* At end of file */
2631 return NULL;
2632 /* Parse another line */
2633 continue;
2634 }
2635
2636 /* We now have a line of data */
2637 *line_end = 0;
2638
2639 if (flags & PARSE_RAW) {
2640 /* Leave '\' (etc) in line buffer (eg 'for' lines) */
2641 *length = line_end - line;
2642 return line;
2643 }
2644
2645 if (flags & PARSE_SKIP) {
2646 /* Completely ignore non-directives */
2647 if (line[0] != '.')
2648 continue;
2649 /* We could do more of the .else/.elif/.endif checks here */
2650 }
2651 break;
2652 }
2653
2654 /* Brutally ignore anything after a non-escaped '#' in non-commands */
2655 if (comment != NULL && line[0] != '\t') {
2656 line_end = comment;
2657 *line_end = 0;
2658 }
2659
2660 /* If we didn't see a '\\' then the in-situ data is fine */
2661 if (escaped == NULL) {
2662 *length = line_end - line;
2663 return line;
2664 }
2665
2666 /* Remove escapes from '\n' and '#' */
2667 tp = ptr = escaped;
2668 escaped = line;
2669 for (; ; *tp++ = ch) {
2670 ch = *ptr++;
2671 if (ch != '\\') {
2672 if (ch == 0)
2673 break;
2674 continue;
2675 }
2676
2677 ch = *ptr++;
2678 if (ch == 0) {
2679 /* Delete '\\' at end of buffer */
2680 tp--;
2681 break;
2682 }
2683
2684 if (ch == '#' && line[0] != '\t')
2685 /* Delete '\\' from before '#' on non-command lines */
2686 continue;
2687
2688 if (ch != '\n') {
2689 /* Leave '\\' in buffer for later */
2690 *tp++ = '\\';
2691 /* Make sure we don't delete an escaped ' ' from the line end */
2692 escaped = tp + 1;
2693 continue;
2694 }
2695
2696 /* Escaped '\n' replace following whitespace with a single ' ' */
2697 while (ptr[0] == ' ' || ptr[0] == '\t')
2698 ptr++;
2699 ch = ' ';
2700 }
2701
2702 /* Delete any trailing spaces - eg from empty continuations */
2703 while (tp > escaped && ch_isspace(tp[-1]))
2704 tp--;
2705
2706 *tp = 0;
2707 *length = tp - line;
2708 return line;
2709 }
2710
2711 /* Read an entire line from the input file. Called only by Parse_File.
2712 *
2713 * Results:
2714 * A line without its newline.
2715 *
2716 * Side Effects:
2717 * Only those associated with reading a character
2718 */
2719 static char *
2720 ParseReadLine(void)
2721 {
2722 char *line; /* Result */
2723 int lineLength; /* Length of result */
2724 int lineno; /* Saved line # */
2725 int rval;
2726
2727 for (;;) {
2728 line = ParseGetLine(0, &lineLength);
2729 if (line == NULL)
2730 return NULL;
2731
2732 if (line[0] != '.')
2733 return line;
2734
2735 /*
2736 * The line might be a conditional. Ask the conditional module
2737 * about it and act accordingly
2738 */
2739 switch (Cond_EvalLine(line)) {
2740 case COND_SKIP:
2741 /* Skip to next conditional that evaluates to COND_PARSE. */
2742 do {
2743 line = ParseGetLine(PARSE_SKIP, &lineLength);
2744 } while (line && Cond_EvalLine(line) != COND_PARSE);
2745 if (line == NULL)
2746 break;
2747 continue;
2748 case COND_PARSE:
2749 continue;
2750 case COND_INVALID: /* Not a conditional line */
2751 /* Check for .for loops */
2752 rval = For_Eval(line);
2753 if (rval == 0)
2754 /* Not a .for line */
2755 break;
2756 if (rval < 0)
2757 /* Syntax error - error printed, ignore line */
2758 continue;
2759 /* Start of a .for loop */
2760 lineno = curFile->lineno;
2761 /* Accumulate loop lines until matching .endfor */
2762 do {
2763 line = ParseGetLine(PARSE_RAW, &lineLength);
2764 if (line == NULL) {
2765 Parse_Error(PARSE_FATAL,
2766 "Unexpected end of file in for loop.");
2767 break;
2768 }
2769 } while (For_Accum(line));
2770 /* Stash each iteration as a new 'input file' */
2771 For_Run(lineno);
2772 /* Read next line from for-loop buffer */
2773 continue;
2774 }
2775 return line;
2776 }
2777 }
2778
2779 static void
2780 SuffEndTransform(void *target, void *unused MAKE_ATTR_UNUSED)
2781 {
2782 Suff_EndTransform(target);
2783 }
2784
2785 static void
2786 FinishDependencyGroup(void)
2787 {
2788 if (targets != NULL) {
2789 Lst_ForEach(targets, SuffEndTransform, NULL);
2790 Lst_Destroy(targets, ParseHasCommands);
2791 targets = NULL;
2792 }
2793 }
2794
2795 /* Add the command to each target from the current dependency spec. */
2796 static void
2797 ParseLine_ShellCommand(char *cp)
2798 {
2799 for (; ch_isspace(*cp); cp++)
2800 continue;
2801
2802 if (*cp == '\0')
2803 return; /* skip empty commands */
2804
2805 if (targets == NULL) {
2806 Parse_Error(PARSE_FATAL, "Unassociated shell command \"%s\"", cp);
2807 return;
2808 }
2809
2810 {
2811 char *cmd = bmake_strdup(cp);
2812 GNodeListNode *ln;
2813
2814 for (ln = targets->first; ln != NULL; ln = ln->next) {
2815 GNode *gn = ln->datum;
2816 ParseAddCmd(gn, cmd);
2817 }
2818 #ifdef CLEANUP
2819 Lst_Append(targCmds, cmd);
2820 #endif
2821 }
2822 }
2823
2824 /* Parse a top-level makefile into its component parts, incorporating them
2825 * into the global dependency graph.
2826 *
2827 * Input:
2828 * name The name of the file being read
2829 * fd The open file to parse; will be closed at the end
2830 */
2831 void
2832 Parse_File(const char *name, int fd)
2833 {
2834 char *cp; /* pointer into the line */
2835 char *line; /* the line we're working on */
2836 struct loadedfile *lf;
2837
2838 lf = loadfile(name, fd);
2839
2840 assert(targets == NULL);
2841 fatals = 0;
2842
2843 if (name == NULL)
2844 name = "(stdin)";
2845
2846 Parse_SetInput(name, 0, -1, loadedfile_nextbuf, lf);
2847 curFile->lf = lf;
2848
2849 do {
2850 for (; (line = ParseReadLine()) != NULL; ) {
2851 if (DEBUG(PARSE))
2852 fprintf(debug_file, "ParseReadLine (%d): '%s'\n",
2853 curFile->lineno, line);
2854 if (*line == '.') {
2855 /*
2856 * Lines that begin with the special character may be
2857 * include or undef directives.
2858 * On the other hand they can be suffix rules (.c.o: ...)
2859 * or just dependencies for filenames that start '.'.
2860 */
2861 for (cp = line + 1; ch_isspace(*cp); cp++)
2862 continue;
2863 if (IsInclude(cp, FALSE)) {
2864 ParseDoInclude(cp);
2865 continue;
2866 }
2867 if (strncmp(cp, "undef", 5) == 0) {
2868 const char *varname;
2869 for (cp += 5; ch_isspace(*cp); cp++)
2870 continue;
2871 varname = cp;
2872 for (; !ch_isspace(*cp) && *cp != '\0'; cp++)
2873 continue;
2874 *cp = '\0';
2875 Var_Delete(varname, VAR_GLOBAL);
2876 /* TODO: undefine all variables, not only the first */
2877 /* TODO: use Str_Words, like everywhere else */
2878 continue;
2879 } else if (strncmp(cp, "export", 6) == 0) {
2880 for (cp += 6; ch_isspace(*cp); cp++)
2881 continue;
2882 Var_Export(cp, TRUE);
2883 continue;
2884 } else if (strncmp(cp, "unexport", 8) == 0) {
2885 Var_UnExport(cp);
2886 continue;
2887 } else if (strncmp(cp, "info", 4) == 0 ||
2888 strncmp(cp, "error", 5) == 0 ||
2889 strncmp(cp, "warning", 7) == 0) {
2890 if (ParseMessage(cp))
2891 continue;
2892 }
2893 }
2894
2895 if (*line == '\t') {
2896 /*
2897 * If a line starts with a tab, it can only hope to be
2898 * a creation command.
2899 */
2900 cp = line + 1;
2901 shellCommand:
2902 ParseLine_ShellCommand(cp);
2903 continue;
2904 }
2905
2906 #ifdef SYSVINCLUDE
2907 if (IsSysVInclude(line)) {
2908 /*
2909 * It's an S3/S5-style "include".
2910 */
2911 ParseTraditionalInclude(line);
2912 continue;
2913 }
2914 #endif
2915 #ifdef GMAKEEXPORT
2916 if (strncmp(line, "export", 6) == 0 && ch_isspace(line[6]) &&
2917 strchr(line, ':') == NULL) {
2918 /*
2919 * It's a Gmake "export".
2920 */
2921 ParseGmakeExport(line);
2922 continue;
2923 }
2924 #endif
2925 if (Parse_IsVar(line)) {
2926 FinishDependencyGroup();
2927 Parse_DoVar(line, VAR_GLOBAL);
2928 continue;
2929 }
2930
2931 #ifndef POSIX
2932 /*
2933 * To make life easier on novices, if the line is indented we
2934 * first make sure the line has a dependency operator in it.
2935 * If it doesn't have an operator and we're in a dependency
2936 * line's script, we assume it's actually a shell command
2937 * and add it to the current list of targets.
2938 */
2939 cp = line;
2940 if (ch_isspace(line[0])) {
2941 while (ch_isspace(*cp))
2942 cp++;
2943 while (*cp && (ParseIsEscaped(line, cp) ||
2944 *cp != ':' && *cp != '!')) {
2945 cp++;
2946 }
2947 if (*cp == '\0') {
2948 if (targets == NULL) {
2949 Parse_Error(PARSE_WARNING,
2950 "Shell command needs a leading tab");
2951 goto shellCommand;
2952 }
2953 }
2954 }
2955 #endif
2956 FinishDependencyGroup();
2957
2958 /*
2959 * For some reason - probably to make the parser impossible -
2960 * a ';' can be used to separate commands from dependencies.
2961 * Attempt to avoid ';' inside substitution patterns.
2962 */
2963 {
2964 int level = 0;
2965
2966 for (cp = line; *cp != 0; cp++) {
2967 if (*cp == '\\' && cp[1] != 0) {
2968 cp++;
2969 continue;
2970 }
2971 if (*cp == '$' &&
2972 (cp[1] == '(' || cp[1] == '{')) {
2973 level++;
2974 continue;
2975 }
2976 if (level > 0) {
2977 if (*cp == ')' || *cp == '}') {
2978 level--;
2979 continue;
2980 }
2981 } else if (*cp == ';') {
2982 break;
2983 }
2984 }
2985 }
2986 if (*cp != 0)
2987 /* Terminate the dependency list at the ';' */
2988 *cp++ = 0;
2989 else
2990 cp = NULL;
2991
2992 /*
2993 * We now know it's a dependency line so it needs to have all
2994 * variables expanded before being parsed.
2995 *
2996 * XXX: Ideally the dependency line would first be split into
2997 * its left-hand side, dependency operator and right-hand side,
2998 * and then each side would be expanded on its own. This would
2999 * allow for the left-hand side to allow only defined variables
3000 * and to allow variables on the right-hand side to be undefined
3001 * as well.
3002 *
3003 * Parsing the line first would also prevent that targets
3004 * generated from variable expressions are interpreted as the
3005 * dependency operator, such as in "target${:U:} middle: source",
3006 * in which the middle is interpreted as a source, not a target.
3007 */
3008 {
3009 /* In lint mode, allow undefined variables to appear in
3010 * dependency lines.
3011 *
3012 * Ideally, only the right-hand side would allow undefined
3013 * variables since it is common to have no dependencies.
3014 * Having undefined variables on the left-hand side is more
3015 * unusual though. Since both sides are expanded in a single
3016 * pass, there is not much choice what to do here.
3017 *
3018 * In normal mode, it does not matter whether undefined
3019 * variables are allowed or not since as of 2020-09-14,
3020 * Var_Parse does not print any parse errors in such a case.
3021 * It simply returns the special empty string var_Error,
3022 * which cannot be detected in the result of Var_Subst. */
3023 VarEvalFlags eflags = DEBUG(LINT)
3024 ? VARE_WANTRES
3025 : VARE_UNDEFERR|VARE_WANTRES;
3026 (void)Var_Subst(line, VAR_CMD, eflags, &line);
3027 /* TODO: handle errors */
3028 }
3029
3030 /* Need a fresh list for the target nodes */
3031 if (targets != NULL)
3032 Lst_Free(targets);
3033 targets = Lst_Init();
3034
3035 ParseDoDependency(line);
3036 free(line);
3037
3038 /* If there were commands after a ';', add them now */
3039 if (cp != NULL) {
3040 goto shellCommand;
3041 }
3042 }
3043 /*
3044 * Reached EOF, but it may be just EOF of an include file...
3045 */
3046 } while (ParseEOF() == CONTINUE);
3047
3048 FinishDependencyGroup();
3049
3050 if (fatals) {
3051 (void)fflush(stdout);
3052 (void)fprintf(stderr,
3053 "%s: Fatal errors encountered -- cannot continue",
3054 progname);
3055 PrintOnError(NULL, NULL);
3056 exit(1);
3057 }
3058 }
3059
3060 /*-
3061 *---------------------------------------------------------------------
3062 * Parse_Init --
3063 * initialize the parsing module
3064 *
3065 * Results:
3066 * none
3067 *
3068 * Side Effects:
3069 * the parseIncPath list is initialized...
3070 *---------------------------------------------------------------------
3071 */
3072 void
3073 Parse_Init(void)
3074 {
3075 mainNode = NULL;
3076 parseIncPath = Lst_Init();
3077 sysIncPath = Lst_Init();
3078 defIncPath = Lst_Init();
3079 Stack_Init(&includes);
3080 #ifdef CLEANUP
3081 targCmds = Lst_Init();
3082 #endif
3083 }
3084
3085 void
3086 Parse_End(void)
3087 {
3088 #ifdef CLEANUP
3089 Lst_Destroy(targCmds, free);
3090 assert(targets == NULL);
3091 Lst_Destroy(defIncPath, Dir_Destroy);
3092 Lst_Destroy(sysIncPath, Dir_Destroy);
3093 Lst_Destroy(parseIncPath, Dir_Destroy);
3094 assert(Stack_IsEmpty(&includes));
3095 Stack_Done(&includes);
3096 #endif
3097 }
3098
3099
3100 /*-
3101 *-----------------------------------------------------------------------
3102 * Parse_MainName --
3103 * Return a Lst of the main target to create for main()'s sake. If
3104 * no such target exists, we Punt with an obnoxious error message.
3105 *
3106 * Results:
3107 * A Lst of the single node to create.
3108 *
3109 * Side Effects:
3110 * None.
3111 *
3112 *-----------------------------------------------------------------------
3113 */
3114 GNodeList *
3115 Parse_MainName(void)
3116 {
3117 GNodeList *mainList;
3118
3119 mainList = Lst_Init();
3120
3121 if (mainNode == NULL) {
3122 Punt("no target to make.");
3123 /*NOTREACHED*/
3124 } else if (mainNode->type & OP_DOUBLEDEP) {
3125 Lst_Append(mainList, mainNode);
3126 Lst_AppendAll(mainList, mainNode->cohorts);
3127 }
3128 else
3129 Lst_Append(mainList, mainNode);
3130 Var_Append(".TARGETS", mainNode->name, VAR_GLOBAL);
3131 return mainList;
3132 }
3133