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