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