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