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