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