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