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