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