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