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