kernel/u4b: Some additional work for the recent cdce(4) addition.
[dragonfly.git] / contrib / bmake / parse.c
blob6d2cfb40a6e11e51e764312e6e4efd382a8dfd66
1 /* $NetBSD: parse.c,v 1.214 2016/04/06 09:57:00 gson Exp $ */
3 /*
4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
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.
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.
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
39 * This code is derived from software contributed to Berkeley by
40 * Adam de Boor.
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.
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.
71 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: parse.c,v 1.214 2016/04/06 09:57:00 gson 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.214 2016/04/06 09:57:00 gson Exp $");
80 #endif
81 #endif /* not lint */
82 #endif
84 /*-
85 * parse.c --
86 * Functions to parse a makefile.
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.
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.
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.
102 * Interface:
103 * Parse_Init Initialization function which must be
104 * called before anything else in this module
105 * is used.
107 * Parse_End Cleanup the module
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.
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...
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.
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>
134 #include "make.h"
135 #include "hash.h"
136 #include "dir.h"
137 #include "job.h"
138 #include "buf.h"
139 #include "pathnames.h"
141 #ifdef HAVE_MMAP
142 #include <sys/mman.h>
144 #ifndef MAP_COPY
145 #define MAP_COPY MAP_PRIVATE
146 #endif
147 #ifndef MAP_FILE
148 #define MAP_FILE 0
149 #endif
150 #endif
152 ////////////////////////////////////////////////////////////
153 // types and constants
156 * Structure for a file being read ("included file")
158 typedef struct IFile {
159 char *fname; /* name of file */
160 int lineno; /* current line number in file */
161 int first_lineno; /* line number of start of text */
162 int cond_depth; /* 'if' nesting when file opened */
163 Boolean depending; /* state of doing_depend on EOF */
164 char *P_str; /* point to base of string buffer */
165 char *P_ptr; /* point to next char of string buffer */
166 char *P_end; /* point to the end of string buffer */
167 char *(*nextbuf)(void *, size_t *); /* Function to get more data */
168 void *nextbuf_arg; /* Opaque arg for nextbuf() */
169 struct loadedfile *lf; /* loadedfile object, if any */
170 } IFile;
174 * These values are returned by ParseEOF to tell Parse_File whether to
175 * CONTINUE parsing, i.e. it had only reached the end of an include file,
176 * or if it's DONE.
178 #define CONTINUE 1
179 #define DONE 0
182 * Tokens for target attributes
184 typedef enum {
185 Begin, /* .BEGIN */
186 Default, /* .DEFAULT */
187 End, /* .END */
188 dotError, /* .ERROR */
189 Ignore, /* .IGNORE */
190 Includes, /* .INCLUDES */
191 Interrupt, /* .INTERRUPT */
192 Libs, /* .LIBS */
193 Meta, /* .META */
194 MFlags, /* .MFLAGS or .MAKEFLAGS */
195 Main, /* .MAIN and we don't have anything user-specified to
196 * make */
197 NoExport, /* .NOEXPORT */
198 NoMeta, /* .NOMETA */
199 NoMetaCmp, /* .NOMETA_CMP */
200 NoPath, /* .NOPATH */
201 Not, /* Not special */
202 NotParallel, /* .NOTPARALLEL */
203 Null, /* .NULL */
204 ExObjdir, /* .OBJDIR */
205 Order, /* .ORDER */
206 Parallel, /* .PARALLEL */
207 ExPath, /* .PATH */
208 Phony, /* .PHONY */
209 #ifdef POSIX
210 Posix, /* .POSIX */
211 #endif
212 Precious, /* .PRECIOUS */
213 ExShell, /* .SHELL */
214 Silent, /* .SILENT */
215 SingleShell, /* .SINGLESHELL */
216 Stale, /* .STALE */
217 Suffixes, /* .SUFFIXES */
218 Wait, /* .WAIT */
219 Attribute /* Generic attribute */
220 } ParseSpecial;
223 * Other tokens
225 #define LPAREN '('
226 #define RPAREN ')'
229 ////////////////////////////////////////////////////////////
230 // result data
233 * The main target to create. This is the first target on the first
234 * dependency line in the first makefile.
236 static GNode *mainNode;
238 ////////////////////////////////////////////////////////////
239 // eval state
241 /* targets we're working on */
242 static Lst targets;
244 #ifdef CLEANUP
245 /* command lines for targets */
246 static Lst targCmds;
247 #endif
250 * specType contains the SPECial TYPE of the current target. It is
251 * Not if the target is unspecial. If it *is* special, however, the children
252 * are linked as children of the parent but not vice versa. This variable is
253 * set in ParseDoDependency
255 static ParseSpecial specType;
258 * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
259 * seen, then set to each successive source on the line.
261 static GNode *predecessor;
263 ////////////////////////////////////////////////////////////
264 // parser state
266 /* true if currently in a dependency line or its commands */
267 static Boolean inLine;
269 /* number of fatal errors */
270 static int fatals = 0;
273 * Variables for doing includes
276 /* current file being read */
277 static IFile *curFile;
279 /* stack of IFiles generated by .includes */
280 static Lst includes;
282 /* include paths (lists of directories) */
283 Lst parseIncPath; /* dirs for "..." includes */
284 Lst sysIncPath; /* dirs for <...> includes */
285 Lst defIncPath; /* default for sysIncPath */
287 ////////////////////////////////////////////////////////////
288 // parser tables
291 * The parseKeywords table is searched using binary search when deciding
292 * if a target or source is special. The 'spec' field is the ParseSpecial
293 * type of the keyword ("Not" if the keyword isn't special as a target) while
294 * the 'op' field is the operator to apply to the list of targets if the
295 * keyword is used as a source ("0" if the keyword isn't special as a source)
297 static const struct {
298 const char *name; /* Name of keyword */
299 ParseSpecial spec; /* Type when used as a target */
300 int op; /* Operator when used as a source */
301 } parseKeywords[] = {
302 { ".BEGIN", Begin, 0 },
303 { ".DEFAULT", Default, 0 },
304 { ".END", End, 0 },
305 { ".ERROR", dotError, 0 },
306 { ".EXEC", Attribute, OP_EXEC },
307 { ".IGNORE", Ignore, OP_IGNORE },
308 { ".INCLUDES", Includes, 0 },
309 { ".INTERRUPT", Interrupt, 0 },
310 { ".INVISIBLE", Attribute, OP_INVISIBLE },
311 { ".JOIN", Attribute, OP_JOIN },
312 { ".LIBS", Libs, 0 },
313 { ".MADE", Attribute, OP_MADE },
314 { ".MAIN", Main, 0 },
315 { ".MAKE", Attribute, OP_MAKE },
316 { ".MAKEFLAGS", MFlags, 0 },
317 { ".META", Meta, OP_META },
318 { ".MFLAGS", MFlags, 0 },
319 { ".NOMETA", NoMeta, OP_NOMETA },
320 { ".NOMETA_CMP", NoMetaCmp, OP_NOMETA_CMP },
321 { ".NOPATH", NoPath, OP_NOPATH },
322 { ".NOTMAIN", Attribute, OP_NOTMAIN },
323 { ".NOTPARALLEL", NotParallel, 0 },
324 { ".NO_PARALLEL", NotParallel, 0 },
325 { ".NULL", Null, 0 },
326 { ".OBJDIR", ExObjdir, 0 },
327 { ".OPTIONAL", Attribute, OP_OPTIONAL },
328 { ".ORDER", Order, 0 },
329 { ".PARALLEL", Parallel, 0 },
330 { ".PATH", ExPath, 0 },
331 { ".PHONY", Phony, OP_PHONY },
332 #ifdef POSIX
333 { ".POSIX", Posix, 0 },
334 #endif
335 { ".PRECIOUS", Precious, OP_PRECIOUS },
336 { ".RECURSIVE", Attribute, OP_MAKE },
337 { ".SHELL", ExShell, 0 },
338 { ".SILENT", Silent, OP_SILENT },
339 { ".SINGLESHELL", SingleShell, 0 },
340 { ".STALE", Stale, 0 },
341 { ".SUFFIXES", Suffixes, 0 },
342 { ".USE", Attribute, OP_USE },
343 { ".USEBEFORE", Attribute, OP_USEBEFORE },
344 { ".WAIT", Wait, 0 },
347 ////////////////////////////////////////////////////////////
348 // local functions
350 static int ParseIsEscaped(const char *, const char *);
351 static void ParseErrorInternal(const char *, size_t, int, const char *, ...)
352 MAKE_ATTR_PRINTFLIKE(4,5);
353 static void ParseVErrorInternal(FILE *, const char *, size_t, int, const char *, va_list)
354 MAKE_ATTR_PRINTFLIKE(5, 0);
355 static int ParseFindKeyword(const char *);
356 static int ParseLinkSrc(void *, void *);
357 static int ParseDoOp(void *, void *);
358 static void ParseDoSrc(int, const char *);
359 static int ParseFindMain(void *, void *);
360 static int ParseAddDir(void *, void *);
361 static int ParseClearPath(void *, void *);
362 static void ParseDoDependency(char *);
363 static int ParseAddCmd(void *, void *);
364 static void ParseHasCommands(void *);
365 static void ParseDoInclude(char *);
366 static void ParseSetParseFile(const char *);
367 static void ParseSetIncludedFile(void);
368 #ifdef SYSVINCLUDE
369 static void ParseTraditionalInclude(char *);
370 #endif
371 #ifdef GMAKEEXPORT
372 static void ParseGmakeExport(char *);
373 #endif
374 static int ParseEOF(void);
375 static char *ParseReadLine(void);
376 static void ParseFinishLine(void);
377 static void ParseMark(GNode *);
379 ////////////////////////////////////////////////////////////
380 // file loader
382 struct loadedfile {
383 const char *path; /* name, for error reports */
384 char *buf; /* contents buffer */
385 size_t len; /* length of contents */
386 size_t maplen; /* length of mmap area, or 0 */
387 Boolean used; /* XXX: have we used the data yet */
391 * Constructor/destructor for loadedfile
393 static struct loadedfile *
394 loadedfile_create(const char *path)
396 struct loadedfile *lf;
398 lf = bmake_malloc(sizeof(*lf));
399 lf->path = (path == NULL ? "(stdin)" : path);
400 lf->buf = NULL;
401 lf->len = 0;
402 lf->maplen = 0;
403 lf->used = FALSE;
404 return lf;
407 static void
408 loadedfile_destroy(struct loadedfile *lf)
410 if (lf->buf != NULL) {
411 if (lf->maplen > 0) {
412 #ifdef HAVE_MMAP
413 munmap(lf->buf, lf->maplen);
414 #endif
415 } else {
416 free(lf->buf);
419 free(lf);
423 * nextbuf() operation for loadedfile, as needed by the weird and twisted
424 * logic below. Once that's cleaned up, we can get rid of lf->used...
426 static char *
427 loadedfile_nextbuf(void *x, size_t *len)
429 struct loadedfile *lf = x;
431 if (lf->used) {
432 return NULL;
434 lf->used = TRUE;
435 *len = lf->len;
436 return lf->buf;
440 * Try to get the size of a file.
442 static ReturnStatus
443 load_getsize(int fd, size_t *ret)
445 struct stat st;
447 if (fstat(fd, &st) < 0) {
448 return FAILURE;
451 if (!S_ISREG(st.st_mode)) {
452 return FAILURE;
456 * st_size is an off_t, which is 64 bits signed; *ret is
457 * size_t, which might be 32 bits unsigned or 64 bits
458 * unsigned. Rather than being elaborate, just punt on
459 * files that are more than 2^31 bytes. We should never
460 * see a makefile that size in practice...
462 * While we're at it reject negative sizes too, just in case.
464 if (st.st_size < 0 || st.st_size > 0x7fffffff) {
465 return FAILURE;
468 *ret = (size_t) st.st_size;
469 return SUCCESS;
473 * Read in a file.
475 * Until the path search logic can be moved under here instead of
476 * being in the caller in another source file, we need to have the fd
477 * passed in already open. Bleh.
479 * If the path is NULL use stdin and (to insure against fd leaks)
480 * assert that the caller passed in -1.
482 static struct loadedfile *
483 loadfile(const char *path, int fd)
485 struct loadedfile *lf;
486 #ifdef HAVE_MMAP
487 long pagesize;
488 #endif
489 ssize_t result;
490 size_t bufpos;
492 lf = loadedfile_create(path);
494 if (path == NULL) {
495 assert(fd == -1);
496 fd = STDIN_FILENO;
497 } else {
498 #if 0 /* notyet */
499 fd = open(path, O_RDONLY);
500 if (fd < 0) {
502 Error("%s: %s", path, strerror(errno));
503 exit(1);
505 #endif
508 #ifdef HAVE_MMAP
509 if (load_getsize(fd, &lf->len) == SUCCESS) {
510 /* found a size, try mmap */
511 #ifdef _SC_PAGESIZE
512 pagesize = sysconf(_SC_PAGESIZE);
513 #else
514 pagesize = 0;
515 #endif
516 if (pagesize <= 0) {
517 pagesize = 0x1000;
519 /* round size up to a page */
520 lf->maplen = pagesize * ((lf->len + pagesize - 1)/pagesize);
523 * XXX hack for dealing with empty files; remove when
524 * we're no longer limited by interfacing to the old
525 * logic elsewhere in this file.
527 if (lf->maplen == 0) {
528 lf->maplen = pagesize;
532 * FUTURE: remove PROT_WRITE when the parser no longer
533 * needs to scribble on the input.
535 lf->buf = mmap(NULL, lf->maplen, PROT_READ|PROT_WRITE,
536 MAP_FILE|MAP_COPY, fd, 0);
537 if (lf->buf != MAP_FAILED) {
538 /* succeeded */
539 if (lf->len == lf->maplen && lf->buf[lf->len - 1] != '\n') {
540 char *b = malloc(lf->len + 1);
541 b[lf->len] = '\n';
542 memcpy(b, lf->buf, lf->len++);
543 munmap(lf->buf, lf->maplen);
544 lf->maplen = 0;
545 lf->buf = b;
547 goto done;
550 #endif
551 /* cannot mmap; load the traditional way */
553 lf->maplen = 0;
554 lf->len = 1024;
555 lf->buf = bmake_malloc(lf->len);
557 bufpos = 0;
558 while (1) {
559 assert(bufpos <= lf->len);
560 if (bufpos == lf->len) {
561 lf->len *= 2;
562 lf->buf = bmake_realloc(lf->buf, lf->len);
564 result = read(fd, lf->buf + bufpos, lf->len - bufpos);
565 if (result < 0) {
566 Error("%s: read error: %s", path, strerror(errno));
567 exit(1);
569 if (result == 0) {
570 break;
572 bufpos += result;
574 assert(bufpos <= lf->len);
575 lf->len = bufpos;
577 /* truncate malloc region to actual length (maybe not useful) */
578 if (lf->len > 0) {
579 lf->buf = bmake_realloc(lf->buf, lf->len);
582 #ifdef HAVE_MMAP
583 done:
584 #endif
585 if (path != NULL) {
586 close(fd);
588 return lf;
591 ////////////////////////////////////////////////////////////
592 // old code
595 *----------------------------------------------------------------------
596 * ParseIsEscaped --
597 * Check if the current character is escaped on the current line
599 * Results:
600 * 0 if the character is not backslash escaped, 1 otherwise
602 * Side Effects:
603 * None
604 *----------------------------------------------------------------------
606 static int
607 ParseIsEscaped(const char *line, const char *c)
609 int active = 0;
610 for (;;) {
611 if (line == c)
612 return active;
613 if (*--c != '\\')
614 return active;
615 active = !active;
620 *----------------------------------------------------------------------
621 * ParseFindKeyword --
622 * Look in the table of keywords for one matching the given string.
624 * Input:
625 * str String to find
627 * Results:
628 * The index of the keyword, or -1 if it isn't there.
630 * Side Effects:
631 * None
632 *----------------------------------------------------------------------
634 static int
635 ParseFindKeyword(const char *str)
637 int start, end, cur;
638 int diff;
640 start = 0;
641 end = (sizeof(parseKeywords)/sizeof(parseKeywords[0])) - 1;
643 do {
644 cur = start + ((end - start) / 2);
645 diff = strcmp(str, parseKeywords[cur].name);
647 if (diff == 0) {
648 return (cur);
649 } else if (diff < 0) {
650 end = cur - 1;
651 } else {
652 start = cur + 1;
654 } while (start <= end);
655 return (-1);
659 * ParseVErrorInternal --
660 * Error message abort function for parsing. Prints out the context
661 * of the error (line number and file) as well as the message with
662 * two optional arguments.
664 * Results:
665 * None
667 * Side Effects:
668 * "fatals" is incremented if the level is PARSE_FATAL.
670 /* VARARGS */
671 static void
672 ParseVErrorInternal(FILE *f, const char *cfname, size_t clineno, int type,
673 const char *fmt, va_list ap)
675 static Boolean fatal_warning_error_printed = FALSE;
677 (void)fprintf(f, "%s: ", progname);
679 if (cfname != NULL) {
680 (void)fprintf(f, "\"");
681 if (*cfname != '/' && strcmp(cfname, "(stdin)") != 0) {
682 char *cp;
683 const char *dir;
686 * Nothing is more annoying than not knowing
687 * which Makefile is the culprit.
689 dir = Var_Value(".PARSEDIR", VAR_GLOBAL, &cp);
690 if (dir == NULL || *dir == '\0' ||
691 (*dir == '.' && dir[1] == '\0'))
692 dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
693 if (dir == NULL)
694 dir = ".";
696 (void)fprintf(f, "%s/%s", dir, cfname);
697 } else
698 (void)fprintf(f, "%s", cfname);
700 (void)fprintf(f, "\" line %d: ", (int)clineno);
702 if (type == PARSE_WARNING)
703 (void)fprintf(f, "warning: ");
704 (void)vfprintf(f, fmt, ap);
705 (void)fprintf(f, "\n");
706 (void)fflush(f);
707 if (type == PARSE_FATAL || parseWarnFatal)
708 fatals += 1;
709 if (parseWarnFatal && !fatal_warning_error_printed) {
710 Error("parsing warnings being treated as errors");
711 fatal_warning_error_printed = TRUE;
716 * ParseErrorInternal --
717 * Error function
719 * Results:
720 * None
722 * Side Effects:
723 * None
725 /* VARARGS */
726 static void
727 ParseErrorInternal(const char *cfname, size_t clineno, int type,
728 const char *fmt, ...)
730 va_list ap;
732 va_start(ap, fmt);
733 (void)fflush(stdout);
734 ParseVErrorInternal(stderr, cfname, clineno, type, fmt, ap);
735 va_end(ap);
737 if (debug_file != stderr && debug_file != stdout) {
738 va_start(ap, fmt);
739 ParseVErrorInternal(debug_file, cfname, clineno, type, fmt, ap);
740 va_end(ap);
745 * Parse_Error --
746 * External interface to ParseErrorInternal; uses the default filename
747 * Line number.
749 * Results:
750 * None
752 * Side Effects:
753 * None
755 /* VARARGS */
756 void
757 Parse_Error(int type, const char *fmt, ...)
759 va_list ap;
760 const char *fname;
761 size_t lineno;
763 if (curFile == NULL) {
764 fname = NULL;
765 lineno = 0;
766 } else {
767 fname = curFile->fname;
768 lineno = curFile->lineno;
771 va_start(ap, fmt);
772 (void)fflush(stdout);
773 ParseVErrorInternal(stderr, fname, lineno, type, fmt, ap);
774 va_end(ap);
776 if (debug_file != stderr && debug_file != stdout) {
777 va_start(ap, fmt);
778 ParseVErrorInternal(debug_file, fname, lineno, type, fmt, ap);
779 va_end(ap);
785 * ParseMessage
786 * Parse a .info .warning or .error directive
788 * The input is the line minus the ".". We substitute
789 * variables, print the message and exit(1) (for .error) or just print
790 * a warning if the directive is malformed.
792 static Boolean
793 ParseMessage(char *line)
795 int mtype;
797 switch(*line) {
798 case 'i':
799 mtype = 0;
800 break;
801 case 'w':
802 mtype = PARSE_WARNING;
803 break;
804 case 'e':
805 mtype = PARSE_FATAL;
806 break;
807 default:
808 Parse_Error(PARSE_WARNING, "invalid syntax: \".%s\"", line);
809 return FALSE;
812 while (isalpha((unsigned char)*line))
813 line++;
814 if (!isspace((unsigned char)*line))
815 return FALSE; /* not for us */
816 while (isspace((unsigned char)*line))
817 line++;
819 line = Var_Subst(NULL, line, VAR_CMD, VARF_WANTRES);
820 Parse_Error(mtype, "%s", line);
821 free(line);
823 if (mtype == PARSE_FATAL) {
824 /* Terminate immediately. */
825 exit(1);
827 return TRUE;
831 *---------------------------------------------------------------------
832 * ParseLinkSrc --
833 * Link the parent node to its new child. Used in a Lst_ForEach by
834 * ParseDoDependency. If the specType isn't 'Not', the parent
835 * isn't linked as a parent of the child.
837 * Input:
838 * pgnp The parent node
839 * cgpn The child node
841 * Results:
842 * Always = 0
844 * Side Effects:
845 * New elements are added to the parents list of cgn and the
846 * children list of cgn. the unmade field of pgn is updated
847 * to reflect the additional child.
848 *---------------------------------------------------------------------
850 static int
851 ParseLinkSrc(void *pgnp, void *cgnp)
853 GNode *pgn = (GNode *)pgnp;
854 GNode *cgn = (GNode *)cgnp;
856 if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (pgn->cohorts))
857 pgn = (GNode *)Lst_Datum(Lst_Last(pgn->cohorts));
858 (void)Lst_AtEnd(pgn->children, cgn);
859 if (specType == Not)
860 (void)Lst_AtEnd(cgn->parents, pgn);
861 pgn->unmade += 1;
862 if (DEBUG(PARSE)) {
863 fprintf(debug_file, "# %s: added child %s - %s\n", __func__,
864 pgn->name, cgn->name);
865 Targ_PrintNode(pgn, 0);
866 Targ_PrintNode(cgn, 0);
868 return (0);
872 *---------------------------------------------------------------------
873 * ParseDoOp --
874 * Apply the parsed operator to the given target node. Used in a
875 * Lst_ForEach call by ParseDoDependency once all targets have
876 * been found and their operator parsed. If the previous and new
877 * operators are incompatible, a major error is taken.
879 * Input:
880 * gnp The node to which the operator is to be applied
881 * opp The operator to apply
883 * Results:
884 * Always 0
886 * Side Effects:
887 * The type field of the node is altered to reflect any new bits in
888 * the op.
889 *---------------------------------------------------------------------
891 static int
892 ParseDoOp(void *gnp, void *opp)
894 GNode *gn = (GNode *)gnp;
895 int op = *(int *)opp;
897 * If the dependency mask of the operator and the node don't match and
898 * the node has actually had an operator applied to it before, and
899 * the operator actually has some dependency information in it, complain.
901 if (((op & OP_OPMASK) != (gn->type & OP_OPMASK)) &&
902 !OP_NOP(gn->type) && !OP_NOP(op))
904 Parse_Error(PARSE_FATAL, "Inconsistent operator for %s", gn->name);
905 return (1);
908 if ((op == OP_DOUBLEDEP) && ((gn->type & OP_OPMASK) == OP_DOUBLEDEP)) {
910 * If the node was the object of a :: operator, we need to create a
911 * new instance of it for the children and commands on this dependency
912 * line. The new instance is placed on the 'cohorts' list of the
913 * initial one (note the initial one is not on its own cohorts list)
914 * and the new instance is linked to all parents of the initial
915 * instance.
917 GNode *cohort;
920 * Propagate copied bits to the initial node. They'll be propagated
921 * back to the rest of the cohorts later.
923 gn->type |= op & ~OP_OPMASK;
925 cohort = Targ_FindNode(gn->name, TARG_NOHASH);
926 if (doing_depend)
927 ParseMark(cohort);
929 * Make the cohort invisible as well to avoid duplicating it into
930 * other variables. True, parents of this target won't tend to do
931 * anything with their local variables, but better safe than
932 * sorry. (I think this is pointless now, since the relevant list
933 * traversals will no longer see this node anyway. -mycroft)
935 cohort->type = op | OP_INVISIBLE;
936 (void)Lst_AtEnd(gn->cohorts, cohort);
937 cohort->centurion = gn;
938 gn->unmade_cohorts += 1;
939 snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
940 gn->unmade_cohorts);
941 } else {
943 * We don't want to nuke any previous flags (whatever they were) so we
944 * just OR the new operator into the old
946 gn->type |= op;
949 return (0);
953 *---------------------------------------------------------------------
954 * ParseDoSrc --
955 * Given the name of a source, figure out if it is an attribute
956 * and apply it to the targets if it is. Else decide if there is
957 * some attribute which should be applied *to* the source because
958 * of some special target and apply it if so. Otherwise, make the
959 * source be a child of the targets in the list 'targets'
961 * Input:
962 * tOp operator (if any) from special targets
963 * src name of the source to handle
965 * Results:
966 * None
968 * Side Effects:
969 * Operator bits may be added to the list of targets or to the source.
970 * The targets may have a new source added to their lists of children.
971 *---------------------------------------------------------------------
973 static void
974 ParseDoSrc(int tOp, const char *src)
976 GNode *gn = NULL;
977 static int wait_number = 0;
978 char wait_src[16];
980 if (*src == '.' && isupper ((unsigned char)src[1])) {
981 int keywd = ParseFindKeyword(src);
982 if (keywd != -1) {
983 int op = parseKeywords[keywd].op;
984 if (op != 0) {
985 Lst_ForEach(targets, ParseDoOp, &op);
986 return;
988 if (parseKeywords[keywd].spec == Wait) {
990 * We add a .WAIT node in the dependency list.
991 * After any dynamic dependencies (and filename globbing)
992 * have happened, it is given a dependency on the each
993 * previous child back to and previous .WAIT node.
994 * The next child won't be scheduled until the .WAIT node
995 * is built.
996 * We give each .WAIT node a unique name (mainly for diag).
998 snprintf(wait_src, sizeof wait_src, ".WAIT_%u", ++wait_number);
999 gn = Targ_FindNode(wait_src, TARG_NOHASH);
1000 if (doing_depend)
1001 ParseMark(gn);
1002 gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
1003 Lst_ForEach(targets, ParseLinkSrc, gn);
1004 return;
1009 switch (specType) {
1010 case Main:
1012 * If we have noted the existence of a .MAIN, it means we need
1013 * to add the sources of said target to the list of things
1014 * to create. The string 'src' is likely to be free, so we
1015 * must make a new copy of it. Note that this will only be
1016 * invoked if the user didn't specify a target on the command
1017 * line. This is to allow #ifmake's to succeed, or something...
1019 (void)Lst_AtEnd(create, bmake_strdup(src));
1021 * Add the name to the .TARGETS variable as well, so the user can
1022 * employ that, if desired.
1024 Var_Append(".TARGETS", src, VAR_GLOBAL);
1025 return;
1027 case Order:
1029 * Create proper predecessor/successor links between the previous
1030 * source and the current one.
1032 gn = Targ_FindNode(src, TARG_CREATE);
1033 if (doing_depend)
1034 ParseMark(gn);
1035 if (predecessor != NULL) {
1036 (void)Lst_AtEnd(predecessor->order_succ, gn);
1037 (void)Lst_AtEnd(gn->order_pred, predecessor);
1038 if (DEBUG(PARSE)) {
1039 fprintf(debug_file, "# %s: added Order dependency %s - %s\n",
1040 __func__, predecessor->name, gn->name);
1041 Targ_PrintNode(predecessor, 0);
1042 Targ_PrintNode(gn, 0);
1046 * The current source now becomes the predecessor for the next one.
1048 predecessor = gn;
1049 break;
1051 default:
1053 * If the source is not an attribute, we need to find/create
1054 * a node for it. After that we can apply any operator to it
1055 * from a special target or link it to its parents, as
1056 * appropriate.
1058 * In the case of a source that was the object of a :: operator,
1059 * the attribute is applied to all of its instances (as kept in
1060 * the 'cohorts' list of the node) or all the cohorts are linked
1061 * to all the targets.
1064 /* Find/create the 'src' node and attach to all targets */
1065 gn = Targ_FindNode(src, TARG_CREATE);
1066 if (doing_depend)
1067 ParseMark(gn);
1068 if (tOp) {
1069 gn->type |= tOp;
1070 } else {
1071 Lst_ForEach(targets, ParseLinkSrc, gn);
1073 break;
1078 *-----------------------------------------------------------------------
1079 * ParseFindMain --
1080 * Find a real target in the list and set it to be the main one.
1081 * Called by ParseDoDependency when a main target hasn't been found
1082 * yet.
1084 * Input:
1085 * gnp Node to examine
1087 * Results:
1088 * 0 if main not found yet, 1 if it is.
1090 * Side Effects:
1091 * mainNode is changed and Targ_SetMain is called.
1093 *-----------------------------------------------------------------------
1095 static int
1096 ParseFindMain(void *gnp, void *dummy)
1098 GNode *gn = (GNode *)gnp;
1099 if ((gn->type & OP_NOTARGET) == 0) {
1100 mainNode = gn;
1101 Targ_SetMain(gn);
1102 return (dummy ? 1 : 1);
1103 } else {
1104 return (dummy ? 0 : 0);
1109 *-----------------------------------------------------------------------
1110 * ParseAddDir --
1111 * Front-end for Dir_AddDir to make sure Lst_ForEach keeps going
1113 * Results:
1114 * === 0
1116 * Side Effects:
1117 * See Dir_AddDir.
1119 *-----------------------------------------------------------------------
1121 static int
1122 ParseAddDir(void *path, void *name)
1124 (void)Dir_AddDir((Lst) path, (char *)name);
1125 return(0);
1129 *-----------------------------------------------------------------------
1130 * ParseClearPath --
1131 * Front-end for Dir_ClearPath to make sure Lst_ForEach keeps going
1133 * Results:
1134 * === 0
1136 * Side Effects:
1137 * See Dir_ClearPath
1139 *-----------------------------------------------------------------------
1141 static int
1142 ParseClearPath(void *path, void *dummy)
1144 Dir_ClearPath((Lst) path);
1145 return(dummy ? 0 : 0);
1149 *---------------------------------------------------------------------
1150 * ParseDoDependency --
1151 * Parse the dependency line in line.
1153 * Input:
1154 * line the line to parse
1156 * Results:
1157 * None
1159 * Side Effects:
1160 * The nodes of the sources are linked as children to the nodes of the
1161 * targets. Some nodes may be created.
1163 * We parse a dependency line by first extracting words from the line and
1164 * finding nodes in the list of all targets with that name. This is done
1165 * until a character is encountered which is an operator character. Currently
1166 * these are only ! and :. At this point the operator is parsed and the
1167 * pointer into the line advanced until the first source is encountered.
1168 * The parsed operator is applied to each node in the 'targets' list,
1169 * which is where the nodes found for the targets are kept, by means of
1170 * the ParseDoOp function.
1171 * The sources are read in much the same way as the targets were except
1172 * that now they are expanded using the wildcarding scheme of the C-Shell
1173 * and all instances of the resulting words in the list of all targets
1174 * are found. Each of the resulting nodes is then linked to each of the
1175 * targets as one of its children.
1176 * Certain targets are handled specially. These are the ones detailed
1177 * by the specType variable.
1178 * The storing of transformation rules is also taken care of here.
1179 * A target is recognized as a transformation rule by calling
1180 * Suff_IsTransform. If it is a transformation rule, its node is gotten
1181 * from the suffix module via Suff_AddTransform rather than the standard
1182 * Targ_FindNode in the target module.
1183 *---------------------------------------------------------------------
1185 static void
1186 ParseDoDependency(char *line)
1188 char *cp; /* our current position */
1189 GNode *gn = NULL; /* a general purpose temporary node */
1190 int op; /* the operator on the line */
1191 char savec; /* a place to save a character */
1192 Lst paths; /* List of search paths to alter when parsing
1193 * a list of .PATH targets */
1194 int tOp; /* operator from special target */
1195 Lst sources; /* list of archive source names after
1196 * expansion */
1197 Lst curTargs; /* list of target names to be found and added
1198 * to the targets list */
1199 char *lstart = line;
1201 if (DEBUG(PARSE))
1202 fprintf(debug_file, "ParseDoDependency(%s)\n", line);
1203 tOp = 0;
1205 specType = Not;
1206 paths = NULL;
1208 curTargs = Lst_Init(FALSE);
1211 * First, grind through the targets.
1214 do {
1216 * Here LINE points to the beginning of the next word, and
1217 * LSTART points to the actual beginning of the line.
1220 /* Find the end of the next word. */
1221 for (cp = line; *cp && (ParseIsEscaped(lstart, cp) ||
1222 !(isspace((unsigned char)*cp) ||
1223 *cp == '!' || *cp == ':' || *cp == LPAREN));
1224 cp++) {
1225 if (*cp == '$') {
1227 * Must be a dynamic source (would have been expanded
1228 * otherwise), so call the Var module to parse the puppy
1229 * so we can safely advance beyond it...There should be
1230 * no errors in this, as they would have been discovered
1231 * in the initial Var_Subst and we wouldn't be here.
1233 int length;
1234 void *freeIt;
1236 (void)Var_Parse(cp, VAR_CMD, VARF_UNDEFERR|VARF_WANTRES,
1237 &length, &freeIt);
1238 free(freeIt);
1239 cp += length-1;
1244 * If the word is followed by a left parenthesis, it's the
1245 * name of an object file inside an archive (ar file).
1247 if (!ParseIsEscaped(lstart, cp) && *cp == LPAREN) {
1249 * Archives must be handled specially to make sure the OP_ARCHV
1250 * flag is set in their 'type' field, for one thing, and because
1251 * things like "archive(file1.o file2.o file3.o)" are permissible.
1252 * Arch_ParseArchive will set 'line' to be the first non-blank
1253 * after the archive-spec. It creates/finds nodes for the members
1254 * and places them on the given list, returning SUCCESS if all
1255 * went well and FAILURE if there was an error in the
1256 * specification. On error, line should remain untouched.
1258 if (Arch_ParseArchive(&line, targets, VAR_CMD) != SUCCESS) {
1259 Parse_Error(PARSE_FATAL,
1260 "Error in archive specification: \"%s\"", line);
1261 goto out;
1262 } else {
1263 /* Done with this word; on to the next. */
1264 cp = line;
1265 continue;
1269 if (!*cp) {
1271 * We got to the end of the line while we were still
1272 * looking at targets.
1274 * Ending a dependency line without an operator is a Bozo
1275 * no-no. As a heuristic, this is also often triggered by
1276 * undetected conflicts from cvs/rcs merges.
1278 if ((strncmp(line, "<<<<<<", 6) == 0) ||
1279 (strncmp(line, "======", 6) == 0) ||
1280 (strncmp(line, ">>>>>>", 6) == 0))
1281 Parse_Error(PARSE_FATAL,
1282 "Makefile appears to contain unresolved cvs/rcs/??? merge conflicts");
1283 else
1284 Parse_Error(PARSE_FATAL, lstart[0] == '.' ? "Unknown directive"
1285 : "Need an operator");
1286 goto out;
1289 /* Insert a null terminator. */
1290 savec = *cp;
1291 *cp = '\0';
1294 * Got the word. See if it's a special target and if so set
1295 * specType to match it.
1297 if (*line == '.' && isupper ((unsigned char)line[1])) {
1299 * See if the target is a special target that must have it
1300 * or its sources handled specially.
1302 int keywd = ParseFindKeyword(line);
1303 if (keywd != -1) {
1304 if (specType == ExPath && parseKeywords[keywd].spec != ExPath) {
1305 Parse_Error(PARSE_FATAL, "Mismatched special targets");
1306 goto out;
1309 specType = parseKeywords[keywd].spec;
1310 tOp = parseKeywords[keywd].op;
1313 * Certain special targets have special semantics:
1314 * .PATH Have to set the dirSearchPath
1315 * variable too
1316 * .MAIN Its sources are only used if
1317 * nothing has been specified to
1318 * create.
1319 * .DEFAULT Need to create a node to hang
1320 * commands on, but we don't want
1321 * it in the graph, nor do we want
1322 * it to be the Main Target, so we
1323 * create it, set OP_NOTMAIN and
1324 * add it to the list, setting
1325 * DEFAULT to the new node for
1326 * later use. We claim the node is
1327 * A transformation rule to make
1328 * life easier later, when we'll
1329 * use Make_HandleUse to actually
1330 * apply the .DEFAULT commands.
1331 * .PHONY The list of targets
1332 * .NOPATH Don't search for file in the path
1333 * .STALE
1334 * .BEGIN
1335 * .END
1336 * .ERROR
1337 * .INTERRUPT Are not to be considered the
1338 * main target.
1339 * .NOTPARALLEL Make only one target at a time.
1340 * .SINGLESHELL Create a shell for each command.
1341 * .ORDER Must set initial predecessor to NULL
1343 switch (specType) {
1344 case ExPath:
1345 if (paths == NULL) {
1346 paths = Lst_Init(FALSE);
1348 (void)Lst_AtEnd(paths, dirSearchPath);
1349 break;
1350 case Main:
1351 if (!Lst_IsEmpty(create)) {
1352 specType = Not;
1354 break;
1355 case Begin:
1356 case End:
1357 case Stale:
1358 case dotError:
1359 case Interrupt:
1360 gn = Targ_FindNode(line, TARG_CREATE);
1361 if (doing_depend)
1362 ParseMark(gn);
1363 gn->type |= OP_NOTMAIN|OP_SPECIAL;
1364 (void)Lst_AtEnd(targets, gn);
1365 break;
1366 case Default:
1367 gn = Targ_NewGN(".DEFAULT");
1368 gn->type |= (OP_NOTMAIN|OP_TRANSFORM);
1369 (void)Lst_AtEnd(targets, gn);
1370 DEFAULT = gn;
1371 break;
1372 case NotParallel:
1373 maxJobs = 1;
1374 break;
1375 case SingleShell:
1376 compatMake = TRUE;
1377 break;
1378 case Order:
1379 predecessor = NULL;
1380 break;
1381 default:
1382 break;
1384 } else if (strncmp(line, ".PATH", 5) == 0) {
1386 * .PATH<suffix> has to be handled specially.
1387 * Call on the suffix module to give us a path to
1388 * modify.
1390 Lst path;
1392 specType = ExPath;
1393 path = Suff_GetPath(&line[5]);
1394 if (path == NULL) {
1395 Parse_Error(PARSE_FATAL,
1396 "Suffix '%s' not defined (yet)",
1397 &line[5]);
1398 goto out;
1399 } else {
1400 if (paths == NULL) {
1401 paths = Lst_Init(FALSE);
1403 (void)Lst_AtEnd(paths, path);
1409 * Have word in line. Get or create its node and stick it at
1410 * the end of the targets list
1412 if ((specType == Not) && (*line != '\0')) {
1413 if (Dir_HasWildcards(line)) {
1415 * Targets are to be sought only in the current directory,
1416 * so create an empty path for the thing. Note we need to
1417 * use Dir_Destroy in the destruction of the path as the
1418 * Dir module could have added a directory to the path...
1420 Lst emptyPath = Lst_Init(FALSE);
1422 Dir_Expand(line, emptyPath, curTargs);
1424 Lst_Destroy(emptyPath, Dir_Destroy);
1425 } else {
1427 * No wildcards, but we want to avoid code duplication,
1428 * so create a list with the word on it.
1430 (void)Lst_AtEnd(curTargs, line);
1433 /* Apply the targets. */
1435 while(!Lst_IsEmpty(curTargs)) {
1436 char *targName = (char *)Lst_DeQueue(curTargs);
1438 if (!Suff_IsTransform (targName)) {
1439 gn = Targ_FindNode(targName, TARG_CREATE);
1440 } else {
1441 gn = Suff_AddTransform(targName);
1443 if (doing_depend)
1444 ParseMark(gn);
1446 (void)Lst_AtEnd(targets, gn);
1448 } else if (specType == ExPath && *line != '.' && *line != '\0') {
1449 Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", line);
1452 /* Don't need the inserted null terminator any more. */
1453 *cp = savec;
1456 * If it is a special type and not .PATH, it's the only target we
1457 * allow on this line...
1459 if (specType != Not && specType != ExPath) {
1460 Boolean warning = FALSE;
1462 while (*cp && (ParseIsEscaped(lstart, cp) ||
1463 ((*cp != '!') && (*cp != ':')))) {
1464 if (ParseIsEscaped(lstart, cp) ||
1465 (*cp != ' ' && *cp != '\t')) {
1466 warning = TRUE;
1468 cp++;
1470 if (warning) {
1471 Parse_Error(PARSE_WARNING, "Extra target ignored");
1473 } else {
1474 while (*cp && isspace ((unsigned char)*cp)) {
1475 cp++;
1478 line = cp;
1479 } while (*line && (ParseIsEscaped(lstart, line) ||
1480 ((*line != '!') && (*line != ':'))));
1483 * Don't need the list of target names anymore...
1485 Lst_Destroy(curTargs, NULL);
1486 curTargs = NULL;
1488 if (!Lst_IsEmpty(targets)) {
1489 switch(specType) {
1490 default:
1491 Parse_Error(PARSE_WARNING, "Special and mundane targets don't mix. Mundane ones ignored");
1492 break;
1493 case Default:
1494 case Stale:
1495 case Begin:
1496 case End:
1497 case dotError:
1498 case Interrupt:
1500 * These four create nodes on which to hang commands, so
1501 * targets shouldn't be empty...
1503 case Not:
1505 * Nothing special here -- targets can be empty if it wants.
1507 break;
1512 * Have now parsed all the target names. Must parse the operator next. The
1513 * result is left in op .
1515 if (*cp == '!') {
1516 op = OP_FORCE;
1517 } else if (*cp == ':') {
1518 if (cp[1] == ':') {
1519 op = OP_DOUBLEDEP;
1520 cp++;
1521 } else {
1522 op = OP_DEPENDS;
1524 } else {
1525 Parse_Error(PARSE_FATAL, lstart[0] == '.' ? "Unknown directive"
1526 : "Missing dependency operator");
1527 goto out;
1530 /* Advance beyond the operator */
1531 cp++;
1534 * Apply the operator to the target. This is how we remember which
1535 * operator a target was defined with. It fails if the operator
1536 * used isn't consistent across all references.
1538 Lst_ForEach(targets, ParseDoOp, &op);
1541 * Onward to the sources.
1543 * LINE will now point to the first source word, if any, or the
1544 * end of the string if not.
1546 while (*cp && isspace ((unsigned char)*cp)) {
1547 cp++;
1549 line = cp;
1552 * Several special targets take different actions if present with no
1553 * sources:
1554 * a .SUFFIXES line with no sources clears out all old suffixes
1555 * a .PRECIOUS line makes all targets precious
1556 * a .IGNORE line ignores errors for all targets
1557 * a .SILENT line creates silence when making all targets
1558 * a .PATH removes all directories from the search path(s).
1560 if (!*line) {
1561 switch (specType) {
1562 case Suffixes:
1563 Suff_ClearSuffixes();
1564 break;
1565 case Precious:
1566 allPrecious = TRUE;
1567 break;
1568 case Ignore:
1569 ignoreErrors = TRUE;
1570 break;
1571 case Silent:
1572 beSilent = TRUE;
1573 break;
1574 case ExPath:
1575 Lst_ForEach(paths, ParseClearPath, NULL);
1576 Dir_SetPATH();
1577 break;
1578 #ifdef POSIX
1579 case Posix:
1580 Var_Set("%POSIX", "1003.2", VAR_GLOBAL, 0);
1581 break;
1582 #endif
1583 default:
1584 break;
1586 } else if (specType == MFlags) {
1588 * Call on functions in main.c to deal with these arguments and
1589 * set the initial character to a null-character so the loop to
1590 * get sources won't get anything
1592 Main_ParseArgLine(line);
1593 *line = '\0';
1594 } else if (specType == ExShell) {
1595 if (Job_ParseShell(line) != SUCCESS) {
1596 Parse_Error(PARSE_FATAL, "improper shell specification");
1597 goto out;
1599 *line = '\0';
1600 } else if ((specType == NotParallel) || (specType == SingleShell)) {
1601 *line = '\0';
1605 * NOW GO FOR THE SOURCES
1607 if ((specType == Suffixes) || (specType == ExPath) ||
1608 (specType == Includes) || (specType == Libs) ||
1609 (specType == Null) || (specType == ExObjdir))
1611 while (*line) {
1613 * If the target was one that doesn't take files as its sources
1614 * but takes something like suffixes, we take each
1615 * space-separated word on the line as a something and deal
1616 * with it accordingly.
1618 * If the target was .SUFFIXES, we take each source as a
1619 * suffix and add it to the list of suffixes maintained by the
1620 * Suff module.
1622 * If the target was a .PATH, we add the source as a directory
1623 * to search on the search path.
1625 * If it was .INCLUDES, the source is taken to be the suffix of
1626 * files which will be #included and whose search path should
1627 * be present in the .INCLUDES variable.
1629 * If it was .LIBS, the source is taken to be the suffix of
1630 * files which are considered libraries and whose search path
1631 * should be present in the .LIBS variable.
1633 * If it was .NULL, the source is the suffix to use when a file
1634 * has no valid suffix.
1636 * If it was .OBJDIR, the source is a new definition for .OBJDIR,
1637 * and will cause make to do a new chdir to that path.
1639 while (*cp && !isspace ((unsigned char)*cp)) {
1640 cp++;
1642 savec = *cp;
1643 *cp = '\0';
1644 switch (specType) {
1645 case Suffixes:
1646 Suff_AddSuffix(line, &mainNode);
1647 break;
1648 case ExPath:
1649 Lst_ForEach(paths, ParseAddDir, line);
1650 break;
1651 case Includes:
1652 Suff_AddInclude(line);
1653 break;
1654 case Libs:
1655 Suff_AddLib(line);
1656 break;
1657 case Null:
1658 Suff_SetNull(line);
1659 break;
1660 case ExObjdir:
1661 Main_SetObjdir(line);
1662 break;
1663 default:
1664 break;
1666 *cp = savec;
1667 if (savec != '\0') {
1668 cp++;
1670 while (*cp && isspace ((unsigned char)*cp)) {
1671 cp++;
1673 line = cp;
1675 if (paths) {
1676 Lst_Destroy(paths, NULL);
1678 if (specType == ExPath)
1679 Dir_SetPATH();
1680 } else {
1681 while (*line) {
1683 * The targets take real sources, so we must beware of archive
1684 * specifications (i.e. things with left parentheses in them)
1685 * and handle them accordingly.
1687 for (; *cp && !isspace ((unsigned char)*cp); cp++) {
1688 if ((*cp == LPAREN) && (cp > line) && (cp[-1] != '$')) {
1690 * Only stop for a left parenthesis if it isn't at the
1691 * start of a word (that'll be for variable changes
1692 * later) and isn't preceded by a dollar sign (a dynamic
1693 * source).
1695 break;
1699 if (*cp == LPAREN) {
1700 sources = Lst_Init(FALSE);
1701 if (Arch_ParseArchive(&line, sources, VAR_CMD) != SUCCESS) {
1702 Parse_Error(PARSE_FATAL,
1703 "Error in source archive spec \"%s\"", line);
1704 goto out;
1707 while (!Lst_IsEmpty (sources)) {
1708 gn = (GNode *)Lst_DeQueue(sources);
1709 ParseDoSrc(tOp, gn->name);
1711 Lst_Destroy(sources, NULL);
1712 cp = line;
1713 } else {
1714 if (*cp) {
1715 *cp = '\0';
1716 cp += 1;
1719 ParseDoSrc(tOp, line);
1721 while (*cp && isspace ((unsigned char)*cp)) {
1722 cp++;
1724 line = cp;
1728 if (mainNode == NULL) {
1730 * If we have yet to decide on a main target to make, in the
1731 * absence of any user input, we want the first target on
1732 * the first dependency line that is actually a real target
1733 * (i.e. isn't a .USE or .EXEC rule) to be made.
1735 Lst_ForEach(targets, ParseFindMain, NULL);
1738 out:
1739 if (curTargs)
1740 Lst_Destroy(curTargs, NULL);
1744 *---------------------------------------------------------------------
1745 * Parse_IsVar --
1746 * Return TRUE if the passed line is a variable assignment. A variable
1747 * assignment consists of a single word followed by optional whitespace
1748 * followed by either a += or an = operator.
1749 * This function is used both by the Parse_File function and main when
1750 * parsing the command-line arguments.
1752 * Input:
1753 * line the line to check
1755 * Results:
1756 * TRUE if it is. FALSE if it ain't
1758 * Side Effects:
1759 * none
1760 *---------------------------------------------------------------------
1762 Boolean
1763 Parse_IsVar(char *line)
1765 Boolean wasSpace = FALSE; /* set TRUE if found a space */
1766 char ch;
1767 int level = 0;
1768 #define ISEQOPERATOR(c) \
1769 (((c) == '+') || ((c) == ':') || ((c) == '?') || ((c) == '!'))
1772 * Skip to variable name
1774 for (;(*line == ' ') || (*line == '\t'); line++)
1775 continue;
1777 /* Scan for one of the assignment operators outside a variable expansion */
1778 while ((ch = *line++) != 0) {
1779 if (ch == '(' || ch == '{') {
1780 level++;
1781 continue;
1783 if (ch == ')' || ch == '}') {
1784 level--;
1785 continue;
1787 if (level != 0)
1788 continue;
1789 while (ch == ' ' || ch == '\t') {
1790 ch = *line++;
1791 wasSpace = TRUE;
1793 #ifdef SUNSHCMD
1794 if (ch == ':' && strncmp(line, "sh", 2) == 0) {
1795 line += 2;
1796 continue;
1798 #endif
1799 if (ch == '=')
1800 return TRUE;
1801 if (*line == '=' && ISEQOPERATOR(ch))
1802 return TRUE;
1803 if (wasSpace)
1804 return FALSE;
1807 return FALSE;
1811 *---------------------------------------------------------------------
1812 * Parse_DoVar --
1813 * Take the variable assignment in the passed line and do it in the
1814 * global context.
1816 * Note: There is a lexical ambiguity with assignment modifier characters
1817 * in variable names. This routine interprets the character before the =
1818 * as a modifier. Therefore, an assignment like
1819 * C++=/usr/bin/CC
1820 * is interpreted as "C+ +=" instead of "C++ =".
1822 * Input:
1823 * line a line guaranteed to be a variable assignment.
1824 * This reduces error checks
1825 * ctxt Context in which to do the assignment
1827 * Results:
1828 * none
1830 * Side Effects:
1831 * the variable structure of the given variable name is altered in the
1832 * global context.
1833 *---------------------------------------------------------------------
1835 void
1836 Parse_DoVar(char *line, GNode *ctxt)
1838 char *cp; /* pointer into line */
1839 enum {
1840 VAR_SUBST, VAR_APPEND, VAR_SHELL, VAR_NORMAL
1841 } type; /* Type of assignment */
1842 char *opc; /* ptr to operator character to
1843 * null-terminate the variable name */
1844 Boolean freeCp = FALSE; /* TRUE if cp needs to be freed,
1845 * i.e. if any variable expansion was
1846 * performed */
1847 int depth;
1850 * Skip to variable name
1852 while ((*line == ' ') || (*line == '\t')) {
1853 line++;
1857 * Skip to operator character, nulling out whitespace as we go
1858 * XXX Rather than counting () and {} we should look for $ and
1859 * then expand the variable.
1861 for (depth = 0, cp = line + 1; depth != 0 || *cp != '='; cp++) {
1862 if (*cp == '(' || *cp == '{') {
1863 depth++;
1864 continue;
1866 if (*cp == ')' || *cp == '}') {
1867 depth--;
1868 continue;
1870 if (depth == 0 && isspace ((unsigned char)*cp)) {
1871 *cp = '\0';
1874 opc = cp-1; /* operator is the previous character */
1875 *cp++ = '\0'; /* nuke the = */
1878 * Check operator type
1880 switch (*opc) {
1881 case '+':
1882 type = VAR_APPEND;
1883 *opc = '\0';
1884 break;
1886 case '?':
1888 * If the variable already has a value, we don't do anything.
1890 *opc = '\0';
1891 if (Var_Exists(line, ctxt)) {
1892 return;
1893 } else {
1894 type = VAR_NORMAL;
1896 break;
1898 case ':':
1899 type = VAR_SUBST;
1900 *opc = '\0';
1901 break;
1903 case '!':
1904 type = VAR_SHELL;
1905 *opc = '\0';
1906 break;
1908 default:
1909 #ifdef SUNSHCMD
1910 while (opc > line && *opc != ':')
1911 opc--;
1913 if (strncmp(opc, ":sh", 3) == 0) {
1914 type = VAR_SHELL;
1915 *opc = '\0';
1916 break;
1918 #endif
1919 type = VAR_NORMAL;
1920 break;
1923 while (isspace ((unsigned char)*cp)) {
1924 cp++;
1927 if (type == VAR_APPEND) {
1928 Var_Append(line, cp, ctxt);
1929 } else if (type == VAR_SUBST) {
1931 * Allow variables in the old value to be undefined, but leave their
1932 * invocation alone -- this is done by forcing oldVars to be false.
1933 * XXX: This can cause recursive variables, but that's not hard to do,
1934 * and this allows someone to do something like
1936 * CFLAGS = $(.INCLUDES)
1937 * CFLAGS := -I.. $(CFLAGS)
1939 * And not get an error.
1941 Boolean oldOldVars = oldVars;
1943 oldVars = FALSE;
1946 * make sure that we set the variable the first time to nothing
1947 * so that it gets substituted!
1949 if (!Var_Exists(line, ctxt))
1950 Var_Set(line, "", ctxt, 0);
1952 cp = Var_Subst(NULL, cp, ctxt, VARF_WANTRES|VARF_ASSIGN);
1953 oldVars = oldOldVars;
1954 freeCp = TRUE;
1956 Var_Set(line, cp, ctxt, 0);
1957 } else if (type == VAR_SHELL) {
1958 char *res;
1959 const char *error;
1961 if (strchr(cp, '$') != NULL) {
1963 * There's a dollar sign in the command, so perform variable
1964 * expansion on the whole thing. The resulting string will need
1965 * freeing when we're done, so set freeCmd to TRUE.
1967 cp = Var_Subst(NULL, cp, VAR_CMD, VARF_UNDEFERR|VARF_WANTRES);
1968 freeCp = TRUE;
1971 res = Cmd_Exec(cp, &error);
1972 Var_Set(line, res, ctxt, 0);
1973 free(res);
1975 if (error)
1976 Parse_Error(PARSE_WARNING, error, cp);
1977 } else {
1979 * Normal assignment -- just do it.
1981 Var_Set(line, cp, ctxt, 0);
1983 if (strcmp(line, MAKEOVERRIDES) == 0)
1984 Main_ExportMAKEFLAGS(FALSE); /* re-export MAKEFLAGS */
1985 else if (strcmp(line, ".CURDIR") == 0) {
1987 * Somone is being (too?) clever...
1988 * Let's pretend they know what they are doing and
1989 * re-initialize the 'cur' Path.
1991 Dir_InitCur(cp);
1992 Dir_SetPATH();
1993 } else if (strcmp(line, MAKE_JOB_PREFIX) == 0) {
1994 Job_SetPrefix();
1995 } else if (strcmp(line, MAKE_EXPORTED) == 0) {
1996 Var_Export(cp, 0);
1998 if (freeCp)
1999 free(cp);
2004 * ParseMaybeSubMake --
2005 * Scan the command string to see if it a possible submake node
2006 * Input:
2007 * cmd the command to scan
2008 * Results:
2009 * TRUE if the command is possibly a submake, FALSE if not.
2011 static Boolean
2012 ParseMaybeSubMake(const char *cmd)
2014 size_t i;
2015 static struct {
2016 const char *name;
2017 size_t len;
2018 } vals[] = {
2019 #define MKV(A) { A, sizeof(A) - 1 }
2020 MKV("${MAKE}"),
2021 MKV("${.MAKE}"),
2022 MKV("$(MAKE)"),
2023 MKV("$(.MAKE)"),
2024 MKV("make"),
2026 for (i = 0; i < sizeof(vals)/sizeof(vals[0]); i++) {
2027 char *ptr;
2028 if ((ptr = strstr(cmd, vals[i].name)) == NULL)
2029 continue;
2030 if ((ptr == cmd || !isalnum((unsigned char)ptr[-1]))
2031 && !isalnum((unsigned char)ptr[vals[i].len]))
2032 return TRUE;
2034 return FALSE;
2038 * ParseAddCmd --
2039 * Lst_ForEach function to add a command line to all targets
2041 * Input:
2042 * gnp the node to which the command is to be added
2043 * cmd the command to add
2045 * Results:
2046 * Always 0
2048 * Side Effects:
2049 * A new element is added to the commands list of the node,
2050 * and the node can be marked as a submake node if the command is
2051 * determined to be that.
2053 static int
2054 ParseAddCmd(void *gnp, void *cmd)
2056 GNode *gn = (GNode *)gnp;
2058 /* Add to last (ie current) cohort for :: targets */
2059 if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts))
2060 gn = (GNode *)Lst_Datum(Lst_Last(gn->cohorts));
2062 /* if target already supplied, ignore commands */
2063 if (!(gn->type & OP_HAS_COMMANDS)) {
2064 (void)Lst_AtEnd(gn->commands, cmd);
2065 if (ParseMaybeSubMake(cmd))
2066 gn->type |= OP_SUBMAKE;
2067 ParseMark(gn);
2068 } else {
2069 #ifdef notyet
2070 /* XXX: We cannot do this until we fix the tree */
2071 (void)Lst_AtEnd(gn->commands, cmd);
2072 Parse_Error(PARSE_WARNING,
2073 "overriding commands for target \"%s\"; "
2074 "previous commands defined at %s: %d ignored",
2075 gn->name, gn->fname, gn->lineno);
2076 #else
2077 Parse_Error(PARSE_WARNING,
2078 "duplicate script for target \"%s\" ignored",
2079 gn->name);
2080 ParseErrorInternal(gn->fname, gn->lineno, PARSE_WARNING,
2081 "using previous script for \"%s\" defined here",
2082 gn->name);
2083 #endif
2085 return(0);
2089 *-----------------------------------------------------------------------
2090 * ParseHasCommands --
2091 * Callback procedure for Parse_File when destroying the list of
2092 * targets on the last dependency line. Marks a target as already
2093 * having commands if it does, to keep from having shell commands
2094 * on multiple dependency lines.
2096 * Input:
2097 * gnp Node to examine
2099 * Results:
2100 * None
2102 * Side Effects:
2103 * OP_HAS_COMMANDS may be set for the target.
2105 *-----------------------------------------------------------------------
2107 static void
2108 ParseHasCommands(void *gnp)
2110 GNode *gn = (GNode *)gnp;
2111 if (!Lst_IsEmpty(gn->commands)) {
2112 gn->type |= OP_HAS_COMMANDS;
2117 *-----------------------------------------------------------------------
2118 * Parse_AddIncludeDir --
2119 * Add a directory to the path searched for included makefiles
2120 * bracketed by double-quotes. Used by functions in main.c
2122 * Input:
2123 * dir The name of the directory to add
2125 * Results:
2126 * None.
2128 * Side Effects:
2129 * The directory is appended to the list.
2131 *-----------------------------------------------------------------------
2133 void
2134 Parse_AddIncludeDir(char *dir)
2136 (void)Dir_AddDir(parseIncPath, dir);
2140 *---------------------------------------------------------------------
2141 * ParseDoInclude --
2142 * Push to another file.
2144 * The input is the line minus the `.'. A file spec is a string
2145 * enclosed in <> or "". The former is looked for only in sysIncPath.
2146 * The latter in . and the directories specified by -I command line
2147 * options
2149 * Results:
2150 * None
2152 * Side Effects:
2153 * A structure is added to the includes Lst and readProc, lineno,
2154 * fname and curFILE are altered for the new file
2155 *---------------------------------------------------------------------
2158 static void
2159 Parse_include_file(char *file, Boolean isSystem, Boolean depinc, int silent)
2161 struct loadedfile *lf;
2162 char *fullname; /* full pathname of file */
2163 char *newName;
2164 char *prefEnd, *incdir;
2165 int fd;
2166 int i;
2169 * Now we know the file's name and its search path, we attempt to
2170 * find the durn thing. A return of NULL indicates the file don't
2171 * exist.
2173 fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
2175 if (fullname == NULL && !isSystem) {
2177 * Include files contained in double-quotes are first searched for
2178 * relative to the including file's location. We don't want to
2179 * cd there, of course, so we just tack on the old file's
2180 * leading path components and call Dir_FindFile to see if
2181 * we can locate the beast.
2184 incdir = bmake_strdup(curFile->fname);
2185 prefEnd = strrchr(incdir, '/');
2186 if (prefEnd != NULL) {
2187 *prefEnd = '\0';
2188 /* Now do lexical processing of leading "../" on the filename */
2189 for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
2190 prefEnd = strrchr(incdir + 1, '/');
2191 if (prefEnd == NULL || strcmp(prefEnd, "/..") == 0)
2192 break;
2193 *prefEnd = '\0';
2195 newName = str_concat(incdir, file + i, STR_ADDSLASH);
2196 fullname = Dir_FindFile(newName, parseIncPath);
2197 if (fullname == NULL)
2198 fullname = Dir_FindFile(newName, dirSearchPath);
2199 free(newName);
2201 free(incdir);
2203 if (fullname == NULL) {
2205 * Makefile wasn't found in same directory as included makefile.
2206 * Search for it first on the -I search path,
2207 * then on the .PATH search path, if not found in a -I directory.
2208 * If we have a suffix specific path we should use that.
2210 char *suff;
2211 Lst suffPath = NULL;
2213 if ((suff = strrchr(file, '.'))) {
2214 suffPath = Suff_GetPath(suff);
2215 if (suffPath != NULL) {
2216 fullname = Dir_FindFile(file, suffPath);
2219 if (fullname == NULL) {
2220 fullname = Dir_FindFile(file, parseIncPath);
2221 if (fullname == NULL) {
2222 fullname = Dir_FindFile(file, dirSearchPath);
2228 /* Looking for a system file or file still not found */
2229 if (fullname == NULL) {
2231 * Look for it on the system path
2233 fullname = Dir_FindFile(file,
2234 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
2237 if (fullname == NULL) {
2238 if (!silent)
2239 Parse_Error(PARSE_FATAL, "Could not find %s", file);
2240 return;
2243 /* Actually open the file... */
2244 fd = open(fullname, O_RDONLY);
2245 if (fd == -1) {
2246 if (!silent)
2247 Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
2248 free(fullname);
2249 return;
2252 /* load it */
2253 lf = loadfile(fullname, fd);
2255 ParseSetIncludedFile();
2256 /* Start reading from this file next */
2257 Parse_SetInput(fullname, 0, -1, loadedfile_nextbuf, lf);
2258 curFile->lf = lf;
2259 if (depinc)
2260 doing_depend = depinc; /* only turn it on */
2263 static void
2264 ParseDoInclude(char *line)
2266 char endc; /* the character which ends the file spec */
2267 char *cp; /* current position in file spec */
2268 int silent = (*line != 'i') ? 1 : 0;
2269 char *file = &line[7 + silent];
2271 /* Skip to delimiter character so we know where to look */
2272 while (*file == ' ' || *file == '\t')
2273 file++;
2275 if (*file != '"' && *file != '<') {
2276 Parse_Error(PARSE_FATAL,
2277 ".include filename must be delimited by '\"' or '<'");
2278 return;
2282 * Set the search path on which to find the include file based on the
2283 * characters which bracket its name. Angle-brackets imply it's
2284 * a system Makefile while double-quotes imply it's a user makefile
2286 if (*file == '<') {
2287 endc = '>';
2288 } else {
2289 endc = '"';
2292 /* Skip to matching delimiter */
2293 for (cp = ++file; *cp && *cp != endc; cp++)
2294 continue;
2296 if (*cp != endc) {
2297 Parse_Error(PARSE_FATAL,
2298 "Unclosed %cinclude filename. '%c' expected",
2299 '.', endc);
2300 return;
2302 *cp = '\0';
2305 * Substitute for any variables in the file name before trying to
2306 * find the thing.
2308 file = Var_Subst(NULL, file, VAR_CMD, VARF_WANTRES);
2310 Parse_include_file(file, endc == '>', (*line == 'd'), silent);
2311 free(file);
2316 *---------------------------------------------------------------------
2317 * ParseSetIncludedFile --
2318 * Set the .INCLUDEDFROMFILE variable to the contents of .PARSEFILE
2319 * and the .INCLUDEDFROMDIR variable to the contents of .PARSEDIR
2321 * Results:
2322 * None
2324 * Side Effects:
2325 * The .INCLUDEDFROMFILE variable is overwritten by the contents
2326 * of .PARSEFILE and the .INCLUDEDFROMDIR variable is overwriten
2327 * by the contents of .PARSEDIR
2328 *---------------------------------------------------------------------
2330 static void
2331 ParseSetIncludedFile(void)
2333 char *pf, *fp = NULL;
2334 char *pd, *dp = NULL;
2336 pf = Var_Value(".PARSEFILE", VAR_GLOBAL, &fp);
2337 Var_Set(".INCLUDEDFROMFILE", pf, VAR_GLOBAL, 0);
2338 pd = Var_Value(".PARSEDIR", VAR_GLOBAL, &dp);
2339 Var_Set(".INCLUDEDFROMDIR", pd, VAR_GLOBAL, 0);
2341 if (DEBUG(PARSE))
2342 fprintf(debug_file, "%s: ${.INCLUDEDFROMDIR} = `%s' "
2343 "${.INCLUDEDFROMFILE} = `%s'\n", __func__, pd, pf);
2345 free(fp);
2346 free(dp);
2349 *---------------------------------------------------------------------
2350 * ParseSetParseFile --
2351 * Set the .PARSEDIR and .PARSEFILE variables to the dirname and
2352 * basename of the given filename
2354 * Results:
2355 * None
2357 * Side Effects:
2358 * The .PARSEDIR and .PARSEFILE variables are overwritten by the
2359 * dirname and basename of the given filename.
2360 *---------------------------------------------------------------------
2362 static void
2363 ParseSetParseFile(const char *filename)
2365 char *slash, *dirname;
2366 const char *pd, *pf;
2367 int len;
2369 slash = strrchr(filename, '/');
2370 if (slash == NULL) {
2371 Var_Set(".PARSEDIR", pd = curdir, VAR_GLOBAL, 0);
2372 Var_Set(".PARSEFILE", pf = filename, VAR_GLOBAL, 0);
2373 dirname= NULL;
2374 } else {
2375 len = slash - filename;
2376 dirname = bmake_malloc(len + 1);
2377 memcpy(dirname, filename, len);
2378 dirname[len] = '\0';
2379 Var_Set(".PARSEDIR", pd = dirname, VAR_GLOBAL, 0);
2380 Var_Set(".PARSEFILE", pf = slash + 1, VAR_GLOBAL, 0);
2382 if (DEBUG(PARSE))
2383 fprintf(debug_file, "%s: ${.PARSEDIR} = `%s' ${.PARSEFILE} = `%s'\n",
2384 __func__, pd, pf);
2385 free(dirname);
2389 * Track the makefiles we read - so makefiles can
2390 * set dependencies on them.
2391 * Avoid adding anything more than once.
2394 static void
2395 ParseTrackInput(const char *name)
2397 char *old;
2398 char *ep;
2399 char *fp = NULL;
2400 size_t name_len = strlen(name);
2402 old = Var_Value(MAKE_MAKEFILES, VAR_GLOBAL, &fp);
2403 if (old) {
2404 ep = old + strlen(old) - name_len;
2405 /* does it contain name? */
2406 for (; old != NULL; old = strchr(old, ' ')) {
2407 if (*old == ' ')
2408 old++;
2409 if (old >= ep)
2410 break; /* cannot contain name */
2411 if (memcmp(old, name, name_len) == 0
2412 && (old[name_len] == 0 || old[name_len] == ' '))
2413 goto cleanup;
2416 Var_Append (MAKE_MAKEFILES, name, VAR_GLOBAL);
2417 cleanup:
2418 if (fp) {
2419 free(fp);
2425 *---------------------------------------------------------------------
2426 * Parse_setInput --
2427 * Start Parsing from the given source
2429 * Results:
2430 * None
2432 * Side Effects:
2433 * A structure is added to the includes Lst and readProc, lineno,
2434 * fname and curFile are altered for the new file
2435 *---------------------------------------------------------------------
2437 void
2438 Parse_SetInput(const char *name, int line, int fd,
2439 char *(*nextbuf)(void *, size_t *), void *arg)
2441 char *buf;
2442 size_t len;
2444 if (name == NULL)
2445 name = curFile->fname;
2446 else
2447 ParseTrackInput(name);
2449 if (DEBUG(PARSE))
2450 fprintf(debug_file, "%s: file %s, line %d, fd %d, nextbuf %p, arg %p\n",
2451 __func__, name, line, fd, nextbuf, arg);
2453 if (fd == -1 && nextbuf == NULL)
2454 /* sanity */
2455 return;
2457 if (curFile != NULL)
2458 /* Save exiting file info */
2459 Lst_AtFront(includes, curFile);
2461 /* Allocate and fill in new structure */
2462 curFile = bmake_malloc(sizeof *curFile);
2465 * Once the previous state has been saved, we can get down to reading
2466 * the new file. We set up the name of the file to be the absolute
2467 * name of the include file so error messages refer to the right
2468 * place.
2470 curFile->fname = bmake_strdup(name);
2471 curFile->lineno = line;
2472 curFile->first_lineno = line;
2473 curFile->nextbuf = nextbuf;
2474 curFile->nextbuf_arg = arg;
2475 curFile->lf = NULL;
2476 curFile->depending = doing_depend; /* restore this on EOF */
2478 assert(nextbuf != NULL);
2480 /* Get first block of input data */
2481 buf = curFile->nextbuf(curFile->nextbuf_arg, &len);
2482 if (buf == NULL) {
2483 /* Was all a waste of time ... */
2484 if (curFile->fname)
2485 free(curFile->fname);
2486 free(curFile);
2487 return;
2489 curFile->P_str = buf;
2490 curFile->P_ptr = buf;
2491 curFile->P_end = buf+len;
2493 curFile->cond_depth = Cond_save_depth();
2494 ParseSetParseFile(name);
2497 #ifdef SYSVINCLUDE
2499 *---------------------------------------------------------------------
2500 * ParseTraditionalInclude --
2501 * Push to another file.
2503 * The input is the current line. The file name(s) are
2504 * following the "include".
2506 * Results:
2507 * None
2509 * Side Effects:
2510 * A structure is added to the includes Lst and readProc, lineno,
2511 * fname and curFILE are altered for the new file
2512 *---------------------------------------------------------------------
2514 static void
2515 ParseTraditionalInclude(char *line)
2517 char *cp; /* current position in file spec */
2518 int done = 0;
2519 int silent = (line[0] != 'i') ? 1 : 0;
2520 char *file = &line[silent + 7];
2521 char *all_files;
2523 if (DEBUG(PARSE)) {
2524 fprintf(debug_file, "%s: %s\n", __func__, file);
2528 * Skip over whitespace
2530 while (isspace((unsigned char)*file))
2531 file++;
2534 * Substitute for any variables in the file name before trying to
2535 * find the thing.
2537 all_files = Var_Subst(NULL, file, VAR_CMD, VARF_WANTRES);
2539 if (*file == '\0') {
2540 Parse_Error(PARSE_FATAL,
2541 "Filename missing from \"include\"");
2542 return;
2545 for (file = all_files; !done; file = cp + 1) {
2546 /* Skip to end of line or next whitespace */
2547 for (cp = file; *cp && !isspace((unsigned char) *cp); cp++)
2548 continue;
2550 if (*cp)
2551 *cp = '\0';
2552 else
2553 done = 1;
2555 Parse_include_file(file, FALSE, FALSE, silent);
2557 free(all_files);
2559 #endif
2561 #ifdef GMAKEEXPORT
2563 *---------------------------------------------------------------------
2564 * ParseGmakeExport --
2565 * Parse export <variable>=<value>
2567 * And set the environment with it.
2569 * Results:
2570 * None
2572 * Side Effects:
2573 * None
2574 *---------------------------------------------------------------------
2576 static void
2577 ParseGmakeExport(char *line)
2579 char *variable = &line[6];
2580 char *value;
2582 if (DEBUG(PARSE)) {
2583 fprintf(debug_file, "%s: %s\n", __func__, variable);
2587 * Skip over whitespace
2589 while (isspace((unsigned char)*variable))
2590 variable++;
2592 for (value = variable; *value && *value != '='; value++)
2593 continue;
2595 if (*value != '=') {
2596 Parse_Error(PARSE_FATAL,
2597 "Variable/Value missing from \"export\"");
2598 return;
2600 *value++ = '\0'; /* terminate variable */
2603 * Expand the value before putting it in the environment.
2605 value = Var_Subst(NULL, value, VAR_CMD, VARF_WANTRES);
2606 setenv(variable, value, 1);
2608 #endif
2611 *---------------------------------------------------------------------
2612 * ParseEOF --
2613 * Called when EOF is reached in the current file. If we were reading
2614 * an include file, the includes stack is popped and things set up
2615 * to go back to reading the previous file at the previous location.
2617 * Results:
2618 * CONTINUE if there's more to do. DONE if not.
2620 * Side Effects:
2621 * The old curFILE, is closed. The includes list is shortened.
2622 * lineno, curFILE, and fname are changed if CONTINUE is returned.
2623 *---------------------------------------------------------------------
2625 static int
2626 ParseEOF(void)
2628 char *ptr;
2629 size_t len;
2631 assert(curFile->nextbuf != NULL);
2633 doing_depend = curFile->depending; /* restore this */
2634 /* get next input buffer, if any */
2635 ptr = curFile->nextbuf(curFile->nextbuf_arg, &len);
2636 curFile->P_ptr = ptr;
2637 curFile->P_str = ptr;
2638 curFile->P_end = ptr + len;
2639 curFile->lineno = curFile->first_lineno;
2640 if (ptr != NULL) {
2641 /* Iterate again */
2642 return CONTINUE;
2645 /* Ensure the makefile (or loop) didn't have mismatched conditionals */
2646 Cond_restore_depth(curFile->cond_depth);
2648 if (curFile->lf != NULL) {
2649 loadedfile_destroy(curFile->lf);
2650 curFile->lf = NULL;
2653 /* Dispose of curFile info */
2654 /* Leak curFile->fname because all the gnodes have pointers to it */
2655 free(curFile->P_str);
2656 free(curFile);
2658 curFile = Lst_DeQueue(includes);
2660 if (curFile == NULL) {
2661 /* We've run out of input */
2662 Var_Delete(".PARSEDIR", VAR_GLOBAL);
2663 Var_Delete(".PARSEFILE", VAR_GLOBAL);
2664 Var_Delete(".INCLUDEDFROMDIR", VAR_GLOBAL);
2665 Var_Delete(".INCLUDEDFROMFILE", VAR_GLOBAL);
2666 return DONE;
2669 if (DEBUG(PARSE))
2670 fprintf(debug_file, "ParseEOF: returning to file %s, line %d\n",
2671 curFile->fname, curFile->lineno);
2673 /* Restore the PARSEDIR/PARSEFILE variables */
2674 ParseSetParseFile(curFile->fname);
2675 return (CONTINUE);
2678 #define PARSE_RAW 1
2679 #define PARSE_SKIP 2
2681 static char *
2682 ParseGetLine(int flags, int *length)
2684 IFile *cf = curFile;
2685 char *ptr;
2686 char ch;
2687 char *line;
2688 char *line_end;
2689 char *escaped;
2690 char *comment;
2691 char *tp;
2693 /* Loop through blank lines and comment lines */
2694 for (;;) {
2695 cf->lineno++;
2696 line = cf->P_ptr;
2697 ptr = line;
2698 line_end = line;
2699 escaped = NULL;
2700 comment = NULL;
2701 for (;;) {
2702 if (cf->P_end != NULL && ptr == cf->P_end) {
2703 /* end of buffer */
2704 ch = 0;
2705 break;
2707 ch = *ptr;
2708 if (ch == 0 || (ch == '\\' && ptr[1] == 0)) {
2709 if (cf->P_end == NULL)
2710 /* End of string (aka for loop) data */
2711 break;
2712 /* see if there is more we can parse */
2713 while (ptr++ < cf->P_end) {
2714 if ((ch = *ptr) == '\n') {
2715 if (ptr > line && ptr[-1] == '\\')
2716 continue;
2717 Parse_Error(PARSE_WARNING,
2718 "Zero byte read from file, skipping rest of line.");
2719 break;
2722 if (cf->nextbuf != NULL) {
2724 * End of this buffer; return EOF and outer logic
2725 * will get the next one. (eww)
2727 break;
2729 Parse_Error(PARSE_FATAL, "Zero byte read from file");
2730 return NULL;
2733 if (ch == '\\') {
2734 /* Don't treat next character as special, remember first one */
2735 if (escaped == NULL)
2736 escaped = ptr;
2737 if (ptr[1] == '\n')
2738 cf->lineno++;
2739 ptr += 2;
2740 line_end = ptr;
2741 continue;
2743 if (ch == '#' && comment == NULL) {
2744 /* Remember first '#' for comment stripping */
2745 /* Unless previous char was '[', as in modifier :[#] */
2746 if (!(ptr > line && ptr[-1] == '['))
2747 comment = line_end;
2749 ptr++;
2750 if (ch == '\n')
2751 break;
2752 if (!isspace((unsigned char)ch))
2753 /* We are not interested in trailing whitespace */
2754 line_end = ptr;
2757 /* Save next 'to be processed' location */
2758 cf->P_ptr = ptr;
2760 /* Check we have a non-comment, non-blank line */
2761 if (line_end == line || comment == line) {
2762 if (ch == 0)
2763 /* At end of file */
2764 return NULL;
2765 /* Parse another line */
2766 continue;
2769 /* We now have a line of data */
2770 *line_end = 0;
2772 if (flags & PARSE_RAW) {
2773 /* Leave '\' (etc) in line buffer (eg 'for' lines) */
2774 *length = line_end - line;
2775 return line;
2778 if (flags & PARSE_SKIP) {
2779 /* Completely ignore non-directives */
2780 if (line[0] != '.')
2781 continue;
2782 /* We could do more of the .else/.elif/.endif checks here */
2784 break;
2787 /* Brutally ignore anything after a non-escaped '#' in non-commands */
2788 if (comment != NULL && line[0] != '\t') {
2789 line_end = comment;
2790 *line_end = 0;
2793 /* If we didn't see a '\\' then the in-situ data is fine */
2794 if (escaped == NULL) {
2795 *length = line_end - line;
2796 return line;
2799 /* Remove escapes from '\n' and '#' */
2800 tp = ptr = escaped;
2801 escaped = line;
2802 for (; ; *tp++ = ch) {
2803 ch = *ptr++;
2804 if (ch != '\\') {
2805 if (ch == 0)
2806 break;
2807 continue;
2810 ch = *ptr++;
2811 if (ch == 0) {
2812 /* Delete '\\' at end of buffer */
2813 tp--;
2814 break;
2817 if (ch == '#' && line[0] != '\t')
2818 /* Delete '\\' from before '#' on non-command lines */
2819 continue;
2821 if (ch != '\n') {
2822 /* Leave '\\' in buffer for later */
2823 *tp++ = '\\';
2824 /* Make sure we don't delete an escaped ' ' from the line end */
2825 escaped = tp + 1;
2826 continue;
2829 /* Escaped '\n' replace following whitespace with a single ' ' */
2830 while (ptr[0] == ' ' || ptr[0] == '\t')
2831 ptr++;
2832 ch = ' ';
2835 /* Delete any trailing spaces - eg from empty continuations */
2836 while (tp > escaped && isspace((unsigned char)tp[-1]))
2837 tp--;
2839 *tp = 0;
2840 *length = tp - line;
2841 return line;
2845 *---------------------------------------------------------------------
2846 * ParseReadLine --
2847 * Read an entire line from the input file. Called only by Parse_File.
2849 * Results:
2850 * A line w/o its newline
2852 * Side Effects:
2853 * Only those associated with reading a character
2854 *---------------------------------------------------------------------
2856 static char *
2857 ParseReadLine(void)
2859 char *line; /* Result */
2860 int lineLength; /* Length of result */
2861 int lineno; /* Saved line # */
2862 int rval;
2864 for (;;) {
2865 line = ParseGetLine(0, &lineLength);
2866 if (line == NULL)
2867 return NULL;
2869 if (line[0] != '.')
2870 return line;
2873 * The line might be a conditional. Ask the conditional module
2874 * about it and act accordingly
2876 switch (Cond_Eval(line)) {
2877 case COND_SKIP:
2878 /* Skip to next conditional that evaluates to COND_PARSE. */
2879 do {
2880 line = ParseGetLine(PARSE_SKIP, &lineLength);
2881 } while (line && Cond_Eval(line) != COND_PARSE);
2882 if (line == NULL)
2883 break;
2884 continue;
2885 case COND_PARSE:
2886 continue;
2887 case COND_INVALID: /* Not a conditional line */
2888 /* Check for .for loops */
2889 rval = For_Eval(line);
2890 if (rval == 0)
2891 /* Not a .for line */
2892 break;
2893 if (rval < 0)
2894 /* Syntax error - error printed, ignore line */
2895 continue;
2896 /* Start of a .for loop */
2897 lineno = curFile->lineno;
2898 /* Accumulate loop lines until matching .endfor */
2899 do {
2900 line = ParseGetLine(PARSE_RAW, &lineLength);
2901 if (line == NULL) {
2902 Parse_Error(PARSE_FATAL,
2903 "Unexpected end of file in for loop.");
2904 break;
2906 } while (For_Accum(line));
2907 /* Stash each iteration as a new 'input file' */
2908 For_Run(lineno);
2909 /* Read next line from for-loop buffer */
2910 continue;
2912 return (line);
2917 *-----------------------------------------------------------------------
2918 * ParseFinishLine --
2919 * Handle the end of a dependency group.
2921 * Results:
2922 * Nothing.
2924 * Side Effects:
2925 * inLine set FALSE. 'targets' list destroyed.
2927 *-----------------------------------------------------------------------
2929 static void
2930 ParseFinishLine(void)
2932 if (inLine) {
2933 Lst_ForEach(targets, Suff_EndTransform, NULL);
2934 Lst_Destroy(targets, ParseHasCommands);
2935 targets = NULL;
2936 inLine = FALSE;
2942 *---------------------------------------------------------------------
2943 * Parse_File --
2944 * Parse a file into its component parts, incorporating it into the
2945 * current dependency graph. This is the main function and controls
2946 * almost every other function in this module
2948 * Input:
2949 * name the name of the file being read
2950 * fd Open file to makefile to parse
2952 * Results:
2953 * None
2955 * Side Effects:
2956 * closes fd.
2957 * Loads. Nodes are added to the list of all targets, nodes and links
2958 * are added to the dependency graph. etc. etc. etc.
2959 *---------------------------------------------------------------------
2961 void
2962 Parse_File(const char *name, int fd)
2964 char *cp; /* pointer into the line */
2965 char *line; /* the line we're working on */
2966 struct loadedfile *lf;
2968 lf = loadfile(name, fd);
2970 inLine = FALSE;
2971 fatals = 0;
2973 if (name == NULL) {
2974 name = "(stdin)";
2977 Parse_SetInput(name, 0, -1, loadedfile_nextbuf, lf);
2978 curFile->lf = lf;
2980 do {
2981 for (; (line = ParseReadLine()) != NULL; ) {
2982 if (DEBUG(PARSE))
2983 fprintf(debug_file, "ParseReadLine (%d): '%s'\n",
2984 curFile->lineno, line);
2985 if (*line == '.') {
2987 * Lines that begin with the special character may be
2988 * include or undef directives.
2989 * On the other hand they can be suffix rules (.c.o: ...)
2990 * or just dependencies for filenames that start '.'.
2992 for (cp = line + 1; isspace((unsigned char)*cp); cp++) {
2993 continue;
2995 if (strncmp(cp, "include", 7) == 0 ||
2996 ((cp[0] == 'd' || cp[0] == 's' || cp[0] == '-') &&
2997 strncmp(&cp[1], "include", 7) == 0)) {
2998 ParseDoInclude(cp);
2999 continue;
3001 if (strncmp(cp, "undef", 5) == 0) {
3002 char *cp2;
3003 for (cp += 5; isspace((unsigned char) *cp); cp++)
3004 continue;
3005 for (cp2 = cp; !isspace((unsigned char) *cp2) &&
3006 (*cp2 != '\0'); cp2++)
3007 continue;
3008 *cp2 = '\0';
3009 Var_Delete(cp, VAR_GLOBAL);
3010 continue;
3011 } else if (strncmp(cp, "export", 6) == 0) {
3012 for (cp += 6; isspace((unsigned char) *cp); cp++)
3013 continue;
3014 Var_Export(cp, 1);
3015 continue;
3016 } else if (strncmp(cp, "unexport", 8) == 0) {
3017 Var_UnExport(cp);
3018 continue;
3019 } else if (strncmp(cp, "info", 4) == 0 ||
3020 strncmp(cp, "error", 5) == 0 ||
3021 strncmp(cp, "warning", 7) == 0) {
3022 if (ParseMessage(cp))
3023 continue;
3027 if (*line == '\t') {
3029 * If a line starts with a tab, it can only hope to be
3030 * a creation command.
3032 cp = line + 1;
3033 shellCommand:
3034 for (; isspace ((unsigned char)*cp); cp++) {
3035 continue;
3037 if (*cp) {
3038 if (!inLine)
3039 Parse_Error(PARSE_FATAL,
3040 "Unassociated shell command \"%s\"",
3041 cp);
3043 * So long as it's not a blank line and we're actually
3044 * in a dependency spec, add the command to the list of
3045 * commands of all targets in the dependency spec
3047 if (targets) {
3048 cp = bmake_strdup(cp);
3049 Lst_ForEach(targets, ParseAddCmd, cp);
3050 #ifdef CLEANUP
3051 Lst_AtEnd(targCmds, cp);
3052 #endif
3055 continue;
3058 #ifdef SYSVINCLUDE
3059 if (((strncmp(line, "include", 7) == 0 &&
3060 isspace((unsigned char) line[7])) ||
3061 ((line[0] == 's' || line[0] == '-') &&
3062 strncmp(&line[1], "include", 7) == 0 &&
3063 isspace((unsigned char) line[8]))) &&
3064 strchr(line, ':') == NULL) {
3066 * It's an S3/S5-style "include".
3068 ParseTraditionalInclude(line);
3069 continue;
3071 #endif
3072 #ifdef GMAKEEXPORT
3073 if (strncmp(line, "export", 6) == 0 &&
3074 isspace((unsigned char) line[6]) &&
3075 strchr(line, ':') == NULL) {
3077 * It's a Gmake "export".
3079 ParseGmakeExport(line);
3080 continue;
3082 #endif
3083 if (Parse_IsVar(line)) {
3084 ParseFinishLine();
3085 Parse_DoVar(line, VAR_GLOBAL);
3086 continue;
3089 #ifndef POSIX
3091 * To make life easier on novices, if the line is indented we
3092 * first make sure the line has a dependency operator in it.
3093 * If it doesn't have an operator and we're in a dependency
3094 * line's script, we assume it's actually a shell command
3095 * and add it to the current list of targets.
3097 cp = line;
3098 if (isspace((unsigned char) line[0])) {
3099 while ((*cp != '\0') && isspace((unsigned char) *cp))
3100 cp++;
3101 while (*cp && (ParseIsEscaped(line, cp) ||
3102 (*cp != ':') && (*cp != '!'))) {
3103 cp++;
3105 if (*cp == '\0') {
3106 if (inLine) {
3107 Parse_Error(PARSE_WARNING,
3108 "Shell command needs a leading tab");
3109 goto shellCommand;
3113 #endif
3114 ParseFinishLine();
3117 * For some reason - probably to make the parser impossible -
3118 * a ';' can be used to separate commands from dependencies.
3119 * Attempt to avoid ';' inside substitution patterns.
3122 int level = 0;
3124 for (cp = line; *cp != 0; cp++) {
3125 if (*cp == '\\' && cp[1] != 0) {
3126 cp++;
3127 continue;
3129 if (*cp == '$' &&
3130 (cp[1] == '(' || cp[1] == '{')) {
3131 level++;
3132 continue;
3134 if (level > 0) {
3135 if (*cp == ')' || *cp == '}') {
3136 level--;
3137 continue;
3139 } else if (*cp == ';') {
3140 break;
3144 if (*cp != 0)
3145 /* Terminate the dependency list at the ';' */
3146 *cp++ = 0;
3147 else
3148 cp = NULL;
3151 * We now know it's a dependency line so it needs to have all
3152 * variables expanded before being parsed. Tell the variable
3153 * module to complain if some variable is undefined...
3155 line = Var_Subst(NULL, line, VAR_CMD, VARF_UNDEFERR|VARF_WANTRES);
3158 * Need a non-circular list for the target nodes
3160 if (targets)
3161 Lst_Destroy(targets, NULL);
3163 targets = Lst_Init(FALSE);
3164 inLine = TRUE;
3166 ParseDoDependency(line);
3167 free(line);
3169 /* If there were commands after a ';', add them now */
3170 if (cp != NULL) {
3171 goto shellCommand;
3175 * Reached EOF, but it may be just EOF of an include file...
3177 } while (ParseEOF() == CONTINUE);
3179 if (fatals) {
3180 (void)fflush(stdout);
3181 (void)fprintf(stderr,
3182 "%s: Fatal errors encountered -- cannot continue",
3183 progname);
3184 PrintOnError(NULL, NULL);
3185 exit(1);
3190 *---------------------------------------------------------------------
3191 * Parse_Init --
3192 * initialize the parsing module
3194 * Results:
3195 * none
3197 * Side Effects:
3198 * the parseIncPath list is initialized...
3199 *---------------------------------------------------------------------
3201 void
3202 Parse_Init(void)
3204 mainNode = NULL;
3205 parseIncPath = Lst_Init(FALSE);
3206 sysIncPath = Lst_Init(FALSE);
3207 defIncPath = Lst_Init(FALSE);
3208 includes = Lst_Init(FALSE);
3209 #ifdef CLEANUP
3210 targCmds = Lst_Init(FALSE);
3211 #endif
3214 void
3215 Parse_End(void)
3217 #ifdef CLEANUP
3218 Lst_Destroy(targCmds, (FreeProc *)free);
3219 if (targets)
3220 Lst_Destroy(targets, NULL);
3221 Lst_Destroy(defIncPath, Dir_Destroy);
3222 Lst_Destroy(sysIncPath, Dir_Destroy);
3223 Lst_Destroy(parseIncPath, Dir_Destroy);
3224 Lst_Destroy(includes, NULL); /* Should be empty now */
3225 #endif
3230 *-----------------------------------------------------------------------
3231 * Parse_MainName --
3232 * Return a Lst of the main target to create for main()'s sake. If
3233 * no such target exists, we Punt with an obnoxious error message.
3235 * Results:
3236 * A Lst of the single node to create.
3238 * Side Effects:
3239 * None.
3241 *-----------------------------------------------------------------------
3244 Parse_MainName(void)
3246 Lst mainList; /* result list */
3248 mainList = Lst_Init(FALSE);
3250 if (mainNode == NULL) {
3251 Punt("no target to make.");
3252 /*NOTREACHED*/
3253 } else if (mainNode->type & OP_DOUBLEDEP) {
3254 (void)Lst_AtEnd(mainList, mainNode);
3255 Lst_Concat(mainList, mainNode->cohorts, LST_CONCNEW);
3257 else
3258 (void)Lst_AtEnd(mainList, mainNode);
3259 Var_Append(".TARGETS", mainNode->name, VAR_GLOBAL);
3260 return (mainList);
3264 *-----------------------------------------------------------------------
3265 * ParseMark --
3266 * Add the filename and lineno to the GNode so that we remember
3267 * where it was first defined.
3269 * Side Effects:
3270 * None.
3272 *-----------------------------------------------------------------------
3274 static void
3275 ParseMark(GNode *gn)
3277 gn->fname = curFile->fname;
3278 gn->lineno = curFile->lineno;