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